xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 1956a48d273dca31d379b3b032bf772040d3c93d)
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/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/Pass.h"
115 #include "llvm/Support/Casting.h"
116 #include "llvm/Support/CommandLine.h"
117 #include "llvm/Support/Compiler.h"
118 #include "llvm/Support/Debug.h"
119 #include "llvm/Support/ErrorHandling.h"
120 #include "llvm/Support/KnownBits.h"
121 #include "llvm/Support/SaveAndRestore.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <climits>
126 #include <cstddef>
127 #include <cstdint>
128 #include <cstdlib>
129 #include <map>
130 #include <memory>
131 #include <tuple>
132 #include <utility>
133 #include <vector>
134 
135 using namespace llvm;
136 
137 #define DEBUG_TYPE "scalar-evolution"
138 
139 STATISTIC(NumArrayLenItCounts,
140           "Number of trip counts computed with array length");
141 STATISTIC(NumTripCountsComputed,
142           "Number of loops with predictable loop counts");
143 STATISTIC(NumTripCountsNotComputed,
144           "Number of loops without predictable loop counts");
145 STATISTIC(NumBruteForceTripCountsComputed,
146           "Number of loops with trip counts computed by force");
147 
148 static cl::opt<unsigned>
149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
150                         cl::desc("Maximum number of iterations SCEV will "
151                                  "symbolically execute a constant "
152                                  "derived loop"),
153                         cl::init(100));
154 
155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
156 static cl::opt<bool> VerifySCEV(
157     "verify-scev", cl::Hidden,
158     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159 static cl::opt<bool>
160     VerifySCEVMap("verify-scev-maps", cl::Hidden,
161                   cl::desc("Verify no dangling value in ScalarEvolution's "
162                            "ExprValueMap (slow)"));
163 
164 static cl::opt<unsigned> MulOpsInlineThreshold(
165     "scev-mulops-inline-threshold", cl::Hidden,
166     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
167     cl::init(32));
168 
169 static cl::opt<unsigned> AddOpsInlineThreshold(
170     "scev-addops-inline-threshold", cl::Hidden,
171     cl::desc("Threshold for inlining addition operands into a SCEV"),
172     cl::init(500));
173 
174 static cl::opt<unsigned> MaxSCEVCompareDepth(
175     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
176     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
177     cl::init(32));
178 
179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
180     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
181     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
182     cl::init(2));
183 
184 static cl::opt<unsigned> MaxValueCompareDepth(
185     "scalar-evolution-max-value-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive value complexity comparisons"),
187     cl::init(2));
188 
189 static cl::opt<unsigned>
190     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
191                   cl::desc("Maximum depth of recursive arithmetics"),
192                   cl::init(32));
193 
194 static cl::opt<unsigned> MaxConstantEvolvingDepth(
195     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
197 
198 static cl::opt<unsigned>
199     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
200                 cl::desc("Maximum depth of recursive SExt/ZExt"),
201                 cl::init(8));
202 
203 static cl::opt<unsigned>
204     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
205                   cl::desc("Max coefficients in AddRec during evolving"),
206                   cl::init(16));
207 
208 //===----------------------------------------------------------------------===//
209 //                           SCEV class definitions
210 //===----------------------------------------------------------------------===//
211 
212 //===----------------------------------------------------------------------===//
213 // Implementation of the SCEV class.
214 //
215 
216 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
217 LLVM_DUMP_METHOD void SCEV::dump() const {
218   print(dbgs());
219   dbgs() << '\n';
220 }
221 #endif
222 
223 void SCEV::print(raw_ostream &OS) const {
224   switch (static_cast<SCEVTypes>(getSCEVType())) {
225   case scConstant:
226     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
227     return;
228   case scTruncate: {
229     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
230     const SCEV *Op = Trunc->getOperand();
231     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
232        << *Trunc->getType() << ")";
233     return;
234   }
235   case scZeroExtend: {
236     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
237     const SCEV *Op = ZExt->getOperand();
238     OS << "(zext " << *Op->getType() << " " << *Op << " to "
239        << *ZExt->getType() << ")";
240     return;
241   }
242   case scSignExtend: {
243     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
244     const SCEV *Op = SExt->getOperand();
245     OS << "(sext " << *Op->getType() << " " << *Op << " to "
246        << *SExt->getType() << ")";
247     return;
248   }
249   case scAddRecExpr: {
250     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
251     OS << "{" << *AR->getOperand(0);
252     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
253       OS << ",+," << *AR->getOperand(i);
254     OS << "}<";
255     if (AR->hasNoUnsignedWrap())
256       OS << "nuw><";
257     if (AR->hasNoSignedWrap())
258       OS << "nsw><";
259     if (AR->hasNoSelfWrap() &&
260         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
261       OS << "nw><";
262     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
263     OS << ">";
264     return;
265   }
266   case scAddExpr:
267   case scMulExpr:
268   case scUMaxExpr:
269   case scSMaxExpr: {
270     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
271     const char *OpStr = nullptr;
272     switch (NAry->getSCEVType()) {
273     case scAddExpr: OpStr = " + "; break;
274     case scMulExpr: OpStr = " * "; break;
275     case scUMaxExpr: OpStr = " umax "; break;
276     case scSMaxExpr: OpStr = " smax "; break;
277     }
278     OS << "(";
279     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
280          I != E; ++I) {
281       OS << **I;
282       if (std::next(I) != E)
283         OS << OpStr;
284     }
285     OS << ")";
286     switch (NAry->getSCEVType()) {
287     case scAddExpr:
288     case scMulExpr:
289       if (NAry->hasNoUnsignedWrap())
290         OS << "<nuw>";
291       if (NAry->hasNoSignedWrap())
292         OS << "<nsw>";
293     }
294     return;
295   }
296   case scUDivExpr: {
297     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
298     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
299     return;
300   }
301   case scUnknown: {
302     const SCEVUnknown *U = cast<SCEVUnknown>(this);
303     Type *AllocTy;
304     if (U->isSizeOf(AllocTy)) {
305       OS << "sizeof(" << *AllocTy << ")";
306       return;
307     }
308     if (U->isAlignOf(AllocTy)) {
309       OS << "alignof(" << *AllocTy << ")";
310       return;
311     }
312 
313     Type *CTy;
314     Constant *FieldNo;
315     if (U->isOffsetOf(CTy, FieldNo)) {
316       OS << "offsetof(" << *CTy << ", ";
317       FieldNo->printAsOperand(OS, false);
318       OS << ")";
319       return;
320     }
321 
322     // Otherwise just print it normally.
323     U->getValue()->printAsOperand(OS, false);
324     return;
325   }
326   case scCouldNotCompute:
327     OS << "***COULDNOTCOMPUTE***";
328     return;
329   }
330   llvm_unreachable("Unknown SCEV kind!");
331 }
332 
333 Type *SCEV::getType() const {
334   switch (static_cast<SCEVTypes>(getSCEVType())) {
335   case scConstant:
336     return cast<SCEVConstant>(this)->getType();
337   case scTruncate:
338   case scZeroExtend:
339   case scSignExtend:
340     return cast<SCEVCastExpr>(this)->getType();
341   case scAddRecExpr:
342   case scMulExpr:
343   case scUMaxExpr:
344   case scSMaxExpr:
345     return cast<SCEVNAryExpr>(this)->getType();
346   case scAddExpr:
347     return cast<SCEVAddExpr>(this)->getType();
348   case scUDivExpr:
349     return cast<SCEVUDivExpr>(this)->getType();
350   case scUnknown:
351     return cast<SCEVUnknown>(this)->getType();
352   case scCouldNotCompute:
353     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
354   }
355   llvm_unreachable("Unknown SCEV kind!");
356 }
357 
358 bool SCEV::isZero() const {
359   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
360     return SC->getValue()->isZero();
361   return false;
362 }
363 
364 bool SCEV::isOne() const {
365   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
366     return SC->getValue()->isOne();
367   return false;
368 }
369 
370 bool SCEV::isAllOnesValue() const {
371   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
372     return SC->getValue()->isMinusOne();
373   return false;
374 }
375 
376 bool SCEV::isNonConstantNegative() const {
377   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
378   if (!Mul) return false;
379 
380   // If there is a constant factor, it will be first.
381   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
382   if (!SC) return false;
383 
384   // Return true if the value is negative, this matches things like (-42 * V).
385   return SC->getAPInt().isNegative();
386 }
387 
388 SCEVCouldNotCompute::SCEVCouldNotCompute() :
389   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
390 
391 bool SCEVCouldNotCompute::classof(const SCEV *S) {
392   return S->getSCEVType() == scCouldNotCompute;
393 }
394 
395 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
396   FoldingSetNodeID ID;
397   ID.AddInteger(scConstant);
398   ID.AddPointer(V);
399   void *IP = nullptr;
400   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
401   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
402   UniqueSCEVs.InsertNode(S, IP);
403   return S;
404 }
405 
406 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
407   return getConstant(ConstantInt::get(getContext(), Val));
408 }
409 
410 const SCEV *
411 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
412   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
413   return getConstant(ConstantInt::get(ITy, V, isSigned));
414 }
415 
416 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
417                            unsigned SCEVTy, const SCEV *op, Type *ty)
418   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
419 
420 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
421                                    const SCEV *op, Type *ty)
422   : SCEVCastExpr(ID, scTruncate, op, ty) {
423   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
424          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
425          "Cannot truncate non-integer value!");
426 }
427 
428 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
429                                        const SCEV *op, Type *ty)
430   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
431   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
432          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
433          "Cannot zero extend non-integer value!");
434 }
435 
436 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
437                                        const SCEV *op, Type *ty)
438   : SCEVCastExpr(ID, scSignExtend, op, ty) {
439   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
440          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
441          "Cannot sign extend non-integer value!");
442 }
443 
444 void SCEVUnknown::deleted() {
445   // Clear this SCEVUnknown from various maps.
446   SE->forgetMemoizedResults(this);
447 
448   // Remove this SCEVUnknown from the uniquing map.
449   SE->UniqueSCEVs.RemoveNode(this);
450 
451   // Release the value.
452   setValPtr(nullptr);
453 }
454 
455 void SCEVUnknown::allUsesReplacedWith(Value *New) {
456   // Remove this SCEVUnknown from the uniquing map.
457   SE->UniqueSCEVs.RemoveNode(this);
458 
459   // Update this SCEVUnknown to point to the new value. This is needed
460   // because there may still be outstanding SCEVs which still point to
461   // this SCEVUnknown.
462   setValPtr(New);
463 }
464 
465 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
466   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
467     if (VCE->getOpcode() == Instruction::PtrToInt)
468       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
469         if (CE->getOpcode() == Instruction::GetElementPtr &&
470             CE->getOperand(0)->isNullValue() &&
471             CE->getNumOperands() == 2)
472           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
473             if (CI->isOne()) {
474               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
475                                  ->getElementType();
476               return true;
477             }
478 
479   return false;
480 }
481 
482 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
483   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
484     if (VCE->getOpcode() == Instruction::PtrToInt)
485       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
486         if (CE->getOpcode() == Instruction::GetElementPtr &&
487             CE->getOperand(0)->isNullValue()) {
488           Type *Ty =
489             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
490           if (StructType *STy = dyn_cast<StructType>(Ty))
491             if (!STy->isPacked() &&
492                 CE->getNumOperands() == 3 &&
493                 CE->getOperand(1)->isNullValue()) {
494               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
495                 if (CI->isOne() &&
496                     STy->getNumElements() == 2 &&
497                     STy->getElementType(0)->isIntegerTy(1)) {
498                   AllocTy = STy->getElementType(1);
499                   return true;
500                 }
501             }
502         }
503 
504   return false;
505 }
506 
507 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
508   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
509     if (VCE->getOpcode() == Instruction::PtrToInt)
510       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
511         if (CE->getOpcode() == Instruction::GetElementPtr &&
512             CE->getNumOperands() == 3 &&
513             CE->getOperand(0)->isNullValue() &&
514             CE->getOperand(1)->isNullValue()) {
515           Type *Ty =
516             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
517           // Ignore vector types here so that ScalarEvolutionExpander doesn't
518           // emit getelementptrs that index into vectors.
519           if (Ty->isStructTy() || Ty->isArrayTy()) {
520             CTy = Ty;
521             FieldNo = CE->getOperand(2);
522             return true;
523           }
524         }
525 
526   return false;
527 }
528 
529 //===----------------------------------------------------------------------===//
530 //                               SCEV Utilities
531 //===----------------------------------------------------------------------===//
532 
533 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
534 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
535 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
536 /// have been previously deemed to be "equally complex" by this routine.  It is
537 /// intended to avoid exponential time complexity in cases like:
538 ///
539 ///   %a = f(%x, %y)
540 ///   %b = f(%a, %a)
541 ///   %c = f(%b, %b)
542 ///
543 ///   %d = f(%x, %y)
544 ///   %e = f(%d, %d)
545 ///   %f = f(%e, %e)
546 ///
547 ///   CompareValueComplexity(%f, %c)
548 ///
549 /// Since we do not continue running this routine on expression trees once we
550 /// have seen unequal values, there is no need to track them in the cache.
551 static int
552 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
553                        const LoopInfo *const LI, Value *LV, Value *RV,
554                        unsigned Depth) {
555   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
556     return 0;
557 
558   // Order pointer values after integer values. This helps SCEVExpander form
559   // GEPs.
560   bool LIsPointer = LV->getType()->isPointerTy(),
561        RIsPointer = RV->getType()->isPointerTy();
562   if (LIsPointer != RIsPointer)
563     return (int)LIsPointer - (int)RIsPointer;
564 
565   // Compare getValueID values.
566   unsigned LID = LV->getValueID(), RID = RV->getValueID();
567   if (LID != RID)
568     return (int)LID - (int)RID;
569 
570   // Sort arguments by their position.
571   if (const auto *LA = dyn_cast<Argument>(LV)) {
572     const auto *RA = cast<Argument>(RV);
573     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
574     return (int)LArgNo - (int)RArgNo;
575   }
576 
577   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
578     const auto *RGV = cast<GlobalValue>(RV);
579 
580     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
581       auto LT = GV->getLinkage();
582       return !(GlobalValue::isPrivateLinkage(LT) ||
583                GlobalValue::isInternalLinkage(LT));
584     };
585 
586     // Use the names to distinguish the two values, but only if the
587     // names are semantically important.
588     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
589       return LGV->getName().compare(RGV->getName());
590   }
591 
592   // For instructions, compare their loop depth, and their operand count.  This
593   // is pretty loose.
594   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
595     const auto *RInst = cast<Instruction>(RV);
596 
597     // Compare loop depths.
598     const BasicBlock *LParent = LInst->getParent(),
599                      *RParent = RInst->getParent();
600     if (LParent != RParent) {
601       unsigned LDepth = LI->getLoopDepth(LParent),
602                RDepth = LI->getLoopDepth(RParent);
603       if (LDepth != RDepth)
604         return (int)LDepth - (int)RDepth;
605     }
606 
607     // Compare the number of operands.
608     unsigned LNumOps = LInst->getNumOperands(),
609              RNumOps = RInst->getNumOperands();
610     if (LNumOps != RNumOps)
611       return (int)LNumOps - (int)RNumOps;
612 
613     for (unsigned Idx : seq(0u, LNumOps)) {
614       int Result =
615           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
616                                  RInst->getOperand(Idx), Depth + 1);
617       if (Result != 0)
618         return Result;
619     }
620   }
621 
622   EqCacheValue.unionSets(LV, RV);
623   return 0;
624 }
625 
626 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
627 // than RHS, respectively. A three-way result allows recursive comparisons to be
628 // more efficient.
629 static int CompareSCEVComplexity(
630     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
631     EquivalenceClasses<const Value *> &EqCacheValue,
632     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
633     DominatorTree &DT, unsigned Depth = 0) {
634   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
635   if (LHS == RHS)
636     return 0;
637 
638   // Primarily, sort the SCEVs by their getSCEVType().
639   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
640   if (LType != RType)
641     return (int)LType - (int)RType;
642 
643   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
644     return 0;
645   // Aside from the getSCEVType() ordering, the particular ordering
646   // isn't very important except that it's beneficial to be consistent,
647   // so that (a + b) and (b + a) don't end up as different expressions.
648   switch (static_cast<SCEVTypes>(LType)) {
649   case scUnknown: {
650     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
651     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
652 
653     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
654                                    RU->getValue(), Depth + 1);
655     if (X == 0)
656       EqCacheSCEV.unionSets(LHS, RHS);
657     return X;
658   }
659 
660   case scConstant: {
661     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
662     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
663 
664     // Compare constant values.
665     const APInt &LA = LC->getAPInt();
666     const APInt &RA = RC->getAPInt();
667     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
668     if (LBitWidth != RBitWidth)
669       return (int)LBitWidth - (int)RBitWidth;
670     return LA.ult(RA) ? -1 : 1;
671   }
672 
673   case scAddRecExpr: {
674     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
675     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
676 
677     // There is always a dominance between two recs that are used by one SCEV,
678     // so we can safely sort recs by loop header dominance. We require such
679     // order in getAddExpr.
680     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
681     if (LLoop != RLoop) {
682       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
683       assert(LHead != RHead && "Two loops share the same header?");
684       if (DT.dominates(LHead, RHead))
685         return 1;
686       else
687         assert(DT.dominates(RHead, LHead) &&
688                "No dominance between recurrences used by one SCEV?");
689       return -1;
690     }
691 
692     // Addrec complexity grows with operand count.
693     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
694     if (LNumOps != RNumOps)
695       return (int)LNumOps - (int)RNumOps;
696 
697     // Compare NoWrap flags.
698     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
699       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
700 
701     // Lexicographically compare.
702     for (unsigned i = 0; i != LNumOps; ++i) {
703       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
704                                     LA->getOperand(i), RA->getOperand(i), DT,
705                                     Depth + 1);
706       if (X != 0)
707         return X;
708     }
709     EqCacheSCEV.unionSets(LHS, RHS);
710     return 0;
711   }
712 
713   case scAddExpr:
714   case scMulExpr:
715   case scSMaxExpr:
716   case scUMaxExpr: {
717     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
718     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
719 
720     // Lexicographically compare n-ary expressions.
721     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
722     if (LNumOps != RNumOps)
723       return (int)LNumOps - (int)RNumOps;
724 
725     // Compare NoWrap flags.
726     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
727       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
728 
729     for (unsigned i = 0; i != LNumOps; ++i) {
730       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
731                                     LC->getOperand(i), RC->getOperand(i), DT,
732                                     Depth + 1);
733       if (X != 0)
734         return X;
735     }
736     EqCacheSCEV.unionSets(LHS, RHS);
737     return 0;
738   }
739 
740   case scUDivExpr: {
741     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
742     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
743 
744     // Lexicographically compare udiv expressions.
745     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
746                                   RC->getLHS(), DT, Depth + 1);
747     if (X != 0)
748       return X;
749     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
750                               RC->getRHS(), DT, Depth + 1);
751     if (X == 0)
752       EqCacheSCEV.unionSets(LHS, RHS);
753     return X;
754   }
755 
756   case scTruncate:
757   case scZeroExtend:
758   case scSignExtend: {
759     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
760     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
761 
762     // Compare cast expressions by operand.
763     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
764                                   LC->getOperand(), RC->getOperand(), DT,
765                                   Depth + 1);
766     if (X == 0)
767       EqCacheSCEV.unionSets(LHS, RHS);
768     return X;
769   }
770 
771   case scCouldNotCompute:
772     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
773   }
774   llvm_unreachable("Unknown SCEV kind!");
775 }
776 
777 /// Given a list of SCEV objects, order them by their complexity, and group
778 /// objects of the same complexity together by value.  When this routine is
779 /// finished, we know that any duplicates in the vector are consecutive and that
780 /// complexity is monotonically increasing.
781 ///
782 /// Note that we go take special precautions to ensure that we get deterministic
783 /// results from this routine.  In other words, we don't want the results of
784 /// this to depend on where the addresses of various SCEV objects happened to
785 /// land in memory.
786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
787                               LoopInfo *LI, DominatorTree &DT) {
788   if (Ops.size() < 2) return;  // Noop
789 
790   EquivalenceClasses<const SCEV *> EqCacheSCEV;
791   EquivalenceClasses<const Value *> EqCacheValue;
792   if (Ops.size() == 2) {
793     // This is the common case, which also happens to be trivially simple.
794     // Special case it.
795     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
796     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
797       std::swap(LHS, RHS);
798     return;
799   }
800 
801   // Do the rough sort by complexity.
802   std::stable_sort(Ops.begin(), Ops.end(),
803                    [&](const SCEV *LHS, const SCEV *RHS) {
804                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
805                                                   LHS, RHS, DT) < 0;
806                    });
807 
808   // Now that we are sorted by complexity, group elements of the same
809   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
810   // be extremely short in practice.  Note that we take this approach because we
811   // do not want to depend on the addresses of the objects we are grouping.
812   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
813     const SCEV *S = Ops[i];
814     unsigned Complexity = S->getSCEVType();
815 
816     // If there are any objects of the same complexity and same value as this
817     // one, group them.
818     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
819       if (Ops[j] == S) { // Found a duplicate.
820         // Move it to immediately after i'th element.
821         std::swap(Ops[i+1], Ops[j]);
822         ++i;   // no need to rescan it.
823         if (i == e-2) return;  // Done!
824       }
825     }
826   }
827 }
828 
829 // Returns the size of the SCEV S.
830 static inline int sizeOfSCEV(const SCEV *S) {
831   struct FindSCEVSize {
832     int Size = 0;
833 
834     FindSCEVSize() = default;
835 
836     bool follow(const SCEV *S) {
837       ++Size;
838       // Keep looking at all operands of S.
839       return true;
840     }
841 
842     bool isDone() const {
843       return false;
844     }
845   };
846 
847   FindSCEVSize F;
848   SCEVTraversal<FindSCEVSize> ST(F);
849   ST.visitAll(S);
850   return F.Size;
851 }
852 
853 namespace {
854 
855 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
856 public:
857   // Computes the Quotient and Remainder of the division of Numerator by
858   // Denominator.
859   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
860                      const SCEV *Denominator, const SCEV **Quotient,
861                      const SCEV **Remainder) {
862     assert(Numerator && Denominator && "Uninitialized SCEV");
863 
864     SCEVDivision D(SE, Numerator, Denominator);
865 
866     // Check for the trivial case here to avoid having to check for it in the
867     // rest of the code.
868     if (Numerator == Denominator) {
869       *Quotient = D.One;
870       *Remainder = D.Zero;
871       return;
872     }
873 
874     if (Numerator->isZero()) {
875       *Quotient = D.Zero;
876       *Remainder = D.Zero;
877       return;
878     }
879 
880     // A simple case when N/1. The quotient is N.
881     if (Denominator->isOne()) {
882       *Quotient = Numerator;
883       *Remainder = D.Zero;
884       return;
885     }
886 
887     // Split the Denominator when it is a product.
888     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
889       const SCEV *Q, *R;
890       *Quotient = Numerator;
891       for (const SCEV *Op : T->operands()) {
892         divide(SE, *Quotient, Op, &Q, &R);
893         *Quotient = Q;
894 
895         // Bail out when the Numerator is not divisible by one of the terms of
896         // the Denominator.
897         if (!R->isZero()) {
898           *Quotient = D.Zero;
899           *Remainder = Numerator;
900           return;
901         }
902       }
903       *Remainder = D.Zero;
904       return;
905     }
906 
907     D.visit(Numerator);
908     *Quotient = D.Quotient;
909     *Remainder = D.Remainder;
910   }
911 
912   // Except in the trivial case described above, we do not know how to divide
913   // Expr by Denominator for the following functions with empty implementation.
914   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
915   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
916   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
917   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
918   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
919   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
920   void visitUnknown(const SCEVUnknown *Numerator) {}
921   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
922 
923   void visitConstant(const SCEVConstant *Numerator) {
924     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
925       APInt NumeratorVal = Numerator->getAPInt();
926       APInt DenominatorVal = D->getAPInt();
927       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
928       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
929 
930       if (NumeratorBW > DenominatorBW)
931         DenominatorVal = DenominatorVal.sext(NumeratorBW);
932       else if (NumeratorBW < DenominatorBW)
933         NumeratorVal = NumeratorVal.sext(DenominatorBW);
934 
935       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
936       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
937       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
938       Quotient = SE.getConstant(QuotientVal);
939       Remainder = SE.getConstant(RemainderVal);
940       return;
941     }
942   }
943 
944   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
945     const SCEV *StartQ, *StartR, *StepQ, *StepR;
946     if (!Numerator->isAffine())
947       return cannotDivide(Numerator);
948     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
949     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
950     // Bail out if the types do not match.
951     Type *Ty = Denominator->getType();
952     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
953         Ty != StepQ->getType() || Ty != StepR->getType())
954       return cannotDivide(Numerator);
955     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
956                                 Numerator->getNoWrapFlags());
957     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
958                                  Numerator->getNoWrapFlags());
959   }
960 
961   void visitAddExpr(const SCEVAddExpr *Numerator) {
962     SmallVector<const SCEV *, 2> Qs, Rs;
963     Type *Ty = Denominator->getType();
964 
965     for (const SCEV *Op : Numerator->operands()) {
966       const SCEV *Q, *R;
967       divide(SE, Op, Denominator, &Q, &R);
968 
969       // Bail out if types do not match.
970       if (Ty != Q->getType() || Ty != R->getType())
971         return cannotDivide(Numerator);
972 
973       Qs.push_back(Q);
974       Rs.push_back(R);
975     }
976 
977     if (Qs.size() == 1) {
978       Quotient = Qs[0];
979       Remainder = Rs[0];
980       return;
981     }
982 
983     Quotient = SE.getAddExpr(Qs);
984     Remainder = SE.getAddExpr(Rs);
985   }
986 
987   void visitMulExpr(const SCEVMulExpr *Numerator) {
988     SmallVector<const SCEV *, 2> Qs;
989     Type *Ty = Denominator->getType();
990 
991     bool FoundDenominatorTerm = false;
992     for (const SCEV *Op : Numerator->operands()) {
993       // Bail out if types do not match.
994       if (Ty != Op->getType())
995         return cannotDivide(Numerator);
996 
997       if (FoundDenominatorTerm) {
998         Qs.push_back(Op);
999         continue;
1000       }
1001 
1002       // Check whether Denominator divides one of the product operands.
1003       const SCEV *Q, *R;
1004       divide(SE, Op, Denominator, &Q, &R);
1005       if (!R->isZero()) {
1006         Qs.push_back(Op);
1007         continue;
1008       }
1009 
1010       // Bail out if types do not match.
1011       if (Ty != Q->getType())
1012         return cannotDivide(Numerator);
1013 
1014       FoundDenominatorTerm = true;
1015       Qs.push_back(Q);
1016     }
1017 
1018     if (FoundDenominatorTerm) {
1019       Remainder = Zero;
1020       if (Qs.size() == 1)
1021         Quotient = Qs[0];
1022       else
1023         Quotient = SE.getMulExpr(Qs);
1024       return;
1025     }
1026 
1027     if (!isa<SCEVUnknown>(Denominator))
1028       return cannotDivide(Numerator);
1029 
1030     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1031     ValueToValueMap RewriteMap;
1032     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1033         cast<SCEVConstant>(Zero)->getValue();
1034     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1035 
1036     if (Remainder->isZero()) {
1037       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1038       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1039           cast<SCEVConstant>(One)->getValue();
1040       Quotient =
1041           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1042       return;
1043     }
1044 
1045     // Quotient is (Numerator - Remainder) divided by Denominator.
1046     const SCEV *Q, *R;
1047     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1048     // This SCEV does not seem to simplify: fail the division here.
1049     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1050       return cannotDivide(Numerator);
1051     divide(SE, Diff, Denominator, &Q, &R);
1052     if (R != Zero)
1053       return cannotDivide(Numerator);
1054     Quotient = Q;
1055   }
1056 
1057 private:
1058   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1059                const SCEV *Denominator)
1060       : SE(S), Denominator(Denominator) {
1061     Zero = SE.getZero(Denominator->getType());
1062     One = SE.getOne(Denominator->getType());
1063 
1064     // We generally do not know how to divide Expr by Denominator. We
1065     // initialize the division to a "cannot divide" state to simplify the rest
1066     // of the code.
1067     cannotDivide(Numerator);
1068   }
1069 
1070   // Convenience function for giving up on the division. We set the quotient to
1071   // be equal to zero and the remainder to be equal to the numerator.
1072   void cannotDivide(const SCEV *Numerator) {
1073     Quotient = Zero;
1074     Remainder = Numerator;
1075   }
1076 
1077   ScalarEvolution &SE;
1078   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1079 };
1080 
1081 } // end anonymous namespace
1082 
1083 //===----------------------------------------------------------------------===//
1084 //                      Simple SCEV method implementations
1085 //===----------------------------------------------------------------------===//
1086 
1087 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1088 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1089                                        ScalarEvolution &SE,
1090                                        Type *ResultTy) {
1091   // Handle the simplest case efficiently.
1092   if (K == 1)
1093     return SE.getTruncateOrZeroExtend(It, ResultTy);
1094 
1095   // We are using the following formula for BC(It, K):
1096   //
1097   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1098   //
1099   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1100   // overflow.  Hence, we must assure that the result of our computation is
1101   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1102   // safe in modular arithmetic.
1103   //
1104   // However, this code doesn't use exactly that formula; the formula it uses
1105   // is something like the following, where T is the number of factors of 2 in
1106   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1107   // exponentiation:
1108   //
1109   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1110   //
1111   // This formula is trivially equivalent to the previous formula.  However,
1112   // this formula can be implemented much more efficiently.  The trick is that
1113   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1114   // arithmetic.  To do exact division in modular arithmetic, all we have
1115   // to do is multiply by the inverse.  Therefore, this step can be done at
1116   // width W.
1117   //
1118   // The next issue is how to safely do the division by 2^T.  The way this
1119   // is done is by doing the multiplication step at a width of at least W + T
1120   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1121   // when we perform the division by 2^T (which is equivalent to a right shift
1122   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1123   // truncated out after the division by 2^T.
1124   //
1125   // In comparison to just directly using the first formula, this technique
1126   // is much more efficient; using the first formula requires W * K bits,
1127   // but this formula less than W + K bits. Also, the first formula requires
1128   // a division step, whereas this formula only requires multiplies and shifts.
1129   //
1130   // It doesn't matter whether the subtraction step is done in the calculation
1131   // width or the input iteration count's width; if the subtraction overflows,
1132   // the result must be zero anyway.  We prefer here to do it in the width of
1133   // the induction variable because it helps a lot for certain cases; CodeGen
1134   // isn't smart enough to ignore the overflow, which leads to much less
1135   // efficient code if the width of the subtraction is wider than the native
1136   // register width.
1137   //
1138   // (It's possible to not widen at all by pulling out factors of 2 before
1139   // the multiplication; for example, K=2 can be calculated as
1140   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1141   // extra arithmetic, so it's not an obvious win, and it gets
1142   // much more complicated for K > 3.)
1143 
1144   // Protection from insane SCEVs; this bound is conservative,
1145   // but it probably doesn't matter.
1146   if (K > 1000)
1147     return SE.getCouldNotCompute();
1148 
1149   unsigned W = SE.getTypeSizeInBits(ResultTy);
1150 
1151   // Calculate K! / 2^T and T; we divide out the factors of two before
1152   // multiplying for calculating K! / 2^T to avoid overflow.
1153   // Other overflow doesn't matter because we only care about the bottom
1154   // W bits of the result.
1155   APInt OddFactorial(W, 1);
1156   unsigned T = 1;
1157   for (unsigned i = 3; i <= K; ++i) {
1158     APInt Mult(W, i);
1159     unsigned TwoFactors = Mult.countTrailingZeros();
1160     T += TwoFactors;
1161     Mult.lshrInPlace(TwoFactors);
1162     OddFactorial *= Mult;
1163   }
1164 
1165   // We need at least W + T bits for the multiplication step
1166   unsigned CalculationBits = W + T;
1167 
1168   // Calculate 2^T, at width T+W.
1169   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1170 
1171   // Calculate the multiplicative inverse of K! / 2^T;
1172   // this multiplication factor will perform the exact division by
1173   // K! / 2^T.
1174   APInt Mod = APInt::getSignedMinValue(W+1);
1175   APInt MultiplyFactor = OddFactorial.zext(W+1);
1176   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1177   MultiplyFactor = MultiplyFactor.trunc(W);
1178 
1179   // Calculate the product, at width T+W
1180   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1181                                                       CalculationBits);
1182   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1183   for (unsigned i = 1; i != K; ++i) {
1184     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1185     Dividend = SE.getMulExpr(Dividend,
1186                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1187   }
1188 
1189   // Divide by 2^T
1190   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1191 
1192   // Truncate the result, and divide by K! / 2^T.
1193 
1194   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1195                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1196 }
1197 
1198 /// Return the value of this chain of recurrences at the specified iteration
1199 /// number.  We can evaluate this recurrence by multiplying each element in the
1200 /// chain by the binomial coefficient corresponding to it.  In other words, we
1201 /// can evaluate {A,+,B,+,C,+,D} as:
1202 ///
1203 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1204 ///
1205 /// where BC(It, k) stands for binomial coefficient.
1206 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1207                                                 ScalarEvolution &SE) const {
1208   const SCEV *Result = getStart();
1209   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1210     // The computation is correct in the face of overflow provided that the
1211     // multiplication is performed _after_ the evaluation of the binomial
1212     // coefficient.
1213     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1214     if (isa<SCEVCouldNotCompute>(Coeff))
1215       return Coeff;
1216 
1217     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1218   }
1219   return Result;
1220 }
1221 
1222 //===----------------------------------------------------------------------===//
1223 //                    SCEV Expression folder implementations
1224 //===----------------------------------------------------------------------===//
1225 
1226 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1227                                              Type *Ty) {
1228   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1229          "This is not a truncating conversion!");
1230   assert(isSCEVable(Ty) &&
1231          "This is not a conversion to a SCEVable type!");
1232   Ty = getEffectiveSCEVType(Ty);
1233 
1234   FoldingSetNodeID ID;
1235   ID.AddInteger(scTruncate);
1236   ID.AddPointer(Op);
1237   ID.AddPointer(Ty);
1238   void *IP = nullptr;
1239   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1240 
1241   // Fold if the operand is constant.
1242   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1243     return getConstant(
1244       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1245 
1246   // trunc(trunc(x)) --> trunc(x)
1247   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1248     return getTruncateExpr(ST->getOperand(), Ty);
1249 
1250   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1251   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1252     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1253 
1254   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1255   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1256     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1257 
1258   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1259   // eliminate all the truncates, or we replace other casts with truncates.
1260   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1261     SmallVector<const SCEV *, 4> Operands;
1262     bool hasTrunc = false;
1263     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1264       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1265       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1266         hasTrunc = isa<SCEVTruncateExpr>(S);
1267       Operands.push_back(S);
1268     }
1269     if (!hasTrunc)
1270       return getAddExpr(Operands);
1271     // In spite we checked in the beginning that ID is not in the cache,
1272     // it is possible that during recursion and different modification
1273     // ID came to cache, so if we found it, just return it.
1274     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1275       return S;
1276   }
1277 
1278   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1279   // eliminate all the truncates, or we replace other casts with truncates.
1280   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1281     SmallVector<const SCEV *, 4> Operands;
1282     bool hasTrunc = false;
1283     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1284       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1285       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1286         hasTrunc = isa<SCEVTruncateExpr>(S);
1287       Operands.push_back(S);
1288     }
1289     if (!hasTrunc)
1290       return getMulExpr(Operands);
1291     // In spite we checked in the beginning that ID is not in the cache,
1292     // it is possible that during recursion and different modification
1293     // ID came to cache, so if we found it, just return it.
1294     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1295       return S;
1296   }
1297 
1298   // If the input value is a chrec scev, truncate the chrec's operands.
1299   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1300     SmallVector<const SCEV *, 4> Operands;
1301     for (const SCEV *Op : AddRec->operands())
1302       Operands.push_back(getTruncateExpr(Op, Ty));
1303     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1304   }
1305 
1306   // The cast wasn't folded; create an explicit cast node. We can reuse
1307   // the existing insert position since if we get here, we won't have
1308   // made any changes which would invalidate it.
1309   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1310                                                  Op, Ty);
1311   UniqueSCEVs.InsertNode(S, IP);
1312   addToLoopUseLists(S);
1313   return S;
1314 }
1315 
1316 // Get the limit of a recurrence such that incrementing by Step cannot cause
1317 // signed overflow as long as the value of the recurrence within the
1318 // loop does not exceed this limit before incrementing.
1319 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1320                                                  ICmpInst::Predicate *Pred,
1321                                                  ScalarEvolution *SE) {
1322   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1323   if (SE->isKnownPositive(Step)) {
1324     *Pred = ICmpInst::ICMP_SLT;
1325     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1326                            SE->getSignedRangeMax(Step));
1327   }
1328   if (SE->isKnownNegative(Step)) {
1329     *Pred = ICmpInst::ICMP_SGT;
1330     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1331                            SE->getSignedRangeMin(Step));
1332   }
1333   return nullptr;
1334 }
1335 
1336 // Get the limit of a recurrence such that incrementing by Step cannot cause
1337 // unsigned overflow as long as the value of the recurrence within the loop does
1338 // not exceed this limit before incrementing.
1339 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1340                                                    ICmpInst::Predicate *Pred,
1341                                                    ScalarEvolution *SE) {
1342   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1343   *Pred = ICmpInst::ICMP_ULT;
1344 
1345   return SE->getConstant(APInt::getMinValue(BitWidth) -
1346                          SE->getUnsignedRangeMax(Step));
1347 }
1348 
1349 namespace {
1350 
1351 struct ExtendOpTraitsBase {
1352   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1353                                                           unsigned);
1354 };
1355 
1356 // Used to make code generic over signed and unsigned overflow.
1357 template <typename ExtendOp> struct ExtendOpTraits {
1358   // Members present:
1359   //
1360   // static const SCEV::NoWrapFlags WrapType;
1361   //
1362   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1363   //
1364   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1365   //                                           ICmpInst::Predicate *Pred,
1366   //                                           ScalarEvolution *SE);
1367 };
1368 
1369 template <>
1370 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1371   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1372 
1373   static const GetExtendExprTy GetExtendExpr;
1374 
1375   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1376                                              ICmpInst::Predicate *Pred,
1377                                              ScalarEvolution *SE) {
1378     return getSignedOverflowLimitForStep(Step, Pred, SE);
1379   }
1380 };
1381 
1382 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1383     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1384 
1385 template <>
1386 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1387   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1388 
1389   static const GetExtendExprTy GetExtendExpr;
1390 
1391   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1392                                              ICmpInst::Predicate *Pred,
1393                                              ScalarEvolution *SE) {
1394     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1395   }
1396 };
1397 
1398 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1399     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1400 
1401 } // end anonymous namespace
1402 
1403 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1404 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1405 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1406 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1407 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1408 // expression "Step + sext/zext(PreIncAR)" is congruent with
1409 // "sext/zext(PostIncAR)"
1410 template <typename ExtendOpTy>
1411 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1412                                         ScalarEvolution *SE, unsigned Depth) {
1413   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1414   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1415 
1416   const Loop *L = AR->getLoop();
1417   const SCEV *Start = AR->getStart();
1418   const SCEV *Step = AR->getStepRecurrence(*SE);
1419 
1420   // Check for a simple looking step prior to loop entry.
1421   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1422   if (!SA)
1423     return nullptr;
1424 
1425   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1426   // subtraction is expensive. For this purpose, perform a quick and dirty
1427   // difference, by checking for Step in the operand list.
1428   SmallVector<const SCEV *, 4> DiffOps;
1429   for (const SCEV *Op : SA->operands())
1430     if (Op != Step)
1431       DiffOps.push_back(Op);
1432 
1433   if (DiffOps.size() == SA->getNumOperands())
1434     return nullptr;
1435 
1436   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1437   // `Step`:
1438 
1439   // 1. NSW/NUW flags on the step increment.
1440   auto PreStartFlags =
1441     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1442   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1443   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1444       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1445 
1446   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1447   // "S+X does not sign/unsign-overflow".
1448   //
1449 
1450   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1451   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1452       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1453     return PreStart;
1454 
1455   // 2. Direct overflow check on the step operation's expression.
1456   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1457   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1458   const SCEV *OperandExtendedStart =
1459       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1460                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1461   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1462     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1463       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1464       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1465       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1466       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1467     }
1468     return PreStart;
1469   }
1470 
1471   // 3. Loop precondition.
1472   ICmpInst::Predicate Pred;
1473   const SCEV *OverflowLimit =
1474       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1475 
1476   if (OverflowLimit &&
1477       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1478     return PreStart;
1479 
1480   return nullptr;
1481 }
1482 
1483 // Get the normalized zero or sign extended expression for this AddRec's Start.
1484 template <typename ExtendOpTy>
1485 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1486                                         ScalarEvolution *SE,
1487                                         unsigned Depth) {
1488   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1489 
1490   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1491   if (!PreStart)
1492     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1493 
1494   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1495                                              Depth),
1496                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1497 }
1498 
1499 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1500 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1501 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1502 //
1503 // Formally:
1504 //
1505 //     {S,+,X} == {S-T,+,X} + T
1506 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1507 //
1508 // If ({S-T,+,X} + T) does not overflow  ... (1)
1509 //
1510 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1511 //
1512 // If {S-T,+,X} does not overflow  ... (2)
1513 //
1514 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1515 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1516 //
1517 // If (S-T)+T does not overflow  ... (3)
1518 //
1519 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1520 //      == {Ext(S),+,Ext(X)} == LHS
1521 //
1522 // Thus, if (1), (2) and (3) are true for some T, then
1523 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1524 //
1525 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1526 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1527 // to check for (1) and (2).
1528 //
1529 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1530 // is `Delta` (defined below).
1531 template <typename ExtendOpTy>
1532 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1533                                                 const SCEV *Step,
1534                                                 const Loop *L) {
1535   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1536 
1537   // We restrict `Start` to a constant to prevent SCEV from spending too much
1538   // time here.  It is correct (but more expensive) to continue with a
1539   // non-constant `Start` and do a general SCEV subtraction to compute
1540   // `PreStart` below.
1541   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1542   if (!StartC)
1543     return false;
1544 
1545   APInt StartAI = StartC->getAPInt();
1546 
1547   for (unsigned Delta : {-2, -1, 1, 2}) {
1548     const SCEV *PreStart = getConstant(StartAI - Delta);
1549 
1550     FoldingSetNodeID ID;
1551     ID.AddInteger(scAddRecExpr);
1552     ID.AddPointer(PreStart);
1553     ID.AddPointer(Step);
1554     ID.AddPointer(L);
1555     void *IP = nullptr;
1556     const auto *PreAR =
1557       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1558 
1559     // Give up if we don't already have the add recurrence we need because
1560     // actually constructing an add recurrence is relatively expensive.
1561     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1562       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1563       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1564       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1565           DeltaS, &Pred, this);
1566       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1567         return true;
1568     }
1569   }
1570 
1571   return false;
1572 }
1573 
1574 const SCEV *
1575 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1576   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1577          "This is not an extending conversion!");
1578   assert(isSCEVable(Ty) &&
1579          "This is not a conversion to a SCEVable type!");
1580   Ty = getEffectiveSCEVType(Ty);
1581 
1582   // Fold if the operand is constant.
1583   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1584     return getConstant(
1585       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1586 
1587   // zext(zext(x)) --> zext(x)
1588   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1589     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1590 
1591   // Before doing any expensive analysis, check to see if we've already
1592   // computed a SCEV for this Op and Ty.
1593   FoldingSetNodeID ID;
1594   ID.AddInteger(scZeroExtend);
1595   ID.AddPointer(Op);
1596   ID.AddPointer(Ty);
1597   void *IP = nullptr;
1598   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1599   if (Depth > MaxExtDepth) {
1600     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1601                                                      Op, Ty);
1602     UniqueSCEVs.InsertNode(S, IP);
1603     addToLoopUseLists(S);
1604     return S;
1605   }
1606 
1607   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1608   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1609     // It's possible the bits taken off by the truncate were all zero bits. If
1610     // so, we should be able to simplify this further.
1611     const SCEV *X = ST->getOperand();
1612     ConstantRange CR = getUnsignedRange(X);
1613     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1614     unsigned NewBits = getTypeSizeInBits(Ty);
1615     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1616             CR.zextOrTrunc(NewBits)))
1617       return getTruncateOrZeroExtend(X, Ty);
1618   }
1619 
1620   // If the input value is a chrec scev, and we can prove that the value
1621   // did not overflow the old, smaller, value, we can zero extend all of the
1622   // operands (often constants).  This allows analysis of something like
1623   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1624   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1625     if (AR->isAffine()) {
1626       const SCEV *Start = AR->getStart();
1627       const SCEV *Step = AR->getStepRecurrence(*this);
1628       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1629       const Loop *L = AR->getLoop();
1630 
1631       if (!AR->hasNoUnsignedWrap()) {
1632         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1633         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1634       }
1635 
1636       // If we have special knowledge that this addrec won't overflow,
1637       // we don't need to do any further analysis.
1638       if (AR->hasNoUnsignedWrap())
1639         return getAddRecExpr(
1640             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1641             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1642 
1643       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1644       // Note that this serves two purposes: It filters out loops that are
1645       // simply not analyzable, and it covers the case where this code is
1646       // being called from within backedge-taken count analysis, such that
1647       // attempting to ask for the backedge-taken count would likely result
1648       // in infinite recursion. In the later case, the analysis code will
1649       // cope with a conservative value, and it will take care to purge
1650       // that value once it has finished.
1651       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1652       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1653         // Manually compute the final value for AR, checking for
1654         // overflow.
1655 
1656         // Check whether the backedge-taken count can be losslessly casted to
1657         // the addrec's type. The count is always unsigned.
1658         const SCEV *CastedMaxBECount =
1659           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1660         const SCEV *RecastedMaxBECount =
1661           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1662         if (MaxBECount == RecastedMaxBECount) {
1663           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1664           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1665           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1666                                         SCEV::FlagAnyWrap, Depth + 1);
1667           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1668                                                           SCEV::FlagAnyWrap,
1669                                                           Depth + 1),
1670                                                WideTy, Depth + 1);
1671           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1672           const SCEV *WideMaxBECount =
1673             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1674           const SCEV *OperandExtendedAdd =
1675             getAddExpr(WideStart,
1676                        getMulExpr(WideMaxBECount,
1677                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1678                                   SCEV::FlagAnyWrap, Depth + 1),
1679                        SCEV::FlagAnyWrap, Depth + 1);
1680           if (ZAdd == OperandExtendedAdd) {
1681             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1682             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1683             // Return the expression with the addrec on the outside.
1684             return getAddRecExpr(
1685                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1686                                                          Depth + 1),
1687                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1688                 AR->getNoWrapFlags());
1689           }
1690           // Similar to above, only this time treat the step value as signed.
1691           // This covers loops that count down.
1692           OperandExtendedAdd =
1693             getAddExpr(WideStart,
1694                        getMulExpr(WideMaxBECount,
1695                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1696                                   SCEV::FlagAnyWrap, Depth + 1),
1697                        SCEV::FlagAnyWrap, Depth + 1);
1698           if (ZAdd == OperandExtendedAdd) {
1699             // Cache knowledge of AR NW, which is propagated to this AddRec.
1700             // Negative step causes unsigned wrap, but it still can't self-wrap.
1701             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1702             // Return the expression with the addrec on the outside.
1703             return getAddRecExpr(
1704                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1705                                                          Depth + 1),
1706                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1707                 AR->getNoWrapFlags());
1708           }
1709         }
1710       }
1711 
1712       // Normally, in the cases we can prove no-overflow via a
1713       // backedge guarding condition, we can also compute a backedge
1714       // taken count for the loop.  The exceptions are assumptions and
1715       // guards present in the loop -- SCEV is not great at exploiting
1716       // these to compute max backedge taken counts, but can still use
1717       // these to prove lack of overflow.  Use this fact to avoid
1718       // doing extra work that may not pay off.
1719       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1720           !AC.assumptions().empty()) {
1721         // If the backedge is guarded by a comparison with the pre-inc
1722         // value the addrec is safe. Also, if the entry is guarded by
1723         // a comparison with the start value and the backedge is
1724         // guarded by a comparison with the post-inc value, the addrec
1725         // is safe.
1726         if (isKnownPositive(Step)) {
1727           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1728                                       getUnsignedRangeMax(Step));
1729           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1730               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1731             // Cache knowledge of AR NUW, which is propagated to this
1732             // AddRec.
1733             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1734             // Return the expression with the addrec on the outside.
1735             return getAddRecExpr(
1736                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1737                                                          Depth + 1),
1738                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1739                 AR->getNoWrapFlags());
1740           }
1741         } else if (isKnownNegative(Step)) {
1742           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1743                                       getSignedRangeMin(Step));
1744           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1745               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1746             // Cache knowledge of AR NW, which is propagated to this
1747             // AddRec.  Negative step causes unsigned wrap, but it
1748             // still can't self-wrap.
1749             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1750             // Return the expression with the addrec on the outside.
1751             return getAddRecExpr(
1752                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1753                                                          Depth + 1),
1754                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1755                 AR->getNoWrapFlags());
1756           }
1757         }
1758       }
1759 
1760       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1761         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1762         return getAddRecExpr(
1763             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1764             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1765       }
1766     }
1767 
1768   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1769     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1770     if (SA->hasNoUnsignedWrap()) {
1771       // If the addition does not unsign overflow then we can, by definition,
1772       // commute the zero extension with the addition operation.
1773       SmallVector<const SCEV *, 4> Ops;
1774       for (const auto *Op : SA->operands())
1775         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1776       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1777     }
1778   }
1779 
1780   // The cast wasn't folded; create an explicit cast node.
1781   // Recompute the insert position, as it may have been invalidated.
1782   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1783   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1784                                                    Op, Ty);
1785   UniqueSCEVs.InsertNode(S, IP);
1786   addToLoopUseLists(S);
1787   return S;
1788 }
1789 
1790 const SCEV *
1791 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1792   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1793          "This is not an extending conversion!");
1794   assert(isSCEVable(Ty) &&
1795          "This is not a conversion to a SCEVable type!");
1796   Ty = getEffectiveSCEVType(Ty);
1797 
1798   // Fold if the operand is constant.
1799   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1800     return getConstant(
1801       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1802 
1803   // sext(sext(x)) --> sext(x)
1804   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1805     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1806 
1807   // sext(zext(x)) --> zext(x)
1808   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1809     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1810 
1811   // Before doing any expensive analysis, check to see if we've already
1812   // computed a SCEV for this Op and Ty.
1813   FoldingSetNodeID ID;
1814   ID.AddInteger(scSignExtend);
1815   ID.AddPointer(Op);
1816   ID.AddPointer(Ty);
1817   void *IP = nullptr;
1818   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1819   // Limit recursion depth.
1820   if (Depth > MaxExtDepth) {
1821     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1822                                                      Op, Ty);
1823     UniqueSCEVs.InsertNode(S, IP);
1824     addToLoopUseLists(S);
1825     return S;
1826   }
1827 
1828   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1829   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1830     // It's possible the bits taken off by the truncate were all sign bits. If
1831     // so, we should be able to simplify this further.
1832     const SCEV *X = ST->getOperand();
1833     ConstantRange CR = getSignedRange(X);
1834     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1835     unsigned NewBits = getTypeSizeInBits(Ty);
1836     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1837             CR.sextOrTrunc(NewBits)))
1838       return getTruncateOrSignExtend(X, Ty);
1839   }
1840 
1841   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1842   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1843     if (SA->getNumOperands() == 2) {
1844       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1845       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1846       if (SMul && SC1) {
1847         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1848           const APInt &C1 = SC1->getAPInt();
1849           const APInt &C2 = SC2->getAPInt();
1850           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1851               C2.ugt(C1) && C2.isPowerOf2())
1852             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1853                               getSignExtendExpr(SMul, Ty, Depth + 1),
1854                               SCEV::FlagAnyWrap, Depth + 1);
1855         }
1856       }
1857     }
1858 
1859     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1860     if (SA->hasNoSignedWrap()) {
1861       // If the addition does not sign overflow then we can, by definition,
1862       // commute the sign extension with the addition operation.
1863       SmallVector<const SCEV *, 4> Ops;
1864       for (const auto *Op : SA->operands())
1865         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1866       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1867     }
1868   }
1869   // If the input value is a chrec scev, and we can prove that the value
1870   // did not overflow the old, smaller, value, we can sign extend all of the
1871   // operands (often constants).  This allows analysis of something like
1872   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1873   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1874     if (AR->isAffine()) {
1875       const SCEV *Start = AR->getStart();
1876       const SCEV *Step = AR->getStepRecurrence(*this);
1877       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1878       const Loop *L = AR->getLoop();
1879 
1880       if (!AR->hasNoSignedWrap()) {
1881         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1882         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1883       }
1884 
1885       // If we have special knowledge that this addrec won't overflow,
1886       // we don't need to do any further analysis.
1887       if (AR->hasNoSignedWrap())
1888         return getAddRecExpr(
1889             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1890             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1891 
1892       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1893       // Note that this serves two purposes: It filters out loops that are
1894       // simply not analyzable, and it covers the case where this code is
1895       // being called from within backedge-taken count analysis, such that
1896       // attempting to ask for the backedge-taken count would likely result
1897       // in infinite recursion. In the later case, the analysis code will
1898       // cope with a conservative value, and it will take care to purge
1899       // that value once it has finished.
1900       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1901       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1902         // Manually compute the final value for AR, checking for
1903         // overflow.
1904 
1905         // Check whether the backedge-taken count can be losslessly casted to
1906         // the addrec's type. The count is always unsigned.
1907         const SCEV *CastedMaxBECount =
1908           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1909         const SCEV *RecastedMaxBECount =
1910           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1911         if (MaxBECount == RecastedMaxBECount) {
1912           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1913           // Check whether Start+Step*MaxBECount has no signed overflow.
1914           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1915                                         SCEV::FlagAnyWrap, Depth + 1);
1916           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1917                                                           SCEV::FlagAnyWrap,
1918                                                           Depth + 1),
1919                                                WideTy, Depth + 1);
1920           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1921           const SCEV *WideMaxBECount =
1922             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1923           const SCEV *OperandExtendedAdd =
1924             getAddExpr(WideStart,
1925                        getMulExpr(WideMaxBECount,
1926                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1927                                   SCEV::FlagAnyWrap, Depth + 1),
1928                        SCEV::FlagAnyWrap, Depth + 1);
1929           if (SAdd == OperandExtendedAdd) {
1930             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1931             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1932             // Return the expression with the addrec on the outside.
1933             return getAddRecExpr(
1934                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1935                                                          Depth + 1),
1936                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1937                 AR->getNoWrapFlags());
1938           }
1939           // Similar to above, only this time treat the step value as unsigned.
1940           // This covers loops that count up with an unsigned step.
1941           OperandExtendedAdd =
1942             getAddExpr(WideStart,
1943                        getMulExpr(WideMaxBECount,
1944                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1945                                   SCEV::FlagAnyWrap, Depth + 1),
1946                        SCEV::FlagAnyWrap, Depth + 1);
1947           if (SAdd == OperandExtendedAdd) {
1948             // If AR wraps around then
1949             //
1950             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1951             // => SAdd != OperandExtendedAdd
1952             //
1953             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1954             // (SAdd == OperandExtendedAdd => AR is NW)
1955 
1956             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1957 
1958             // Return the expression with the addrec on the outside.
1959             return getAddRecExpr(
1960                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1961                                                          Depth + 1),
1962                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1963                 AR->getNoWrapFlags());
1964           }
1965         }
1966       }
1967 
1968       // Normally, in the cases we can prove no-overflow via a
1969       // backedge guarding condition, we can also compute a backedge
1970       // taken count for the loop.  The exceptions are assumptions and
1971       // guards present in the loop -- SCEV is not great at exploiting
1972       // these to compute max backedge taken counts, but can still use
1973       // these to prove lack of overflow.  Use this fact to avoid
1974       // doing extra work that may not pay off.
1975 
1976       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1977           !AC.assumptions().empty()) {
1978         // If the backedge is guarded by a comparison with the pre-inc
1979         // value the addrec is safe. Also, if the entry is guarded by
1980         // a comparison with the start value and the backedge is
1981         // guarded by a comparison with the post-inc value, the addrec
1982         // is safe.
1983         ICmpInst::Predicate Pred;
1984         const SCEV *OverflowLimit =
1985             getSignedOverflowLimitForStep(Step, &Pred, this);
1986         if (OverflowLimit &&
1987             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1988              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
1989           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1990           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1991           return getAddRecExpr(
1992               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1993               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1994         }
1995       }
1996 
1997       // If Start and Step are constants, check if we can apply this
1998       // transformation:
1999       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2000       auto *SC1 = dyn_cast<SCEVConstant>(Start);
2001       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2002       if (SC1 && SC2) {
2003         const APInt &C1 = SC1->getAPInt();
2004         const APInt &C2 = SC2->getAPInt();
2005         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2006             C2.isPowerOf2()) {
2007           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2008           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2009                                             AR->getNoWrapFlags());
2010           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2011                             SCEV::FlagAnyWrap, Depth + 1);
2012         }
2013       }
2014 
2015       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2016         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2017         return getAddRecExpr(
2018             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2019             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2020       }
2021     }
2022 
2023   // If the input value is provably positive and we could not simplify
2024   // away the sext build a zext instead.
2025   if (isKnownNonNegative(Op))
2026     return getZeroExtendExpr(Op, Ty, Depth + 1);
2027 
2028   // The cast wasn't folded; create an explicit cast node.
2029   // Recompute the insert position, as it may have been invalidated.
2030   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2031   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2032                                                    Op, Ty);
2033   UniqueSCEVs.InsertNode(S, IP);
2034   addToLoopUseLists(S);
2035   return S;
2036 }
2037 
2038 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2039 /// unspecified bits out to the given type.
2040 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2041                                               Type *Ty) {
2042   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2043          "This is not an extending conversion!");
2044   assert(isSCEVable(Ty) &&
2045          "This is not a conversion to a SCEVable type!");
2046   Ty = getEffectiveSCEVType(Ty);
2047 
2048   // Sign-extend negative constants.
2049   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2050     if (SC->getAPInt().isNegative())
2051       return getSignExtendExpr(Op, Ty);
2052 
2053   // Peel off a truncate cast.
2054   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2055     const SCEV *NewOp = T->getOperand();
2056     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2057       return getAnyExtendExpr(NewOp, Ty);
2058     return getTruncateOrNoop(NewOp, Ty);
2059   }
2060 
2061   // Next try a zext cast. If the cast is folded, use it.
2062   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2063   if (!isa<SCEVZeroExtendExpr>(ZExt))
2064     return ZExt;
2065 
2066   // Next try a sext cast. If the cast is folded, use it.
2067   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2068   if (!isa<SCEVSignExtendExpr>(SExt))
2069     return SExt;
2070 
2071   // Force the cast to be folded into the operands of an addrec.
2072   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2073     SmallVector<const SCEV *, 4> Ops;
2074     for (const SCEV *Op : AR->operands())
2075       Ops.push_back(getAnyExtendExpr(Op, Ty));
2076     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2077   }
2078 
2079   // If the expression is obviously signed, use the sext cast value.
2080   if (isa<SCEVSMaxExpr>(Op))
2081     return SExt;
2082 
2083   // Absent any other information, use the zext cast value.
2084   return ZExt;
2085 }
2086 
2087 /// Process the given Ops list, which is a list of operands to be added under
2088 /// the given scale, update the given map. This is a helper function for
2089 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2090 /// that would form an add expression like this:
2091 ///
2092 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2093 ///
2094 /// where A and B are constants, update the map with these values:
2095 ///
2096 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2097 ///
2098 /// and add 13 + A*B*29 to AccumulatedConstant.
2099 /// This will allow getAddRecExpr to produce this:
2100 ///
2101 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2102 ///
2103 /// This form often exposes folding opportunities that are hidden in
2104 /// the original operand list.
2105 ///
2106 /// Return true iff it appears that any interesting folding opportunities
2107 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2108 /// the common case where no interesting opportunities are present, and
2109 /// is also used as a check to avoid infinite recursion.
2110 static bool
2111 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2112                              SmallVectorImpl<const SCEV *> &NewOps,
2113                              APInt &AccumulatedConstant,
2114                              const SCEV *const *Ops, size_t NumOperands,
2115                              const APInt &Scale,
2116                              ScalarEvolution &SE) {
2117   bool Interesting = false;
2118 
2119   // Iterate over the add operands. They are sorted, with constants first.
2120   unsigned i = 0;
2121   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2122     ++i;
2123     // Pull a buried constant out to the outside.
2124     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2125       Interesting = true;
2126     AccumulatedConstant += Scale * C->getAPInt();
2127   }
2128 
2129   // Next comes everything else. We're especially interested in multiplies
2130   // here, but they're in the middle, so just visit the rest with one loop.
2131   for (; i != NumOperands; ++i) {
2132     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2133     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2134       APInt NewScale =
2135           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2136       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2137         // A multiplication of a constant with another add; recurse.
2138         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2139         Interesting |=
2140           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2141                                        Add->op_begin(), Add->getNumOperands(),
2142                                        NewScale, SE);
2143       } else {
2144         // A multiplication of a constant with some other value. Update
2145         // the map.
2146         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2147         const SCEV *Key = SE.getMulExpr(MulOps);
2148         auto Pair = M.insert({Key, NewScale});
2149         if (Pair.second) {
2150           NewOps.push_back(Pair.first->first);
2151         } else {
2152           Pair.first->second += NewScale;
2153           // The map already had an entry for this value, which may indicate
2154           // a folding opportunity.
2155           Interesting = true;
2156         }
2157       }
2158     } else {
2159       // An ordinary operand. Update the map.
2160       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2161           M.insert({Ops[i], Scale});
2162       if (Pair.second) {
2163         NewOps.push_back(Pair.first->first);
2164       } else {
2165         Pair.first->second += Scale;
2166         // The map already had an entry for this value, which may indicate
2167         // a folding opportunity.
2168         Interesting = true;
2169       }
2170     }
2171   }
2172 
2173   return Interesting;
2174 }
2175 
2176 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2177 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2178 // can't-overflow flags for the operation if possible.
2179 static SCEV::NoWrapFlags
2180 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2181                       const SmallVectorImpl<const SCEV *> &Ops,
2182                       SCEV::NoWrapFlags Flags) {
2183   using namespace std::placeholders;
2184 
2185   using OBO = OverflowingBinaryOperator;
2186 
2187   bool CanAnalyze =
2188       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2189   (void)CanAnalyze;
2190   assert(CanAnalyze && "don't call from other places!");
2191 
2192   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2193   SCEV::NoWrapFlags SignOrUnsignWrap =
2194       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2195 
2196   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2197   auto IsKnownNonNegative = [&](const SCEV *S) {
2198     return SE->isKnownNonNegative(S);
2199   };
2200 
2201   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2202     Flags =
2203         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2204 
2205   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2206 
2207   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2208       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2209 
2210     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2211     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2212 
2213     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2214     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2215       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2216           Instruction::Add, C, OBO::NoSignedWrap);
2217       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2218         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2219     }
2220     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2221       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2222           Instruction::Add, C, OBO::NoUnsignedWrap);
2223       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2224         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2225     }
2226   }
2227 
2228   return Flags;
2229 }
2230 
2231 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2232   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2233 }
2234 
2235 /// Get a canonical add expression, or something simpler if possible.
2236 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2237                                         SCEV::NoWrapFlags Flags,
2238                                         unsigned Depth) {
2239   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2240          "only nuw or nsw allowed");
2241   assert(!Ops.empty() && "Cannot get empty add!");
2242   if (Ops.size() == 1) return Ops[0];
2243 #ifndef NDEBUG
2244   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2245   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2246     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2247            "SCEVAddExpr operand types don't match!");
2248 #endif
2249 
2250   // Sort by complexity, this groups all similar expression types together.
2251   GroupByComplexity(Ops, &LI, DT);
2252 
2253   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2254 
2255   // If there are any constants, fold them together.
2256   unsigned Idx = 0;
2257   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2258     ++Idx;
2259     assert(Idx < Ops.size());
2260     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2261       // We found two constants, fold them together!
2262       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2263       if (Ops.size() == 2) return Ops[0];
2264       Ops.erase(Ops.begin()+1);  // Erase the folded element
2265       LHSC = cast<SCEVConstant>(Ops[0]);
2266     }
2267 
2268     // If we are left with a constant zero being added, strip it off.
2269     if (LHSC->getValue()->isZero()) {
2270       Ops.erase(Ops.begin());
2271       --Idx;
2272     }
2273 
2274     if (Ops.size() == 1) return Ops[0];
2275   }
2276 
2277   // Limit recursion calls depth.
2278   if (Depth > MaxArithDepth)
2279     return getOrCreateAddExpr(Ops, Flags);
2280 
2281   // Okay, check to see if the same value occurs in the operand list more than
2282   // once.  If so, merge them together into an multiply expression.  Since we
2283   // sorted the list, these values are required to be adjacent.
2284   Type *Ty = Ops[0]->getType();
2285   bool FoundMatch = false;
2286   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2287     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2288       // Scan ahead to count how many equal operands there are.
2289       unsigned Count = 2;
2290       while (i+Count != e && Ops[i+Count] == Ops[i])
2291         ++Count;
2292       // Merge the values into a multiply.
2293       const SCEV *Scale = getConstant(Ty, Count);
2294       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2295       if (Ops.size() == Count)
2296         return Mul;
2297       Ops[i] = Mul;
2298       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2299       --i; e -= Count - 1;
2300       FoundMatch = true;
2301     }
2302   if (FoundMatch)
2303     return getAddExpr(Ops, Flags, Depth + 1);
2304 
2305   // Check for truncates. If all the operands are truncated from the same
2306   // type, see if factoring out the truncate would permit the result to be
2307   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2308   // if the contents of the resulting outer trunc fold to something simple.
2309   auto FindTruncSrcType = [&]() -> Type * {
2310     // We're ultimately looking to fold an addrec of truncs and muls of only
2311     // constants and truncs, so if we find any other types of SCEV
2312     // as operands of the addrec then we bail and return nullptr here.
2313     // Otherwise, we return the type of the operand of a trunc that we find.
2314     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2315       return T->getOperand()->getType();
2316     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2317       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2318       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2319         return T->getOperand()->getType();
2320     }
2321     return nullptr;
2322   };
2323   if (auto *SrcType = FindTruncSrcType()) {
2324     SmallVector<const SCEV *, 8> LargeOps;
2325     bool Ok = true;
2326     // Check all the operands to see if they can be represented in the
2327     // source type of the truncate.
2328     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2329       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2330         if (T->getOperand()->getType() != SrcType) {
2331           Ok = false;
2332           break;
2333         }
2334         LargeOps.push_back(T->getOperand());
2335       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2336         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2337       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2338         SmallVector<const SCEV *, 8> LargeMulOps;
2339         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2340           if (const SCEVTruncateExpr *T =
2341                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2342             if (T->getOperand()->getType() != SrcType) {
2343               Ok = false;
2344               break;
2345             }
2346             LargeMulOps.push_back(T->getOperand());
2347           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2348             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2349           } else {
2350             Ok = false;
2351             break;
2352           }
2353         }
2354         if (Ok)
2355           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2356       } else {
2357         Ok = false;
2358         break;
2359       }
2360     }
2361     if (Ok) {
2362       // Evaluate the expression in the larger type.
2363       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2364       // If it folds to something simple, use it. Otherwise, don't.
2365       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2366         return getTruncateExpr(Fold, Ty);
2367     }
2368   }
2369 
2370   // Skip past any other cast SCEVs.
2371   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2372     ++Idx;
2373 
2374   // If there are add operands they would be next.
2375   if (Idx < Ops.size()) {
2376     bool DeletedAdd = false;
2377     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2378       if (Ops.size() > AddOpsInlineThreshold ||
2379           Add->getNumOperands() > AddOpsInlineThreshold)
2380         break;
2381       // If we have an add, expand the add operands onto the end of the operands
2382       // list.
2383       Ops.erase(Ops.begin()+Idx);
2384       Ops.append(Add->op_begin(), Add->op_end());
2385       DeletedAdd = true;
2386     }
2387 
2388     // If we deleted at least one add, we added operands to the end of the list,
2389     // and they are not necessarily sorted.  Recurse to resort and resimplify
2390     // any operands we just acquired.
2391     if (DeletedAdd)
2392       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2393   }
2394 
2395   // Skip over the add expression until we get to a multiply.
2396   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2397     ++Idx;
2398 
2399   // Check to see if there are any folding opportunities present with
2400   // operands multiplied by constant values.
2401   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2402     uint64_t BitWidth = getTypeSizeInBits(Ty);
2403     DenseMap<const SCEV *, APInt> M;
2404     SmallVector<const SCEV *, 8> NewOps;
2405     APInt AccumulatedConstant(BitWidth, 0);
2406     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2407                                      Ops.data(), Ops.size(),
2408                                      APInt(BitWidth, 1), *this)) {
2409       struct APIntCompare {
2410         bool operator()(const APInt &LHS, const APInt &RHS) const {
2411           return LHS.ult(RHS);
2412         }
2413       };
2414 
2415       // Some interesting folding opportunity is present, so its worthwhile to
2416       // re-generate the operands list. Group the operands by constant scale,
2417       // to avoid multiplying by the same constant scale multiple times.
2418       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2419       for (const SCEV *NewOp : NewOps)
2420         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2421       // Re-generate the operands list.
2422       Ops.clear();
2423       if (AccumulatedConstant != 0)
2424         Ops.push_back(getConstant(AccumulatedConstant));
2425       for (auto &MulOp : MulOpLists)
2426         if (MulOp.first != 0)
2427           Ops.push_back(getMulExpr(
2428               getConstant(MulOp.first),
2429               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2430               SCEV::FlagAnyWrap, Depth + 1));
2431       if (Ops.empty())
2432         return getZero(Ty);
2433       if (Ops.size() == 1)
2434         return Ops[0];
2435       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2436     }
2437   }
2438 
2439   // If we are adding something to a multiply expression, make sure the
2440   // something is not already an operand of the multiply.  If so, merge it into
2441   // the multiply.
2442   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2443     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2444     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2445       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2446       if (isa<SCEVConstant>(MulOpSCEV))
2447         continue;
2448       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2449         if (MulOpSCEV == Ops[AddOp]) {
2450           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2451           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2452           if (Mul->getNumOperands() != 2) {
2453             // If the multiply has more than two operands, we must get the
2454             // Y*Z term.
2455             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2456                                                 Mul->op_begin()+MulOp);
2457             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2458             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2459           }
2460           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2461           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2462           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2463                                             SCEV::FlagAnyWrap, Depth + 1);
2464           if (Ops.size() == 2) return OuterMul;
2465           if (AddOp < Idx) {
2466             Ops.erase(Ops.begin()+AddOp);
2467             Ops.erase(Ops.begin()+Idx-1);
2468           } else {
2469             Ops.erase(Ops.begin()+Idx);
2470             Ops.erase(Ops.begin()+AddOp-1);
2471           }
2472           Ops.push_back(OuterMul);
2473           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2474         }
2475 
2476       // Check this multiply against other multiplies being added together.
2477       for (unsigned OtherMulIdx = Idx+1;
2478            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2479            ++OtherMulIdx) {
2480         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2481         // If MulOp occurs in OtherMul, we can fold the two multiplies
2482         // together.
2483         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2484              OMulOp != e; ++OMulOp)
2485           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2486             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2487             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2488             if (Mul->getNumOperands() != 2) {
2489               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2490                                                   Mul->op_begin()+MulOp);
2491               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2492               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2493             }
2494             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2495             if (OtherMul->getNumOperands() != 2) {
2496               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2497                                                   OtherMul->op_begin()+OMulOp);
2498               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2499               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2500             }
2501             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2502             const SCEV *InnerMulSum =
2503                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2504             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2505                                               SCEV::FlagAnyWrap, Depth + 1);
2506             if (Ops.size() == 2) return OuterMul;
2507             Ops.erase(Ops.begin()+Idx);
2508             Ops.erase(Ops.begin()+OtherMulIdx-1);
2509             Ops.push_back(OuterMul);
2510             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2511           }
2512       }
2513     }
2514   }
2515 
2516   // If there are any add recurrences in the operands list, see if any other
2517   // added values are loop invariant.  If so, we can fold them into the
2518   // recurrence.
2519   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2520     ++Idx;
2521 
2522   // Scan over all recurrences, trying to fold loop invariants into them.
2523   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2524     // Scan all of the other operands to this add and add them to the vector if
2525     // they are loop invariant w.r.t. the recurrence.
2526     SmallVector<const SCEV *, 8> LIOps;
2527     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2528     const Loop *AddRecLoop = AddRec->getLoop();
2529     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2530       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2531         LIOps.push_back(Ops[i]);
2532         Ops.erase(Ops.begin()+i);
2533         --i; --e;
2534       }
2535 
2536     // If we found some loop invariants, fold them into the recurrence.
2537     if (!LIOps.empty()) {
2538       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2539       LIOps.push_back(AddRec->getStart());
2540 
2541       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2542                                              AddRec->op_end());
2543       // This follows from the fact that the no-wrap flags on the outer add
2544       // expression are applicable on the 0th iteration, when the add recurrence
2545       // will be equal to its start value.
2546       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2547 
2548       // Build the new addrec. Propagate the NUW and NSW flags if both the
2549       // outer add and the inner addrec are guaranteed to have no overflow.
2550       // Always propagate NW.
2551       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2552       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2553 
2554       // If all of the other operands were loop invariant, we are done.
2555       if (Ops.size() == 1) return NewRec;
2556 
2557       // Otherwise, add the folded AddRec by the non-invariant parts.
2558       for (unsigned i = 0;; ++i)
2559         if (Ops[i] == AddRec) {
2560           Ops[i] = NewRec;
2561           break;
2562         }
2563       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2564     }
2565 
2566     // Okay, if there weren't any loop invariants to be folded, check to see if
2567     // there are multiple AddRec's with the same loop induction variable being
2568     // added together.  If so, we can fold them.
2569     for (unsigned OtherIdx = Idx+1;
2570          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2571          ++OtherIdx) {
2572       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2573       // so that the 1st found AddRecExpr is dominated by all others.
2574       assert(DT.dominates(
2575            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2576            AddRec->getLoop()->getHeader()) &&
2577         "AddRecExprs are not sorted in reverse dominance order?");
2578       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2579         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2580         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2581                                                AddRec->op_end());
2582         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2583              ++OtherIdx) {
2584           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2585           if (OtherAddRec->getLoop() == AddRecLoop) {
2586             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2587                  i != e; ++i) {
2588               if (i >= AddRecOps.size()) {
2589                 AddRecOps.append(OtherAddRec->op_begin()+i,
2590                                  OtherAddRec->op_end());
2591                 break;
2592               }
2593               SmallVector<const SCEV *, 2> TwoOps = {
2594                   AddRecOps[i], OtherAddRec->getOperand(i)};
2595               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2596             }
2597             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2598           }
2599         }
2600         // Step size has changed, so we cannot guarantee no self-wraparound.
2601         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2602         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2603       }
2604     }
2605 
2606     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2607     // next one.
2608   }
2609 
2610   // Okay, it looks like we really DO need an add expr.  Check to see if we
2611   // already have one, otherwise create a new one.
2612   return getOrCreateAddExpr(Ops, Flags);
2613 }
2614 
2615 const SCEV *
2616 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2617                                     SCEV::NoWrapFlags Flags) {
2618   FoldingSetNodeID ID;
2619   ID.AddInteger(scAddExpr);
2620   for (const SCEV *Op : Ops)
2621     ID.AddPointer(Op);
2622   void *IP = nullptr;
2623   SCEVAddExpr *S =
2624       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2625   if (!S) {
2626     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2627     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2628     S = new (SCEVAllocator)
2629         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2630     UniqueSCEVs.InsertNode(S, IP);
2631     addToLoopUseLists(S);
2632   }
2633   S->setNoWrapFlags(Flags);
2634   return S;
2635 }
2636 
2637 const SCEV *
2638 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2639                                     SCEV::NoWrapFlags Flags) {
2640   FoldingSetNodeID ID;
2641   ID.AddInteger(scMulExpr);
2642   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2643     ID.AddPointer(Ops[i]);
2644   void *IP = nullptr;
2645   SCEVMulExpr *S =
2646     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2647   if (!S) {
2648     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2649     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2650     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2651                                         O, Ops.size());
2652     UniqueSCEVs.InsertNode(S, IP);
2653     addToLoopUseLists(S);
2654   }
2655   S->setNoWrapFlags(Flags);
2656   return S;
2657 }
2658 
2659 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2660   uint64_t k = i*j;
2661   if (j > 1 && k / j != i) Overflow = true;
2662   return k;
2663 }
2664 
2665 /// Compute the result of "n choose k", the binomial coefficient.  If an
2666 /// intermediate computation overflows, Overflow will be set and the return will
2667 /// be garbage. Overflow is not cleared on absence of overflow.
2668 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2669   // We use the multiplicative formula:
2670   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2671   // At each iteration, we take the n-th term of the numeral and divide by the
2672   // (k-n)th term of the denominator.  This division will always produce an
2673   // integral result, and helps reduce the chance of overflow in the
2674   // intermediate computations. However, we can still overflow even when the
2675   // final result would fit.
2676 
2677   if (n == 0 || n == k) return 1;
2678   if (k > n) return 0;
2679 
2680   if (k > n/2)
2681     k = n-k;
2682 
2683   uint64_t r = 1;
2684   for (uint64_t i = 1; i <= k; ++i) {
2685     r = umul_ov(r, n-(i-1), Overflow);
2686     r /= i;
2687   }
2688   return r;
2689 }
2690 
2691 /// Determine if any of the operands in this SCEV are a constant or if
2692 /// any of the add or multiply expressions in this SCEV contain a constant.
2693 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2694   struct FindConstantInAddMulChain {
2695     bool FoundConstant = false;
2696 
2697     bool follow(const SCEV *S) {
2698       FoundConstant |= isa<SCEVConstant>(S);
2699       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2700     }
2701 
2702     bool isDone() const {
2703       return FoundConstant;
2704     }
2705   };
2706 
2707   FindConstantInAddMulChain F;
2708   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2709   ST.visitAll(StartExpr);
2710   return F.FoundConstant;
2711 }
2712 
2713 /// Get a canonical multiply expression, or something simpler if possible.
2714 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2715                                         SCEV::NoWrapFlags Flags,
2716                                         unsigned Depth) {
2717   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2718          "only nuw or nsw allowed");
2719   assert(!Ops.empty() && "Cannot get empty mul!");
2720   if (Ops.size() == 1) return Ops[0];
2721 #ifndef NDEBUG
2722   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2723   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2724     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2725            "SCEVMulExpr operand types don't match!");
2726 #endif
2727 
2728   // Sort by complexity, this groups all similar expression types together.
2729   GroupByComplexity(Ops, &LI, DT);
2730 
2731   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2732 
2733   // Limit recursion calls depth.
2734   if (Depth > MaxArithDepth)
2735     return getOrCreateMulExpr(Ops, Flags);
2736 
2737   // If there are any constants, fold them together.
2738   unsigned Idx = 0;
2739   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2740 
2741     // C1*(C2+V) -> C1*C2 + C1*V
2742     if (Ops.size() == 2)
2743         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2744           // If any of Add's ops are Adds or Muls with a constant,
2745           // apply this transformation as well.
2746           if (Add->getNumOperands() == 2)
2747             // TODO: There are some cases where this transformation is not
2748             // profitable, for example:
2749             // Add = (C0 + X) * Y + Z.
2750             // Maybe the scope of this transformation should be narrowed down.
2751             if (containsConstantInAddMulChain(Add))
2752               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2753                                            SCEV::FlagAnyWrap, Depth + 1),
2754                                 getMulExpr(LHSC, Add->getOperand(1),
2755                                            SCEV::FlagAnyWrap, Depth + 1),
2756                                 SCEV::FlagAnyWrap, Depth + 1);
2757 
2758     ++Idx;
2759     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2760       // We found two constants, fold them together!
2761       ConstantInt *Fold =
2762           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2763       Ops[0] = getConstant(Fold);
2764       Ops.erase(Ops.begin()+1);  // Erase the folded element
2765       if (Ops.size() == 1) return Ops[0];
2766       LHSC = cast<SCEVConstant>(Ops[0]);
2767     }
2768 
2769     // If we are left with a constant one being multiplied, strip it off.
2770     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2771       Ops.erase(Ops.begin());
2772       --Idx;
2773     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2774       // If we have a multiply of zero, it will always be zero.
2775       return Ops[0];
2776     } else if (Ops[0]->isAllOnesValue()) {
2777       // If we have a mul by -1 of an add, try distributing the -1 among the
2778       // add operands.
2779       if (Ops.size() == 2) {
2780         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2781           SmallVector<const SCEV *, 4> NewOps;
2782           bool AnyFolded = false;
2783           for (const SCEV *AddOp : Add->operands()) {
2784             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2785                                          Depth + 1);
2786             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2787             NewOps.push_back(Mul);
2788           }
2789           if (AnyFolded)
2790             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2791         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2792           // Negation preserves a recurrence's no self-wrap property.
2793           SmallVector<const SCEV *, 4> Operands;
2794           for (const SCEV *AddRecOp : AddRec->operands())
2795             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2796                                           Depth + 1));
2797 
2798           return getAddRecExpr(Operands, AddRec->getLoop(),
2799                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2800         }
2801       }
2802     }
2803 
2804     if (Ops.size() == 1)
2805       return Ops[0];
2806   }
2807 
2808   // Skip over the add expression until we get to a multiply.
2809   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2810     ++Idx;
2811 
2812   // If there are mul operands inline them all into this expression.
2813   if (Idx < Ops.size()) {
2814     bool DeletedMul = false;
2815     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2816       if (Ops.size() > MulOpsInlineThreshold)
2817         break;
2818       // If we have an mul, expand the mul operands onto the end of the
2819       // operands list.
2820       Ops.erase(Ops.begin()+Idx);
2821       Ops.append(Mul->op_begin(), Mul->op_end());
2822       DeletedMul = true;
2823     }
2824 
2825     // If we deleted at least one mul, we added operands to the end of the
2826     // list, and they are not necessarily sorted.  Recurse to resort and
2827     // resimplify any operands we just acquired.
2828     if (DeletedMul)
2829       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2830   }
2831 
2832   // If there are any add recurrences in the operands list, see if any other
2833   // added values are loop invariant.  If so, we can fold them into the
2834   // recurrence.
2835   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2836     ++Idx;
2837 
2838   // Scan over all recurrences, trying to fold loop invariants into them.
2839   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2840     // Scan all of the other operands to this mul and add them to the vector
2841     // if they are loop invariant w.r.t. the recurrence.
2842     SmallVector<const SCEV *, 8> LIOps;
2843     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2844     const Loop *AddRecLoop = AddRec->getLoop();
2845     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2846       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2847         LIOps.push_back(Ops[i]);
2848         Ops.erase(Ops.begin()+i);
2849         --i; --e;
2850       }
2851 
2852     // If we found some loop invariants, fold them into the recurrence.
2853     if (!LIOps.empty()) {
2854       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2855       SmallVector<const SCEV *, 4> NewOps;
2856       NewOps.reserve(AddRec->getNumOperands());
2857       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2858       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2859         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2860                                     SCEV::FlagAnyWrap, Depth + 1));
2861 
2862       // Build the new addrec. Propagate the NUW and NSW flags if both the
2863       // outer mul and the inner addrec are guaranteed to have no overflow.
2864       //
2865       // No self-wrap cannot be guaranteed after changing the step size, but
2866       // will be inferred if either NUW or NSW is true.
2867       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2868       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2869 
2870       // If all of the other operands were loop invariant, we are done.
2871       if (Ops.size() == 1) return NewRec;
2872 
2873       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2874       for (unsigned i = 0;; ++i)
2875         if (Ops[i] == AddRec) {
2876           Ops[i] = NewRec;
2877           break;
2878         }
2879       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2880     }
2881 
2882     // Okay, if there weren't any loop invariants to be folded, check to see
2883     // if there are multiple AddRec's with the same loop induction variable
2884     // being multiplied together.  If so, we can fold them.
2885 
2886     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2887     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2888     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2889     //   ]]],+,...up to x=2n}.
2890     // Note that the arguments to choose() are always integers with values
2891     // known at compile time, never SCEV objects.
2892     //
2893     // The implementation avoids pointless extra computations when the two
2894     // addrec's are of different length (mathematically, it's equivalent to
2895     // an infinite stream of zeros on the right).
2896     bool OpsModified = false;
2897     for (unsigned OtherIdx = Idx+1;
2898          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2899          ++OtherIdx) {
2900       const SCEVAddRecExpr *OtherAddRec =
2901         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2902       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2903         continue;
2904 
2905       // Limit max number of arguments to avoid creation of unreasonably big
2906       // SCEVAddRecs with very complex operands.
2907       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2908           MaxAddRecSize)
2909         continue;
2910 
2911       bool Overflow = false;
2912       Type *Ty = AddRec->getType();
2913       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2914       SmallVector<const SCEV*, 7> AddRecOps;
2915       for (int x = 0, xe = AddRec->getNumOperands() +
2916              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2917         const SCEV *Term = getZero(Ty);
2918         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2919           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2920           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2921                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2922                z < ze && !Overflow; ++z) {
2923             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2924             uint64_t Coeff;
2925             if (LargerThan64Bits)
2926               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2927             else
2928               Coeff = Coeff1*Coeff2;
2929             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2930             const SCEV *Term1 = AddRec->getOperand(y-z);
2931             const SCEV *Term2 = OtherAddRec->getOperand(z);
2932             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2933                                                SCEV::FlagAnyWrap, Depth + 1),
2934                               SCEV::FlagAnyWrap, Depth + 1);
2935           }
2936         }
2937         AddRecOps.push_back(Term);
2938       }
2939       if (!Overflow) {
2940         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2941                                               SCEV::FlagAnyWrap);
2942         if (Ops.size() == 2) return NewAddRec;
2943         Ops[Idx] = NewAddRec;
2944         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2945         OpsModified = true;
2946         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2947         if (!AddRec)
2948           break;
2949       }
2950     }
2951     if (OpsModified)
2952       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2953 
2954     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2955     // next one.
2956   }
2957 
2958   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2959   // already have one, otherwise create a new one.
2960   return getOrCreateMulExpr(Ops, Flags);
2961 }
2962 
2963 /// Represents an unsigned remainder expression based on unsigned division.
2964 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
2965                                          const SCEV *RHS) {
2966   assert(getEffectiveSCEVType(LHS->getType()) ==
2967          getEffectiveSCEVType(RHS->getType()) &&
2968          "SCEVURemExpr operand types don't match!");
2969 
2970   // Short-circuit easy cases
2971   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2972     // If constant is one, the result is trivial
2973     if (RHSC->getValue()->isOne())
2974       return getZero(LHS->getType()); // X urem 1 --> 0
2975 
2976     // If constant is a power of two, fold into a zext(trunc(LHS)).
2977     if (RHSC->getAPInt().isPowerOf2()) {
2978       Type *FullTy = LHS->getType();
2979       Type *TruncTy =
2980           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
2981       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
2982     }
2983   }
2984 
2985   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
2986   const SCEV *UDiv = getUDivExpr(LHS, RHS);
2987   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
2988   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
2989 }
2990 
2991 /// Get a canonical unsigned division expression, or something simpler if
2992 /// possible.
2993 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2994                                          const SCEV *RHS) {
2995   assert(getEffectiveSCEVType(LHS->getType()) ==
2996          getEffectiveSCEVType(RHS->getType()) &&
2997          "SCEVUDivExpr operand types don't match!");
2998 
2999   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3000     if (RHSC->getValue()->isOne())
3001       return LHS;                               // X udiv 1 --> x
3002     // If the denominator is zero, the result of the udiv is undefined. Don't
3003     // try to analyze it, because the resolution chosen here may differ from
3004     // the resolution chosen in other parts of the compiler.
3005     if (!RHSC->getValue()->isZero()) {
3006       // Determine if the division can be folded into the operands of
3007       // its operands.
3008       // TODO: Generalize this to non-constants by using known-bits information.
3009       Type *Ty = LHS->getType();
3010       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3011       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3012       // For non-power-of-two values, effectively round the value up to the
3013       // nearest power of two.
3014       if (!RHSC->getAPInt().isPowerOf2())
3015         ++MaxShiftAmt;
3016       IntegerType *ExtTy =
3017         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3018       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3019         if (const SCEVConstant *Step =
3020             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3021           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3022           const APInt &StepInt = Step->getAPInt();
3023           const APInt &DivInt = RHSC->getAPInt();
3024           if (!StepInt.urem(DivInt) &&
3025               getZeroExtendExpr(AR, ExtTy) ==
3026               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3027                             getZeroExtendExpr(Step, ExtTy),
3028                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3029             SmallVector<const SCEV *, 4> Operands;
3030             for (const SCEV *Op : AR->operands())
3031               Operands.push_back(getUDivExpr(Op, RHS));
3032             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3033           }
3034           /// Get a canonical UDivExpr for a recurrence.
3035           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3036           // We can currently only fold X%N if X is constant.
3037           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3038           if (StartC && !DivInt.urem(StepInt) &&
3039               getZeroExtendExpr(AR, ExtTy) ==
3040               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3041                             getZeroExtendExpr(Step, ExtTy),
3042                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3043             const APInt &StartInt = StartC->getAPInt();
3044             const APInt &StartRem = StartInt.urem(StepInt);
3045             if (StartRem != 0)
3046               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3047                                   AR->getLoop(), SCEV::FlagNW);
3048           }
3049         }
3050       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3051       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3052         SmallVector<const SCEV *, 4> Operands;
3053         for (const SCEV *Op : M->operands())
3054           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3055         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3056           // Find an operand that's safely divisible.
3057           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3058             const SCEV *Op = M->getOperand(i);
3059             const SCEV *Div = getUDivExpr(Op, RHSC);
3060             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3061               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3062                                                       M->op_end());
3063               Operands[i] = Div;
3064               return getMulExpr(Operands);
3065             }
3066           }
3067       }
3068       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3069       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3070         SmallVector<const SCEV *, 4> Operands;
3071         for (const SCEV *Op : A->operands())
3072           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3073         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3074           Operands.clear();
3075           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3076             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3077             if (isa<SCEVUDivExpr>(Op) ||
3078                 getMulExpr(Op, RHS) != A->getOperand(i))
3079               break;
3080             Operands.push_back(Op);
3081           }
3082           if (Operands.size() == A->getNumOperands())
3083             return getAddExpr(Operands);
3084         }
3085       }
3086 
3087       // Fold if both operands are constant.
3088       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3089         Constant *LHSCV = LHSC->getValue();
3090         Constant *RHSCV = RHSC->getValue();
3091         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3092                                                                    RHSCV)));
3093       }
3094     }
3095   }
3096 
3097   FoldingSetNodeID ID;
3098   ID.AddInteger(scUDivExpr);
3099   ID.AddPointer(LHS);
3100   ID.AddPointer(RHS);
3101   void *IP = nullptr;
3102   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3103   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3104                                              LHS, RHS);
3105   UniqueSCEVs.InsertNode(S, IP);
3106   addToLoopUseLists(S);
3107   return S;
3108 }
3109 
3110 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3111   APInt A = C1->getAPInt().abs();
3112   APInt B = C2->getAPInt().abs();
3113   uint32_t ABW = A.getBitWidth();
3114   uint32_t BBW = B.getBitWidth();
3115 
3116   if (ABW > BBW)
3117     B = B.zext(ABW);
3118   else if (ABW < BBW)
3119     A = A.zext(BBW);
3120 
3121   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3122 }
3123 
3124 /// Get a canonical unsigned division expression, or something simpler if
3125 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3126 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3127 /// it's not exact because the udiv may be clearing bits.
3128 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3129                                               const SCEV *RHS) {
3130   // TODO: we could try to find factors in all sorts of things, but for now we
3131   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3132   // end of this file for inspiration.
3133 
3134   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3135   if (!Mul || !Mul->hasNoUnsignedWrap())
3136     return getUDivExpr(LHS, RHS);
3137 
3138   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3139     // If the mulexpr multiplies by a constant, then that constant must be the
3140     // first element of the mulexpr.
3141     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3142       if (LHSCst == RHSCst) {
3143         SmallVector<const SCEV *, 2> Operands;
3144         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3145         return getMulExpr(Operands);
3146       }
3147 
3148       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3149       // that there's a factor provided by one of the other terms. We need to
3150       // check.
3151       APInt Factor = gcd(LHSCst, RHSCst);
3152       if (!Factor.isIntN(1)) {
3153         LHSCst =
3154             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3155         RHSCst =
3156             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3157         SmallVector<const SCEV *, 2> Operands;
3158         Operands.push_back(LHSCst);
3159         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3160         LHS = getMulExpr(Operands);
3161         RHS = RHSCst;
3162         Mul = dyn_cast<SCEVMulExpr>(LHS);
3163         if (!Mul)
3164           return getUDivExactExpr(LHS, RHS);
3165       }
3166     }
3167   }
3168 
3169   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3170     if (Mul->getOperand(i) == RHS) {
3171       SmallVector<const SCEV *, 2> Operands;
3172       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3173       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3174       return getMulExpr(Operands);
3175     }
3176   }
3177 
3178   return getUDivExpr(LHS, RHS);
3179 }
3180 
3181 /// Get an add recurrence expression for the specified loop.  Simplify the
3182 /// expression as much as possible.
3183 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3184                                            const Loop *L,
3185                                            SCEV::NoWrapFlags Flags) {
3186   SmallVector<const SCEV *, 4> Operands;
3187   Operands.push_back(Start);
3188   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3189     if (StepChrec->getLoop() == L) {
3190       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3191       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3192     }
3193 
3194   Operands.push_back(Step);
3195   return getAddRecExpr(Operands, L, Flags);
3196 }
3197 
3198 /// Get an add recurrence expression for the specified loop.  Simplify the
3199 /// expression as much as possible.
3200 const SCEV *
3201 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3202                                const Loop *L, SCEV::NoWrapFlags Flags) {
3203   if (Operands.size() == 1) return Operands[0];
3204 #ifndef NDEBUG
3205   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3206   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3207     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3208            "SCEVAddRecExpr operand types don't match!");
3209   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3210     assert(isLoopInvariant(Operands[i], L) &&
3211            "SCEVAddRecExpr operand is not loop-invariant!");
3212 #endif
3213 
3214   if (Operands.back()->isZero()) {
3215     Operands.pop_back();
3216     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3217   }
3218 
3219   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3220   // use that information to infer NUW and NSW flags. However, computing a
3221   // BE count requires calling getAddRecExpr, so we may not yet have a
3222   // meaningful BE count at this point (and if we don't, we'd be stuck
3223   // with a SCEVCouldNotCompute as the cached BE count).
3224 
3225   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3226 
3227   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3228   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3229     const Loop *NestedLoop = NestedAR->getLoop();
3230     if (L->contains(NestedLoop)
3231             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3232             : (!NestedLoop->contains(L) &&
3233                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3234       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3235                                                   NestedAR->op_end());
3236       Operands[0] = NestedAR->getStart();
3237       // AddRecs require their operands be loop-invariant with respect to their
3238       // loops. Don't perform this transformation if it would break this
3239       // requirement.
3240       bool AllInvariant = all_of(
3241           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3242 
3243       if (AllInvariant) {
3244         // Create a recurrence for the outer loop with the same step size.
3245         //
3246         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3247         // inner recurrence has the same property.
3248         SCEV::NoWrapFlags OuterFlags =
3249           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3250 
3251         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3252         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3253           return isLoopInvariant(Op, NestedLoop);
3254         });
3255 
3256         if (AllInvariant) {
3257           // Ok, both add recurrences are valid after the transformation.
3258           //
3259           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3260           // the outer recurrence has the same property.
3261           SCEV::NoWrapFlags InnerFlags =
3262             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3263           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3264         }
3265       }
3266       // Reset Operands to its original state.
3267       Operands[0] = NestedAR;
3268     }
3269   }
3270 
3271   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3272   // already have one, otherwise create a new one.
3273   FoldingSetNodeID ID;
3274   ID.AddInteger(scAddRecExpr);
3275   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3276     ID.AddPointer(Operands[i]);
3277   ID.AddPointer(L);
3278   void *IP = nullptr;
3279   SCEVAddRecExpr *S =
3280     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3281   if (!S) {
3282     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3283     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3284     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3285                                            O, Operands.size(), L);
3286     UniqueSCEVs.InsertNode(S, IP);
3287     addToLoopUseLists(S);
3288   }
3289   S->setNoWrapFlags(Flags);
3290   return S;
3291 }
3292 
3293 const SCEV *
3294 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3295                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3296   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3297   // getSCEV(Base)->getType() has the same address space as Base->getType()
3298   // because SCEV::getType() preserves the address space.
3299   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3300   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3301   // instruction to its SCEV, because the Instruction may be guarded by control
3302   // flow and the no-overflow bits may not be valid for the expression in any
3303   // context. This can be fixed similarly to how these flags are handled for
3304   // adds.
3305   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3306                                              : SCEV::FlagAnyWrap;
3307 
3308   const SCEV *TotalOffset = getZero(IntPtrTy);
3309   // The array size is unimportant. The first thing we do on CurTy is getting
3310   // its element type.
3311   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3312   for (const SCEV *IndexExpr : IndexExprs) {
3313     // Compute the (potentially symbolic) offset in bytes for this index.
3314     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3315       // For a struct, add the member offset.
3316       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3317       unsigned FieldNo = Index->getZExtValue();
3318       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3319 
3320       // Add the field offset to the running total offset.
3321       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3322 
3323       // Update CurTy to the type of the field at Index.
3324       CurTy = STy->getTypeAtIndex(Index);
3325     } else {
3326       // Update CurTy to its element type.
3327       CurTy = cast<SequentialType>(CurTy)->getElementType();
3328       // For an array, add the element offset, explicitly scaled.
3329       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3330       // Getelementptr indices are signed.
3331       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3332 
3333       // Multiply the index by the element size to compute the element offset.
3334       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3335 
3336       // Add the element offset to the running total offset.
3337       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3338     }
3339   }
3340 
3341   // Add the total offset from all the GEP indices to the base.
3342   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3343 }
3344 
3345 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3346                                          const SCEV *RHS) {
3347   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3348   return getSMaxExpr(Ops);
3349 }
3350 
3351 const SCEV *
3352 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3353   assert(!Ops.empty() && "Cannot get empty smax!");
3354   if (Ops.size() == 1) return Ops[0];
3355 #ifndef NDEBUG
3356   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3357   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3358     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3359            "SCEVSMaxExpr operand types don't match!");
3360 #endif
3361 
3362   // Sort by complexity, this groups all similar expression types together.
3363   GroupByComplexity(Ops, &LI, DT);
3364 
3365   // If there are any constants, fold them together.
3366   unsigned Idx = 0;
3367   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3368     ++Idx;
3369     assert(Idx < Ops.size());
3370     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3371       // We found two constants, fold them together!
3372       ConstantInt *Fold = ConstantInt::get(
3373           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3374       Ops[0] = getConstant(Fold);
3375       Ops.erase(Ops.begin()+1);  // Erase the folded element
3376       if (Ops.size() == 1) return Ops[0];
3377       LHSC = cast<SCEVConstant>(Ops[0]);
3378     }
3379 
3380     // If we are left with a constant minimum-int, strip it off.
3381     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3382       Ops.erase(Ops.begin());
3383       --Idx;
3384     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3385       // If we have an smax with a constant maximum-int, it will always be
3386       // maximum-int.
3387       return Ops[0];
3388     }
3389 
3390     if (Ops.size() == 1) return Ops[0];
3391   }
3392 
3393   // Find the first SMax
3394   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3395     ++Idx;
3396 
3397   // Check to see if one of the operands is an SMax. If so, expand its operands
3398   // onto our operand list, and recurse to simplify.
3399   if (Idx < Ops.size()) {
3400     bool DeletedSMax = false;
3401     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3402       Ops.erase(Ops.begin()+Idx);
3403       Ops.append(SMax->op_begin(), SMax->op_end());
3404       DeletedSMax = true;
3405     }
3406 
3407     if (DeletedSMax)
3408       return getSMaxExpr(Ops);
3409   }
3410 
3411   // Okay, check to see if the same value occurs in the operand list twice.  If
3412   // so, delete one.  Since we sorted the list, these values are required to
3413   // be adjacent.
3414   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3415     //  X smax Y smax Y  -->  X smax Y
3416     //  X smax Y         -->  X, if X is always greater than Y
3417     if (Ops[i] == Ops[i+1] ||
3418         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3419       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3420       --i; --e;
3421     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3422       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3423       --i; --e;
3424     }
3425 
3426   if (Ops.size() == 1) return Ops[0];
3427 
3428   assert(!Ops.empty() && "Reduced smax down to nothing!");
3429 
3430   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3431   // already have one, otherwise create a new one.
3432   FoldingSetNodeID ID;
3433   ID.AddInteger(scSMaxExpr);
3434   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3435     ID.AddPointer(Ops[i]);
3436   void *IP = nullptr;
3437   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3438   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3439   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3440   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3441                                              O, Ops.size());
3442   UniqueSCEVs.InsertNode(S, IP);
3443   addToLoopUseLists(S);
3444   return S;
3445 }
3446 
3447 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3448                                          const SCEV *RHS) {
3449   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3450   return getUMaxExpr(Ops);
3451 }
3452 
3453 const SCEV *
3454 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3455   assert(!Ops.empty() && "Cannot get empty umax!");
3456   if (Ops.size() == 1) return Ops[0];
3457 #ifndef NDEBUG
3458   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3459   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3460     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3461            "SCEVUMaxExpr operand types don't match!");
3462 #endif
3463 
3464   // Sort by complexity, this groups all similar expression types together.
3465   GroupByComplexity(Ops, &LI, DT);
3466 
3467   // If there are any constants, fold them together.
3468   unsigned Idx = 0;
3469   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3470     ++Idx;
3471     assert(Idx < Ops.size());
3472     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3473       // We found two constants, fold them together!
3474       ConstantInt *Fold = ConstantInt::get(
3475           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3476       Ops[0] = getConstant(Fold);
3477       Ops.erase(Ops.begin()+1);  // Erase the folded element
3478       if (Ops.size() == 1) return Ops[0];
3479       LHSC = cast<SCEVConstant>(Ops[0]);
3480     }
3481 
3482     // If we are left with a constant minimum-int, strip it off.
3483     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3484       Ops.erase(Ops.begin());
3485       --Idx;
3486     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3487       // If we have an umax with a constant maximum-int, it will always be
3488       // maximum-int.
3489       return Ops[0];
3490     }
3491 
3492     if (Ops.size() == 1) return Ops[0];
3493   }
3494 
3495   // Find the first UMax
3496   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3497     ++Idx;
3498 
3499   // Check to see if one of the operands is a UMax. If so, expand its operands
3500   // onto our operand list, and recurse to simplify.
3501   if (Idx < Ops.size()) {
3502     bool DeletedUMax = false;
3503     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3504       Ops.erase(Ops.begin()+Idx);
3505       Ops.append(UMax->op_begin(), UMax->op_end());
3506       DeletedUMax = true;
3507     }
3508 
3509     if (DeletedUMax)
3510       return getUMaxExpr(Ops);
3511   }
3512 
3513   // Okay, check to see if the same value occurs in the operand list twice.  If
3514   // so, delete one.  Since we sorted the list, these values are required to
3515   // be adjacent.
3516   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3517     //  X umax Y umax Y  -->  X umax Y
3518     //  X umax Y         -->  X, if X is always greater than Y
3519     if (Ops[i] == Ops[i+1] ||
3520         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3521       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3522       --i; --e;
3523     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3524       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3525       --i; --e;
3526     }
3527 
3528   if (Ops.size() == 1) return Ops[0];
3529 
3530   assert(!Ops.empty() && "Reduced umax down to nothing!");
3531 
3532   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3533   // already have one, otherwise create a new one.
3534   FoldingSetNodeID ID;
3535   ID.AddInteger(scUMaxExpr);
3536   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3537     ID.AddPointer(Ops[i]);
3538   void *IP = nullptr;
3539   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3540   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3541   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3542   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3543                                              O, Ops.size());
3544   UniqueSCEVs.InsertNode(S, IP);
3545   addToLoopUseLists(S);
3546   return S;
3547 }
3548 
3549 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3550                                          const SCEV *RHS) {
3551   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3552   return getSMinExpr(Ops);
3553 }
3554 
3555 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3556   // ~smax(~x, ~y, ~z) == smin(x, y, z).
3557   SmallVector<const SCEV *, 2> NotOps;
3558   for (auto *S : Ops)
3559     NotOps.push_back(getNotSCEV(S));
3560   return getNotSCEV(getSMaxExpr(NotOps));
3561 }
3562 
3563 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3564                                          const SCEV *RHS) {
3565   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3566   return getUMinExpr(Ops);
3567 }
3568 
3569 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3570   assert(!Ops.empty() && "At least one operand must be!");
3571   // Trivial case.
3572   if (Ops.size() == 1)
3573     return Ops[0];
3574 
3575   // ~umax(~x, ~y, ~z) == umin(x, y, z).
3576   SmallVector<const SCEV *, 2> NotOps;
3577   for (auto *S : Ops)
3578     NotOps.push_back(getNotSCEV(S));
3579   return getNotSCEV(getUMaxExpr(NotOps));
3580 }
3581 
3582 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3583   // We can bypass creating a target-independent
3584   // constant expression and then folding it back into a ConstantInt.
3585   // This is just a compile-time optimization.
3586   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3587 }
3588 
3589 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3590                                              StructType *STy,
3591                                              unsigned FieldNo) {
3592   // We can bypass creating a target-independent
3593   // constant expression and then folding it back into a ConstantInt.
3594   // This is just a compile-time optimization.
3595   return getConstant(
3596       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3597 }
3598 
3599 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3600   // Don't attempt to do anything other than create a SCEVUnknown object
3601   // here.  createSCEV only calls getUnknown after checking for all other
3602   // interesting possibilities, and any other code that calls getUnknown
3603   // is doing so in order to hide a value from SCEV canonicalization.
3604 
3605   FoldingSetNodeID ID;
3606   ID.AddInteger(scUnknown);
3607   ID.AddPointer(V);
3608   void *IP = nullptr;
3609   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3610     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3611            "Stale SCEVUnknown in uniquing map!");
3612     return S;
3613   }
3614   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3615                                             FirstUnknown);
3616   FirstUnknown = cast<SCEVUnknown>(S);
3617   UniqueSCEVs.InsertNode(S, IP);
3618   return S;
3619 }
3620 
3621 //===----------------------------------------------------------------------===//
3622 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3623 //
3624 
3625 /// Test if values of the given type are analyzable within the SCEV
3626 /// framework. This primarily includes integer types, and it can optionally
3627 /// include pointer types if the ScalarEvolution class has access to
3628 /// target-specific information.
3629 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3630   // Integers and pointers are always SCEVable.
3631   return Ty->isIntegerTy() || Ty->isPointerTy();
3632 }
3633 
3634 /// Return the size in bits of the specified type, for which isSCEVable must
3635 /// return true.
3636 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3637   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3638   if (Ty->isPointerTy())
3639     return getDataLayout().getIndexTypeSizeInBits(Ty);
3640   return getDataLayout().getTypeSizeInBits(Ty);
3641 }
3642 
3643 /// Return a type with the same bitwidth as the given type and which represents
3644 /// how SCEV will treat the given type, for which isSCEVable must return
3645 /// true. For pointer types, this is the pointer-sized integer type.
3646 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3647   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3648 
3649   if (Ty->isIntegerTy())
3650     return Ty;
3651 
3652   // The only other support type is pointer.
3653   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3654   return getDataLayout().getIntPtrType(Ty);
3655 }
3656 
3657 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3658   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3659 }
3660 
3661 const SCEV *ScalarEvolution::getCouldNotCompute() {
3662   return CouldNotCompute.get();
3663 }
3664 
3665 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3666   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3667     auto *SU = dyn_cast<SCEVUnknown>(S);
3668     return SU && SU->getValue() == nullptr;
3669   });
3670 
3671   return !ContainsNulls;
3672 }
3673 
3674 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3675   HasRecMapType::iterator I = HasRecMap.find(S);
3676   if (I != HasRecMap.end())
3677     return I->second;
3678 
3679   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3680   HasRecMap.insert({S, FoundAddRec});
3681   return FoundAddRec;
3682 }
3683 
3684 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3685 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3686 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3687 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3688   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3689   if (!Add)
3690     return {S, nullptr};
3691 
3692   if (Add->getNumOperands() != 2)
3693     return {S, nullptr};
3694 
3695   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3696   if (!ConstOp)
3697     return {S, nullptr};
3698 
3699   return {Add->getOperand(1), ConstOp->getValue()};
3700 }
3701 
3702 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3703 /// by the value and offset from any ValueOffsetPair in the set.
3704 SetVector<ScalarEvolution::ValueOffsetPair> *
3705 ScalarEvolution::getSCEVValues(const SCEV *S) {
3706   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3707   if (SI == ExprValueMap.end())
3708     return nullptr;
3709 #ifndef NDEBUG
3710   if (VerifySCEVMap) {
3711     // Check there is no dangling Value in the set returned.
3712     for (const auto &VE : SI->second)
3713       assert(ValueExprMap.count(VE.first));
3714   }
3715 #endif
3716   return &SI->second;
3717 }
3718 
3719 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3720 /// cannot be used separately. eraseValueFromMap should be used to remove
3721 /// V from ValueExprMap and ExprValueMap at the same time.
3722 void ScalarEvolution::eraseValueFromMap(Value *V) {
3723   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3724   if (I != ValueExprMap.end()) {
3725     const SCEV *S = I->second;
3726     // Remove {V, 0} from the set of ExprValueMap[S]
3727     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3728       SV->remove({V, nullptr});
3729 
3730     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3731     const SCEV *Stripped;
3732     ConstantInt *Offset;
3733     std::tie(Stripped, Offset) = splitAddExpr(S);
3734     if (Offset != nullptr) {
3735       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3736         SV->remove({V, Offset});
3737     }
3738     ValueExprMap.erase(V);
3739   }
3740 }
3741 
3742 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3743 /// TODO: In reality it is better to check the poison recursevely
3744 /// but this is better than nothing.
3745 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3746   if (auto *I = dyn_cast<Instruction>(V)) {
3747     if (isa<OverflowingBinaryOperator>(I)) {
3748       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3749         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3750           return true;
3751         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3752           return true;
3753       }
3754     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3755       return true;
3756   }
3757   return false;
3758 }
3759 
3760 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3761 /// create a new one.
3762 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3763   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3764 
3765   const SCEV *S = getExistingSCEV(V);
3766   if (S == nullptr) {
3767     S = createSCEV(V);
3768     // During PHI resolution, it is possible to create two SCEVs for the same
3769     // V, so it is needed to double check whether V->S is inserted into
3770     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3771     std::pair<ValueExprMapType::iterator, bool> Pair =
3772         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3773     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3774       ExprValueMap[S].insert({V, nullptr});
3775 
3776       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3777       // ExprValueMap.
3778       const SCEV *Stripped = S;
3779       ConstantInt *Offset = nullptr;
3780       std::tie(Stripped, Offset) = splitAddExpr(S);
3781       // If stripped is SCEVUnknown, don't bother to save
3782       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3783       // increase the complexity of the expansion code.
3784       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3785       // because it may generate add/sub instead of GEP in SCEV expansion.
3786       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3787           !isa<GetElementPtrInst>(V))
3788         ExprValueMap[Stripped].insert({V, Offset});
3789     }
3790   }
3791   return S;
3792 }
3793 
3794 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3795   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3796 
3797   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3798   if (I != ValueExprMap.end()) {
3799     const SCEV *S = I->second;
3800     if (checkValidity(S))
3801       return S;
3802     eraseValueFromMap(V);
3803     forgetMemoizedResults(S);
3804   }
3805   return nullptr;
3806 }
3807 
3808 /// Return a SCEV corresponding to -V = -1*V
3809 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3810                                              SCEV::NoWrapFlags Flags) {
3811   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3812     return getConstant(
3813                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3814 
3815   Type *Ty = V->getType();
3816   Ty = getEffectiveSCEVType(Ty);
3817   return getMulExpr(
3818       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3819 }
3820 
3821 /// Return a SCEV corresponding to ~V = -1-V
3822 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3823   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3824     return getConstant(
3825                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3826 
3827   Type *Ty = V->getType();
3828   Ty = getEffectiveSCEVType(Ty);
3829   const SCEV *AllOnes =
3830                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3831   return getMinusSCEV(AllOnes, V);
3832 }
3833 
3834 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3835                                           SCEV::NoWrapFlags Flags,
3836                                           unsigned Depth) {
3837   // Fast path: X - X --> 0.
3838   if (LHS == RHS)
3839     return getZero(LHS->getType());
3840 
3841   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3842   // makes it so that we cannot make much use of NUW.
3843   auto AddFlags = SCEV::FlagAnyWrap;
3844   const bool RHSIsNotMinSigned =
3845       !getSignedRangeMin(RHS).isMinSignedValue();
3846   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3847     // Let M be the minimum representable signed value. Then (-1)*RHS
3848     // signed-wraps if and only if RHS is M. That can happen even for
3849     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3850     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3851     // (-1)*RHS, we need to prove that RHS != M.
3852     //
3853     // If LHS is non-negative and we know that LHS - RHS does not
3854     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3855     // either by proving that RHS > M or that LHS >= 0.
3856     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3857       AddFlags = SCEV::FlagNSW;
3858     }
3859   }
3860 
3861   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3862   // RHS is NSW and LHS >= 0.
3863   //
3864   // The difficulty here is that the NSW flag may have been proven
3865   // relative to a loop that is to be found in a recurrence in LHS and
3866   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3867   // larger scope than intended.
3868   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3869 
3870   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3871 }
3872 
3873 const SCEV *
3874 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3875   Type *SrcTy = V->getType();
3876   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3877          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3878          "Cannot truncate or zero extend with non-integer arguments!");
3879   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3880     return V;  // No conversion
3881   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3882     return getTruncateExpr(V, Ty);
3883   return getZeroExtendExpr(V, Ty);
3884 }
3885 
3886 const SCEV *
3887 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3888                                          Type *Ty) {
3889   Type *SrcTy = V->getType();
3890   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3891          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3892          "Cannot truncate or zero extend with non-integer arguments!");
3893   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3894     return V;  // No conversion
3895   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3896     return getTruncateExpr(V, Ty);
3897   return getSignExtendExpr(V, Ty);
3898 }
3899 
3900 const SCEV *
3901 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3902   Type *SrcTy = V->getType();
3903   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3904          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3905          "Cannot noop or zero extend with non-integer arguments!");
3906   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3907          "getNoopOrZeroExtend cannot truncate!");
3908   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3909     return V;  // No conversion
3910   return getZeroExtendExpr(V, Ty);
3911 }
3912 
3913 const SCEV *
3914 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3915   Type *SrcTy = V->getType();
3916   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3917          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3918          "Cannot noop or sign extend with non-integer arguments!");
3919   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3920          "getNoopOrSignExtend cannot truncate!");
3921   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3922     return V;  // No conversion
3923   return getSignExtendExpr(V, Ty);
3924 }
3925 
3926 const SCEV *
3927 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3928   Type *SrcTy = V->getType();
3929   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3930          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3931          "Cannot noop or any extend with non-integer arguments!");
3932   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3933          "getNoopOrAnyExtend cannot truncate!");
3934   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3935     return V;  // No conversion
3936   return getAnyExtendExpr(V, Ty);
3937 }
3938 
3939 const SCEV *
3940 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3941   Type *SrcTy = V->getType();
3942   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3943          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3944          "Cannot truncate or noop with non-integer arguments!");
3945   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3946          "getTruncateOrNoop cannot extend!");
3947   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3948     return V;  // No conversion
3949   return getTruncateExpr(V, Ty);
3950 }
3951 
3952 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3953                                                         const SCEV *RHS) {
3954   const SCEV *PromotedLHS = LHS;
3955   const SCEV *PromotedRHS = RHS;
3956 
3957   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3958     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3959   else
3960     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3961 
3962   return getUMaxExpr(PromotedLHS, PromotedRHS);
3963 }
3964 
3965 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3966                                                         const SCEV *RHS) {
3967   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3968   return getUMinFromMismatchedTypes(Ops);
3969 }
3970 
3971 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
3972     SmallVectorImpl<const SCEV *> &Ops) {
3973   assert(!Ops.empty() && "At least one operand must be!");
3974   // Trivial case.
3975   if (Ops.size() == 1)
3976     return Ops[0];
3977 
3978   // Find the max type first.
3979   Type *MaxType = nullptr;
3980   for (auto *S : Ops)
3981     if (MaxType)
3982       MaxType = getWiderType(MaxType, S->getType());
3983     else
3984       MaxType = S->getType();
3985 
3986   // Extend all ops to max type.
3987   SmallVector<const SCEV *, 2> PromotedOps;
3988   for (auto *S : Ops)
3989     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
3990 
3991   // Generate umin.
3992   return getUMinExpr(PromotedOps);
3993 }
3994 
3995 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3996   // A pointer operand may evaluate to a nonpointer expression, such as null.
3997   if (!V->getType()->isPointerTy())
3998     return V;
3999 
4000   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4001     return getPointerBase(Cast->getOperand());
4002   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4003     const SCEV *PtrOp = nullptr;
4004     for (const SCEV *NAryOp : NAry->operands()) {
4005       if (NAryOp->getType()->isPointerTy()) {
4006         // Cannot find the base of an expression with multiple pointer operands.
4007         if (PtrOp)
4008           return V;
4009         PtrOp = NAryOp;
4010       }
4011     }
4012     if (!PtrOp)
4013       return V;
4014     return getPointerBase(PtrOp);
4015   }
4016   return V;
4017 }
4018 
4019 /// Push users of the given Instruction onto the given Worklist.
4020 static void
4021 PushDefUseChildren(Instruction *I,
4022                    SmallVectorImpl<Instruction *> &Worklist) {
4023   // Push the def-use children onto the Worklist stack.
4024   for (User *U : I->users())
4025     Worklist.push_back(cast<Instruction>(U));
4026 }
4027 
4028 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4029   SmallVector<Instruction *, 16> Worklist;
4030   PushDefUseChildren(PN, Worklist);
4031 
4032   SmallPtrSet<Instruction *, 8> Visited;
4033   Visited.insert(PN);
4034   while (!Worklist.empty()) {
4035     Instruction *I = Worklist.pop_back_val();
4036     if (!Visited.insert(I).second)
4037       continue;
4038 
4039     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4040     if (It != ValueExprMap.end()) {
4041       const SCEV *Old = It->second;
4042 
4043       // Short-circuit the def-use traversal if the symbolic name
4044       // ceases to appear in expressions.
4045       if (Old != SymName && !hasOperand(Old, SymName))
4046         continue;
4047 
4048       // SCEVUnknown for a PHI either means that it has an unrecognized
4049       // structure, it's a PHI that's in the progress of being computed
4050       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4051       // additional loop trip count information isn't going to change anything.
4052       // In the second case, createNodeForPHI will perform the necessary
4053       // updates on its own when it gets to that point. In the third, we do
4054       // want to forget the SCEVUnknown.
4055       if (!isa<PHINode>(I) ||
4056           !isa<SCEVUnknown>(Old) ||
4057           (I != PN && Old == SymName)) {
4058         eraseValueFromMap(It->first);
4059         forgetMemoizedResults(Old);
4060       }
4061     }
4062 
4063     PushDefUseChildren(I, Worklist);
4064   }
4065 }
4066 
4067 namespace {
4068 
4069 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4070 /// expression in case its Loop is L. If it is not L then
4071 /// if IgnoreOtherLoops is true then use AddRec itself
4072 /// otherwise rewrite cannot be done.
4073 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4074 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4075 public:
4076   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4077                              bool IgnoreOtherLoops = true) {
4078     SCEVInitRewriter Rewriter(L, SE);
4079     const SCEV *Result = Rewriter.visit(S);
4080     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4081       return SE.getCouldNotCompute();
4082     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4083                ? SE.getCouldNotCompute()
4084                : Result;
4085   }
4086 
4087   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4088     if (!SE.isLoopInvariant(Expr, L))
4089       SeenLoopVariantSCEVUnknown = true;
4090     return Expr;
4091   }
4092 
4093   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4094     // Only re-write AddRecExprs for this loop.
4095     if (Expr->getLoop() == L)
4096       return Expr->getStart();
4097     SeenOtherLoops = true;
4098     return Expr;
4099   }
4100 
4101   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4102 
4103   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4104 
4105 private:
4106   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4107       : SCEVRewriteVisitor(SE), L(L) {}
4108 
4109   const Loop *L;
4110   bool SeenLoopVariantSCEVUnknown = false;
4111   bool SeenOtherLoops = false;
4112 };
4113 
4114 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4115 /// increment expression in case its Loop is L. If it is not L then
4116 /// use AddRec itself.
4117 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4118 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4119 public:
4120   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4121     SCEVPostIncRewriter Rewriter(L, SE);
4122     const SCEV *Result = Rewriter.visit(S);
4123     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4124         ? SE.getCouldNotCompute()
4125         : Result;
4126   }
4127 
4128   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4129     if (!SE.isLoopInvariant(Expr, L))
4130       SeenLoopVariantSCEVUnknown = true;
4131     return Expr;
4132   }
4133 
4134   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4135     // Only re-write AddRecExprs for this loop.
4136     if (Expr->getLoop() == L)
4137       return Expr->getPostIncExpr(SE);
4138     SeenOtherLoops = true;
4139     return Expr;
4140   }
4141 
4142   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4143 
4144   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4145 
4146 private:
4147   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4148       : SCEVRewriteVisitor(SE), L(L) {}
4149 
4150   const Loop *L;
4151   bool SeenLoopVariantSCEVUnknown = false;
4152   bool SeenOtherLoops = false;
4153 };
4154 
4155 /// This class evaluates the compare condition by matching it against the
4156 /// condition of loop latch. If there is a match we assume a true value
4157 /// for the condition while building SCEV nodes.
4158 class SCEVBackedgeConditionFolder
4159     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4160 public:
4161   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4162                              ScalarEvolution &SE) {
4163     bool IsPosBECond = false;
4164     Value *BECond = nullptr;
4165     if (BasicBlock *Latch = L->getLoopLatch()) {
4166       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4167       if (BI && BI->isConditional()) {
4168         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4169                "Both outgoing branches should not target same header!");
4170         BECond = BI->getCondition();
4171         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4172       } else {
4173         return S;
4174       }
4175     }
4176     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4177     return Rewriter.visit(S);
4178   }
4179 
4180   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4181     const SCEV *Result = Expr;
4182     bool InvariantF = SE.isLoopInvariant(Expr, L);
4183 
4184     if (!InvariantF) {
4185       Instruction *I = cast<Instruction>(Expr->getValue());
4186       switch (I->getOpcode()) {
4187       case Instruction::Select: {
4188         SelectInst *SI = cast<SelectInst>(I);
4189         Optional<const SCEV *> Res =
4190             compareWithBackedgeCondition(SI->getCondition());
4191         if (Res.hasValue()) {
4192           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4193           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4194         }
4195         break;
4196       }
4197       default: {
4198         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4199         if (Res.hasValue())
4200           Result = Res.getValue();
4201         break;
4202       }
4203       }
4204     }
4205     return Result;
4206   }
4207 
4208 private:
4209   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4210                                        bool IsPosBECond, ScalarEvolution &SE)
4211       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4212         IsPositiveBECond(IsPosBECond) {}
4213 
4214   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4215 
4216   const Loop *L;
4217   /// Loop back condition.
4218   Value *BackedgeCond = nullptr;
4219   /// Set to true if loop back is on positive branch condition.
4220   bool IsPositiveBECond;
4221 };
4222 
4223 Optional<const SCEV *>
4224 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4225 
4226   // If value matches the backedge condition for loop latch,
4227   // then return a constant evolution node based on loopback
4228   // branch taken.
4229   if (BackedgeCond == IC)
4230     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4231                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4232   return None;
4233 }
4234 
4235 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4236 public:
4237   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4238                              ScalarEvolution &SE) {
4239     SCEVShiftRewriter Rewriter(L, SE);
4240     const SCEV *Result = Rewriter.visit(S);
4241     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4242   }
4243 
4244   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4245     // Only allow AddRecExprs for this loop.
4246     if (!SE.isLoopInvariant(Expr, L))
4247       Valid = false;
4248     return Expr;
4249   }
4250 
4251   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4252     if (Expr->getLoop() == L && Expr->isAffine())
4253       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4254     Valid = false;
4255     return Expr;
4256   }
4257 
4258   bool isValid() { return Valid; }
4259 
4260 private:
4261   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4262       : SCEVRewriteVisitor(SE), L(L) {}
4263 
4264   const Loop *L;
4265   bool Valid = true;
4266 };
4267 
4268 } // end anonymous namespace
4269 
4270 SCEV::NoWrapFlags
4271 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4272   if (!AR->isAffine())
4273     return SCEV::FlagAnyWrap;
4274 
4275   using OBO = OverflowingBinaryOperator;
4276 
4277   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4278 
4279   if (!AR->hasNoSignedWrap()) {
4280     ConstantRange AddRecRange = getSignedRange(AR);
4281     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4282 
4283     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4284         Instruction::Add, IncRange, OBO::NoSignedWrap);
4285     if (NSWRegion.contains(AddRecRange))
4286       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4287   }
4288 
4289   if (!AR->hasNoUnsignedWrap()) {
4290     ConstantRange AddRecRange = getUnsignedRange(AR);
4291     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4292 
4293     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4294         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4295     if (NUWRegion.contains(AddRecRange))
4296       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4297   }
4298 
4299   return Result;
4300 }
4301 
4302 namespace {
4303 
4304 /// Represents an abstract binary operation.  This may exist as a
4305 /// normal instruction or constant expression, or may have been
4306 /// derived from an expression tree.
4307 struct BinaryOp {
4308   unsigned Opcode;
4309   Value *LHS;
4310   Value *RHS;
4311   bool IsNSW = false;
4312   bool IsNUW = false;
4313 
4314   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4315   /// constant expression.
4316   Operator *Op = nullptr;
4317 
4318   explicit BinaryOp(Operator *Op)
4319       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4320         Op(Op) {
4321     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4322       IsNSW = OBO->hasNoSignedWrap();
4323       IsNUW = OBO->hasNoUnsignedWrap();
4324     }
4325   }
4326 
4327   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4328                     bool IsNUW = false)
4329       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4330 };
4331 
4332 } // end anonymous namespace
4333 
4334 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4335 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4336   auto *Op = dyn_cast<Operator>(V);
4337   if (!Op)
4338     return None;
4339 
4340   // Implementation detail: all the cleverness here should happen without
4341   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4342   // SCEV expressions when possible, and we should not break that.
4343 
4344   switch (Op->getOpcode()) {
4345   case Instruction::Add:
4346   case Instruction::Sub:
4347   case Instruction::Mul:
4348   case Instruction::UDiv:
4349   case Instruction::URem:
4350   case Instruction::And:
4351   case Instruction::Or:
4352   case Instruction::AShr:
4353   case Instruction::Shl:
4354     return BinaryOp(Op);
4355 
4356   case Instruction::Xor:
4357     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4358       // If the RHS of the xor is a signmask, then this is just an add.
4359       // Instcombine turns add of signmask into xor as a strength reduction step.
4360       if (RHSC->getValue().isSignMask())
4361         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4362     return BinaryOp(Op);
4363 
4364   case Instruction::LShr:
4365     // Turn logical shift right of a constant into a unsigned divide.
4366     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4367       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4368 
4369       // If the shift count is not less than the bitwidth, the result of
4370       // the shift is undefined. Don't try to analyze it, because the
4371       // resolution chosen here may differ from the resolution chosen in
4372       // other parts of the compiler.
4373       if (SA->getValue().ult(BitWidth)) {
4374         Constant *X =
4375             ConstantInt::get(SA->getContext(),
4376                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4377         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4378       }
4379     }
4380     return BinaryOp(Op);
4381 
4382   case Instruction::ExtractValue: {
4383     auto *EVI = cast<ExtractValueInst>(Op);
4384     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4385       break;
4386 
4387     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4388     if (!CI)
4389       break;
4390 
4391     if (auto *F = CI->getCalledFunction())
4392       switch (F->getIntrinsicID()) {
4393       case Intrinsic::sadd_with_overflow:
4394       case Intrinsic::uadd_with_overflow:
4395         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4396           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4397                           CI->getArgOperand(1));
4398 
4399         // Now that we know that all uses of the arithmetic-result component of
4400         // CI are guarded by the overflow check, we can go ahead and pretend
4401         // that the arithmetic is non-overflowing.
4402         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4403           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4404                           CI->getArgOperand(1), /* IsNSW = */ true,
4405                           /* IsNUW = */ false);
4406         else
4407           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4408                           CI->getArgOperand(1), /* IsNSW = */ false,
4409                           /* IsNUW*/ true);
4410       case Intrinsic::ssub_with_overflow:
4411       case Intrinsic::usub_with_overflow:
4412         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4413           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4414                           CI->getArgOperand(1));
4415 
4416         // The same reasoning as sadd/uadd above.
4417         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4418           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4419                           CI->getArgOperand(1), /* IsNSW = */ true,
4420                           /* IsNUW = */ false);
4421         else
4422           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4423                           CI->getArgOperand(1), /* IsNSW = */ false,
4424                           /* IsNUW = */ true);
4425       case Intrinsic::smul_with_overflow:
4426       case Intrinsic::umul_with_overflow:
4427         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4428                         CI->getArgOperand(1));
4429       default:
4430         break;
4431       }
4432     break;
4433   }
4434 
4435   default:
4436     break;
4437   }
4438 
4439   return None;
4440 }
4441 
4442 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4443 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4444 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4445 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4446 /// follows one of the following patterns:
4447 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4448 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4449 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4450 /// we return the type of the truncation operation, and indicate whether the
4451 /// truncated type should be treated as signed/unsigned by setting
4452 /// \p Signed to true/false, respectively.
4453 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4454                                bool &Signed, ScalarEvolution &SE) {
4455   // The case where Op == SymbolicPHI (that is, with no type conversions on
4456   // the way) is handled by the regular add recurrence creating logic and
4457   // would have already been triggered in createAddRecForPHI. Reaching it here
4458   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4459   // because one of the other operands of the SCEVAddExpr updating this PHI is
4460   // not invariant).
4461   //
4462   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4463   // this case predicates that allow us to prove that Op == SymbolicPHI will
4464   // be added.
4465   if (Op == SymbolicPHI)
4466     return nullptr;
4467 
4468   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4469   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4470   if (SourceBits != NewBits)
4471     return nullptr;
4472 
4473   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4474   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4475   if (!SExt && !ZExt)
4476     return nullptr;
4477   const SCEVTruncateExpr *Trunc =
4478       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4479            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4480   if (!Trunc)
4481     return nullptr;
4482   const SCEV *X = Trunc->getOperand();
4483   if (X != SymbolicPHI)
4484     return nullptr;
4485   Signed = SExt != nullptr;
4486   return Trunc->getType();
4487 }
4488 
4489 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4490   if (!PN->getType()->isIntegerTy())
4491     return nullptr;
4492   const Loop *L = LI.getLoopFor(PN->getParent());
4493   if (!L || L->getHeader() != PN->getParent())
4494     return nullptr;
4495   return L;
4496 }
4497 
4498 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4499 // computation that updates the phi follows the following pattern:
4500 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4501 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4502 // If so, try to see if it can be rewritten as an AddRecExpr under some
4503 // Predicates. If successful, return them as a pair. Also cache the results
4504 // of the analysis.
4505 //
4506 // Example usage scenario:
4507 //    Say the Rewriter is called for the following SCEV:
4508 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4509 //    where:
4510 //         %X = phi i64 (%Start, %BEValue)
4511 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4512 //    and call this function with %SymbolicPHI = %X.
4513 //
4514 //    The analysis will find that the value coming around the backedge has
4515 //    the following SCEV:
4516 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4517 //    Upon concluding that this matches the desired pattern, the function
4518 //    will return the pair {NewAddRec, SmallPredsVec} where:
4519 //         NewAddRec = {%Start,+,%Step}
4520 //         SmallPredsVec = {P1, P2, P3} as follows:
4521 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4522 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4523 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4524 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4525 //    under the predicates {P1,P2,P3}.
4526 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4527 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4528 //
4529 // TODO's:
4530 //
4531 // 1) Extend the Induction descriptor to also support inductions that involve
4532 //    casts: When needed (namely, when we are called in the context of the
4533 //    vectorizer induction analysis), a Set of cast instructions will be
4534 //    populated by this method, and provided back to isInductionPHI. This is
4535 //    needed to allow the vectorizer to properly record them to be ignored by
4536 //    the cost model and to avoid vectorizing them (otherwise these casts,
4537 //    which are redundant under the runtime overflow checks, will be
4538 //    vectorized, which can be costly).
4539 //
4540 // 2) Support additional induction/PHISCEV patterns: We also want to support
4541 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4542 //    after the induction update operation (the induction increment):
4543 //
4544 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4545 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4546 //
4547 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4548 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4549 //
4550 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4551 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4552 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4553   SmallVector<const SCEVPredicate *, 3> Predicates;
4554 
4555   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4556   // return an AddRec expression under some predicate.
4557 
4558   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4559   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4560   assert(L && "Expecting an integer loop header phi");
4561 
4562   // The loop may have multiple entrances or multiple exits; we can analyze
4563   // this phi as an addrec if it has a unique entry value and a unique
4564   // backedge value.
4565   Value *BEValueV = nullptr, *StartValueV = nullptr;
4566   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4567     Value *V = PN->getIncomingValue(i);
4568     if (L->contains(PN->getIncomingBlock(i))) {
4569       if (!BEValueV) {
4570         BEValueV = V;
4571       } else if (BEValueV != V) {
4572         BEValueV = nullptr;
4573         break;
4574       }
4575     } else if (!StartValueV) {
4576       StartValueV = V;
4577     } else if (StartValueV != V) {
4578       StartValueV = nullptr;
4579       break;
4580     }
4581   }
4582   if (!BEValueV || !StartValueV)
4583     return None;
4584 
4585   const SCEV *BEValue = getSCEV(BEValueV);
4586 
4587   // If the value coming around the backedge is an add with the symbolic
4588   // value we just inserted, possibly with casts that we can ignore under
4589   // an appropriate runtime guard, then we found a simple induction variable!
4590   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4591   if (!Add)
4592     return None;
4593 
4594   // If there is a single occurrence of the symbolic value, possibly
4595   // casted, replace it with a recurrence.
4596   unsigned FoundIndex = Add->getNumOperands();
4597   Type *TruncTy = nullptr;
4598   bool Signed;
4599   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4600     if ((TruncTy =
4601              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4602       if (FoundIndex == e) {
4603         FoundIndex = i;
4604         break;
4605       }
4606 
4607   if (FoundIndex == Add->getNumOperands())
4608     return None;
4609 
4610   // Create an add with everything but the specified operand.
4611   SmallVector<const SCEV *, 8> Ops;
4612   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4613     if (i != FoundIndex)
4614       Ops.push_back(Add->getOperand(i));
4615   const SCEV *Accum = getAddExpr(Ops);
4616 
4617   // The runtime checks will not be valid if the step amount is
4618   // varying inside the loop.
4619   if (!isLoopInvariant(Accum, L))
4620     return None;
4621 
4622   // *** Part2: Create the predicates
4623 
4624   // Analysis was successful: we have a phi-with-cast pattern for which we
4625   // can return an AddRec expression under the following predicates:
4626   //
4627   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4628   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4629   // P2: An Equal predicate that guarantees that
4630   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4631   // P3: An Equal predicate that guarantees that
4632   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4633   //
4634   // As we next prove, the above predicates guarantee that:
4635   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4636   //
4637   //
4638   // More formally, we want to prove that:
4639   //     Expr(i+1) = Start + (i+1) * Accum
4640   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4641   //
4642   // Given that:
4643   // 1) Expr(0) = Start
4644   // 2) Expr(1) = Start + Accum
4645   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4646   // 3) Induction hypothesis (step i):
4647   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4648   //
4649   // Proof:
4650   //  Expr(i+1) =
4651   //   = Start + (i+1)*Accum
4652   //   = (Start + i*Accum) + Accum
4653   //   = Expr(i) + Accum
4654   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4655   //                                                             :: from step i
4656   //
4657   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4658   //
4659   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4660   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4661   //     + Accum                                                     :: from P3
4662   //
4663   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4664   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4665   //
4666   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4667   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4668   //
4669   // By induction, the same applies to all iterations 1<=i<n:
4670   //
4671 
4672   // Create a truncated addrec for which we will add a no overflow check (P1).
4673   const SCEV *StartVal = getSCEV(StartValueV);
4674   const SCEV *PHISCEV =
4675       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4676                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4677 
4678   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4679   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4680   // will be constant.
4681   //
4682   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4683   // add P1.
4684   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4685     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4686         Signed ? SCEVWrapPredicate::IncrementNSSW
4687                : SCEVWrapPredicate::IncrementNUSW;
4688     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4689     Predicates.push_back(AddRecPred);
4690   }
4691 
4692   // Create the Equal Predicates P2,P3:
4693 
4694   // It is possible that the predicates P2 and/or P3 are computable at
4695   // compile time due to StartVal and/or Accum being constants.
4696   // If either one is, then we can check that now and escape if either P2
4697   // or P3 is false.
4698 
4699   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4700   // for each of StartVal and Accum
4701   auto getExtendedExpr = [&](const SCEV *Expr,
4702                              bool CreateSignExtend) -> const SCEV * {
4703     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4704     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4705     const SCEV *ExtendedExpr =
4706         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4707                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4708     return ExtendedExpr;
4709   };
4710 
4711   // Given:
4712   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4713   //               = getExtendedExpr(Expr)
4714   // Determine whether the predicate P: Expr == ExtendedExpr
4715   // is known to be false at compile time
4716   auto PredIsKnownFalse = [&](const SCEV *Expr,
4717                               const SCEV *ExtendedExpr) -> bool {
4718     return Expr != ExtendedExpr &&
4719            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4720   };
4721 
4722   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4723   if (PredIsKnownFalse(StartVal, StartExtended)) {
4724     DEBUG(dbgs() << "P2 is compile-time false\n";);
4725     return None;
4726   }
4727 
4728   // The Step is always Signed (because the overflow checks are either
4729   // NSSW or NUSW)
4730   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4731   if (PredIsKnownFalse(Accum, AccumExtended)) {
4732     DEBUG(dbgs() << "P3 is compile-time false\n";);
4733     return None;
4734   }
4735 
4736   auto AppendPredicate = [&](const SCEV *Expr,
4737                              const SCEV *ExtendedExpr) -> void {
4738     if (Expr != ExtendedExpr &&
4739         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4740       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4741       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4742       Predicates.push_back(Pred);
4743     }
4744   };
4745 
4746   AppendPredicate(StartVal, StartExtended);
4747   AppendPredicate(Accum, AccumExtended);
4748 
4749   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4750   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4751   // into NewAR if it will also add the runtime overflow checks specified in
4752   // Predicates.
4753   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4754 
4755   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4756       std::make_pair(NewAR, Predicates);
4757   // Remember the result of the analysis for this SCEV at this locayyytion.
4758   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4759   return PredRewrite;
4760 }
4761 
4762 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4763 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4764   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4765   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4766   if (!L)
4767     return None;
4768 
4769   // Check to see if we already analyzed this PHI.
4770   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4771   if (I != PredicatedSCEVRewrites.end()) {
4772     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4773         I->second;
4774     // Analysis was done before and failed to create an AddRec:
4775     if (Rewrite.first == SymbolicPHI)
4776       return None;
4777     // Analysis was done before and succeeded to create an AddRec under
4778     // a predicate:
4779     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4780     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4781     return Rewrite;
4782   }
4783 
4784   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4785     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4786 
4787   // Record in the cache that the analysis failed
4788   if (!Rewrite) {
4789     SmallVector<const SCEVPredicate *, 3> Predicates;
4790     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4791     return None;
4792   }
4793 
4794   return Rewrite;
4795 }
4796 
4797 // FIXME: This utility is currently required because the Rewriter currently
4798 // does not rewrite this expression:
4799 // {0, +, (sext ix (trunc iy to ix) to iy)}
4800 // into {0, +, %step},
4801 // even when the following Equal predicate exists:
4802 // "%step == (sext ix (trunc iy to ix) to iy)".
4803 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4804     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4805   if (AR1 == AR2)
4806     return true;
4807 
4808   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4809     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4810         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4811       return false;
4812     return true;
4813   };
4814 
4815   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4816       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4817     return false;
4818   return true;
4819 }
4820 
4821 /// A helper function for createAddRecFromPHI to handle simple cases.
4822 ///
4823 /// This function tries to find an AddRec expression for the simplest (yet most
4824 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4825 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4826 /// technique for finding the AddRec expression.
4827 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4828                                                       Value *BEValueV,
4829                                                       Value *StartValueV) {
4830   const Loop *L = LI.getLoopFor(PN->getParent());
4831   assert(L && L->getHeader() == PN->getParent());
4832   assert(BEValueV && StartValueV);
4833 
4834   auto BO = MatchBinaryOp(BEValueV, DT);
4835   if (!BO)
4836     return nullptr;
4837 
4838   if (BO->Opcode != Instruction::Add)
4839     return nullptr;
4840 
4841   const SCEV *Accum = nullptr;
4842   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4843     Accum = getSCEV(BO->RHS);
4844   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4845     Accum = getSCEV(BO->LHS);
4846 
4847   if (!Accum)
4848     return nullptr;
4849 
4850   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4851   if (BO->IsNUW)
4852     Flags = setFlags(Flags, SCEV::FlagNUW);
4853   if (BO->IsNSW)
4854     Flags = setFlags(Flags, SCEV::FlagNSW);
4855 
4856   const SCEV *StartVal = getSCEV(StartValueV);
4857   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4858 
4859   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4860 
4861   // We can add Flags to the post-inc expression only if we
4862   // know that it is *undefined behavior* for BEValueV to
4863   // overflow.
4864   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4865     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4866       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4867 
4868   return PHISCEV;
4869 }
4870 
4871 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4872   const Loop *L = LI.getLoopFor(PN->getParent());
4873   if (!L || L->getHeader() != PN->getParent())
4874     return nullptr;
4875 
4876   // The loop may have multiple entrances or multiple exits; we can analyze
4877   // this phi as an addrec if it has a unique entry value and a unique
4878   // backedge value.
4879   Value *BEValueV = nullptr, *StartValueV = nullptr;
4880   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4881     Value *V = PN->getIncomingValue(i);
4882     if (L->contains(PN->getIncomingBlock(i))) {
4883       if (!BEValueV) {
4884         BEValueV = V;
4885       } else if (BEValueV != V) {
4886         BEValueV = nullptr;
4887         break;
4888       }
4889     } else if (!StartValueV) {
4890       StartValueV = V;
4891     } else if (StartValueV != V) {
4892       StartValueV = nullptr;
4893       break;
4894     }
4895   }
4896   if (!BEValueV || !StartValueV)
4897     return nullptr;
4898 
4899   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4900          "PHI node already processed?");
4901 
4902   // First, try to find AddRec expression without creating a fictituos symbolic
4903   // value for PN.
4904   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4905     return S;
4906 
4907   // Handle PHI node value symbolically.
4908   const SCEV *SymbolicName = getUnknown(PN);
4909   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4910 
4911   // Using this symbolic name for the PHI, analyze the value coming around
4912   // the back-edge.
4913   const SCEV *BEValue = getSCEV(BEValueV);
4914 
4915   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4916   // has a special value for the first iteration of the loop.
4917 
4918   // If the value coming around the backedge is an add with the symbolic
4919   // value we just inserted, then we found a simple induction variable!
4920   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4921     // If there is a single occurrence of the symbolic value, replace it
4922     // with a recurrence.
4923     unsigned FoundIndex = Add->getNumOperands();
4924     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4925       if (Add->getOperand(i) == SymbolicName)
4926         if (FoundIndex == e) {
4927           FoundIndex = i;
4928           break;
4929         }
4930 
4931     if (FoundIndex != Add->getNumOperands()) {
4932       // Create an add with everything but the specified operand.
4933       SmallVector<const SCEV *, 8> Ops;
4934       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4935         if (i != FoundIndex)
4936           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4937                                                              L, *this));
4938       const SCEV *Accum = getAddExpr(Ops);
4939 
4940       // This is not a valid addrec if the step amount is varying each
4941       // loop iteration, but is not itself an addrec in this loop.
4942       if (isLoopInvariant(Accum, L) ||
4943           (isa<SCEVAddRecExpr>(Accum) &&
4944            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4945         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4946 
4947         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4948           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4949             if (BO->IsNUW)
4950               Flags = setFlags(Flags, SCEV::FlagNUW);
4951             if (BO->IsNSW)
4952               Flags = setFlags(Flags, SCEV::FlagNSW);
4953           }
4954         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4955           // If the increment is an inbounds GEP, then we know the address
4956           // space cannot be wrapped around. We cannot make any guarantee
4957           // about signed or unsigned overflow because pointers are
4958           // unsigned but we may have a negative index from the base
4959           // pointer. We can guarantee that no unsigned wrap occurs if the
4960           // indices form a positive value.
4961           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4962             Flags = setFlags(Flags, SCEV::FlagNW);
4963 
4964             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4965             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4966               Flags = setFlags(Flags, SCEV::FlagNUW);
4967           }
4968 
4969           // We cannot transfer nuw and nsw flags from subtraction
4970           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4971           // for instance.
4972         }
4973 
4974         const SCEV *StartVal = getSCEV(StartValueV);
4975         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4976 
4977         // Okay, for the entire analysis of this edge we assumed the PHI
4978         // to be symbolic.  We now need to go back and purge all of the
4979         // entries for the scalars that use the symbolic expression.
4980         forgetSymbolicName(PN, SymbolicName);
4981         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4982 
4983         // We can add Flags to the post-inc expression only if we
4984         // know that it is *undefined behavior* for BEValueV to
4985         // overflow.
4986         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4987           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4988             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4989 
4990         return PHISCEV;
4991       }
4992     }
4993   } else {
4994     // Otherwise, this could be a loop like this:
4995     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4996     // In this case, j = {1,+,1}  and BEValue is j.
4997     // Because the other in-value of i (0) fits the evolution of BEValue
4998     // i really is an addrec evolution.
4999     //
5000     // We can generalize this saying that i is the shifted value of BEValue
5001     // by one iteration:
5002     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5003     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5004     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5005     if (Shifted != getCouldNotCompute() &&
5006         Start != getCouldNotCompute()) {
5007       const SCEV *StartVal = getSCEV(StartValueV);
5008       if (Start == StartVal) {
5009         // Okay, for the entire analysis of this edge we assumed the PHI
5010         // to be symbolic.  We now need to go back and purge all of the
5011         // entries for the scalars that use the symbolic expression.
5012         forgetSymbolicName(PN, SymbolicName);
5013         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5014         return Shifted;
5015       }
5016     }
5017   }
5018 
5019   // Remove the temporary PHI node SCEV that has been inserted while intending
5020   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5021   // as it will prevent later (possibly simpler) SCEV expressions to be added
5022   // to the ValueExprMap.
5023   eraseValueFromMap(PN);
5024 
5025   return nullptr;
5026 }
5027 
5028 // Checks if the SCEV S is available at BB.  S is considered available at BB
5029 // if S can be materialized at BB without introducing a fault.
5030 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5031                                BasicBlock *BB) {
5032   struct CheckAvailable {
5033     bool TraversalDone = false;
5034     bool Available = true;
5035 
5036     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5037     BasicBlock *BB = nullptr;
5038     DominatorTree &DT;
5039 
5040     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5041       : L(L), BB(BB), DT(DT) {}
5042 
5043     bool setUnavailable() {
5044       TraversalDone = true;
5045       Available = false;
5046       return false;
5047     }
5048 
5049     bool follow(const SCEV *S) {
5050       switch (S->getSCEVType()) {
5051       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5052       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5053         // These expressions are available if their operand(s) is/are.
5054         return true;
5055 
5056       case scAddRecExpr: {
5057         // We allow add recurrences that are on the loop BB is in, or some
5058         // outer loop.  This guarantees availability because the value of the
5059         // add recurrence at BB is simply the "current" value of the induction
5060         // variable.  We can relax this in the future; for instance an add
5061         // recurrence on a sibling dominating loop is also available at BB.
5062         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5063         if (L && (ARLoop == L || ARLoop->contains(L)))
5064           return true;
5065 
5066         return setUnavailable();
5067       }
5068 
5069       case scUnknown: {
5070         // For SCEVUnknown, we check for simple dominance.
5071         const auto *SU = cast<SCEVUnknown>(S);
5072         Value *V = SU->getValue();
5073 
5074         if (isa<Argument>(V))
5075           return false;
5076 
5077         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5078           return false;
5079 
5080         return setUnavailable();
5081       }
5082 
5083       case scUDivExpr:
5084       case scCouldNotCompute:
5085         // We do not try to smart about these at all.
5086         return setUnavailable();
5087       }
5088       llvm_unreachable("switch should be fully covered!");
5089     }
5090 
5091     bool isDone() { return TraversalDone; }
5092   };
5093 
5094   CheckAvailable CA(L, BB, DT);
5095   SCEVTraversal<CheckAvailable> ST(CA);
5096 
5097   ST.visitAll(S);
5098   return CA.Available;
5099 }
5100 
5101 // Try to match a control flow sequence that branches out at BI and merges back
5102 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5103 // match.
5104 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5105                           Value *&C, Value *&LHS, Value *&RHS) {
5106   C = BI->getCondition();
5107 
5108   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5109   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5110 
5111   if (!LeftEdge.isSingleEdge())
5112     return false;
5113 
5114   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5115 
5116   Use &LeftUse = Merge->getOperandUse(0);
5117   Use &RightUse = Merge->getOperandUse(1);
5118 
5119   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5120     LHS = LeftUse;
5121     RHS = RightUse;
5122     return true;
5123   }
5124 
5125   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5126     LHS = RightUse;
5127     RHS = LeftUse;
5128     return true;
5129   }
5130 
5131   return false;
5132 }
5133 
5134 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5135   auto IsReachable =
5136       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5137   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5138     const Loop *L = LI.getLoopFor(PN->getParent());
5139 
5140     // We don't want to break LCSSA, even in a SCEV expression tree.
5141     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5142       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5143         return nullptr;
5144 
5145     // Try to match
5146     //
5147     //  br %cond, label %left, label %right
5148     // left:
5149     //  br label %merge
5150     // right:
5151     //  br label %merge
5152     // merge:
5153     //  V = phi [ %x, %left ], [ %y, %right ]
5154     //
5155     // as "select %cond, %x, %y"
5156 
5157     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5158     assert(IDom && "At least the entry block should dominate PN");
5159 
5160     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5161     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5162 
5163     if (BI && BI->isConditional() &&
5164         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5165         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5166         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5167       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5168   }
5169 
5170   return nullptr;
5171 }
5172 
5173 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5174   if (const SCEV *S = createAddRecFromPHI(PN))
5175     return S;
5176 
5177   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5178     return S;
5179 
5180   // If the PHI has a single incoming value, follow that value, unless the
5181   // PHI's incoming blocks are in a different loop, in which case doing so
5182   // risks breaking LCSSA form. Instcombine would normally zap these, but
5183   // it doesn't have DominatorTree information, so it may miss cases.
5184   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5185     if (LI.replacementPreservesLCSSAForm(PN, V))
5186       return getSCEV(V);
5187 
5188   // If it's not a loop phi, we can't handle it yet.
5189   return getUnknown(PN);
5190 }
5191 
5192 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5193                                                       Value *Cond,
5194                                                       Value *TrueVal,
5195                                                       Value *FalseVal) {
5196   // Handle "constant" branch or select. This can occur for instance when a
5197   // loop pass transforms an inner loop and moves on to process the outer loop.
5198   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5199     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5200 
5201   // Try to match some simple smax or umax patterns.
5202   auto *ICI = dyn_cast<ICmpInst>(Cond);
5203   if (!ICI)
5204     return getUnknown(I);
5205 
5206   Value *LHS = ICI->getOperand(0);
5207   Value *RHS = ICI->getOperand(1);
5208 
5209   switch (ICI->getPredicate()) {
5210   case ICmpInst::ICMP_SLT:
5211   case ICmpInst::ICMP_SLE:
5212     std::swap(LHS, RHS);
5213     LLVM_FALLTHROUGH;
5214   case ICmpInst::ICMP_SGT:
5215   case ICmpInst::ICMP_SGE:
5216     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5217     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5218     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5219       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5220       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5221       const SCEV *LA = getSCEV(TrueVal);
5222       const SCEV *RA = getSCEV(FalseVal);
5223       const SCEV *LDiff = getMinusSCEV(LA, LS);
5224       const SCEV *RDiff = getMinusSCEV(RA, RS);
5225       if (LDiff == RDiff)
5226         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5227       LDiff = getMinusSCEV(LA, RS);
5228       RDiff = getMinusSCEV(RA, LS);
5229       if (LDiff == RDiff)
5230         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5231     }
5232     break;
5233   case ICmpInst::ICMP_ULT:
5234   case ICmpInst::ICMP_ULE:
5235     std::swap(LHS, RHS);
5236     LLVM_FALLTHROUGH;
5237   case ICmpInst::ICMP_UGT:
5238   case ICmpInst::ICMP_UGE:
5239     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5240     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5241     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5242       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5243       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5244       const SCEV *LA = getSCEV(TrueVal);
5245       const SCEV *RA = getSCEV(FalseVal);
5246       const SCEV *LDiff = getMinusSCEV(LA, LS);
5247       const SCEV *RDiff = getMinusSCEV(RA, RS);
5248       if (LDiff == RDiff)
5249         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5250       LDiff = getMinusSCEV(LA, RS);
5251       RDiff = getMinusSCEV(RA, LS);
5252       if (LDiff == RDiff)
5253         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5254     }
5255     break;
5256   case ICmpInst::ICMP_NE:
5257     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5258     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5259         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5260       const SCEV *One = getOne(I->getType());
5261       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5262       const SCEV *LA = getSCEV(TrueVal);
5263       const SCEV *RA = getSCEV(FalseVal);
5264       const SCEV *LDiff = getMinusSCEV(LA, LS);
5265       const SCEV *RDiff = getMinusSCEV(RA, One);
5266       if (LDiff == RDiff)
5267         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5268     }
5269     break;
5270   case ICmpInst::ICMP_EQ:
5271     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5272     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5273         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5274       const SCEV *One = getOne(I->getType());
5275       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5276       const SCEV *LA = getSCEV(TrueVal);
5277       const SCEV *RA = getSCEV(FalseVal);
5278       const SCEV *LDiff = getMinusSCEV(LA, One);
5279       const SCEV *RDiff = getMinusSCEV(RA, LS);
5280       if (LDiff == RDiff)
5281         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5282     }
5283     break;
5284   default:
5285     break;
5286   }
5287 
5288   return getUnknown(I);
5289 }
5290 
5291 /// Expand GEP instructions into add and multiply operations. This allows them
5292 /// to be analyzed by regular SCEV code.
5293 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5294   // Don't attempt to analyze GEPs over unsized objects.
5295   if (!GEP->getSourceElementType()->isSized())
5296     return getUnknown(GEP);
5297 
5298   SmallVector<const SCEV *, 4> IndexExprs;
5299   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5300     IndexExprs.push_back(getSCEV(*Index));
5301   return getGEPExpr(GEP, IndexExprs);
5302 }
5303 
5304 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5305   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5306     return C->getAPInt().countTrailingZeros();
5307 
5308   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5309     return std::min(GetMinTrailingZeros(T->getOperand()),
5310                     (uint32_t)getTypeSizeInBits(T->getType()));
5311 
5312   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5313     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5314     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5315                ? getTypeSizeInBits(E->getType())
5316                : OpRes;
5317   }
5318 
5319   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5320     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5321     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5322                ? getTypeSizeInBits(E->getType())
5323                : OpRes;
5324   }
5325 
5326   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5327     // The result is the min of all operands results.
5328     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5329     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5330       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5331     return MinOpRes;
5332   }
5333 
5334   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5335     // The result is the sum of all operands results.
5336     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5337     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5338     for (unsigned i = 1, e = M->getNumOperands();
5339          SumOpRes != BitWidth && i != e; ++i)
5340       SumOpRes =
5341           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5342     return SumOpRes;
5343   }
5344 
5345   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5346     // The result is the min of all operands results.
5347     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5348     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5349       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5350     return MinOpRes;
5351   }
5352 
5353   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5354     // The result is the min of all operands results.
5355     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5356     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5357       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5358     return MinOpRes;
5359   }
5360 
5361   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5362     // The result is the min of all operands results.
5363     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5364     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5365       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5366     return MinOpRes;
5367   }
5368 
5369   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5370     // For a SCEVUnknown, ask ValueTracking.
5371     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5372     return Known.countMinTrailingZeros();
5373   }
5374 
5375   // SCEVUDivExpr
5376   return 0;
5377 }
5378 
5379 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5380   auto I = MinTrailingZerosCache.find(S);
5381   if (I != MinTrailingZerosCache.end())
5382     return I->second;
5383 
5384   uint32_t Result = GetMinTrailingZerosImpl(S);
5385   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5386   assert(InsertPair.second && "Should insert a new key");
5387   return InsertPair.first->second;
5388 }
5389 
5390 /// Helper method to assign a range to V from metadata present in the IR.
5391 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5392   if (Instruction *I = dyn_cast<Instruction>(V))
5393     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5394       return getConstantRangeFromMetadata(*MD);
5395 
5396   return None;
5397 }
5398 
5399 /// Determine the range for a particular SCEV.  If SignHint is
5400 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5401 /// with a "cleaner" unsigned (resp. signed) representation.
5402 const ConstantRange &
5403 ScalarEvolution::getRangeRef(const SCEV *S,
5404                              ScalarEvolution::RangeSignHint SignHint) {
5405   DenseMap<const SCEV *, ConstantRange> &Cache =
5406       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5407                                                        : SignedRanges;
5408 
5409   // See if we've computed this range already.
5410   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5411   if (I != Cache.end())
5412     return I->second;
5413 
5414   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5415     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5416 
5417   unsigned BitWidth = getTypeSizeInBits(S->getType());
5418   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5419 
5420   // If the value has known zeros, the maximum value will have those known zeros
5421   // as well.
5422   uint32_t TZ = GetMinTrailingZeros(S);
5423   if (TZ != 0) {
5424     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5425       ConservativeResult =
5426           ConstantRange(APInt::getMinValue(BitWidth),
5427                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5428     else
5429       ConservativeResult = ConstantRange(
5430           APInt::getSignedMinValue(BitWidth),
5431           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5432   }
5433 
5434   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5435     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5436     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5437       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5438     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5439   }
5440 
5441   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5442     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5443     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5444       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5445     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5446   }
5447 
5448   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5449     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5450     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5451       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5452     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5453   }
5454 
5455   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5456     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5457     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5458       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5459     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5460   }
5461 
5462   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5463     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5464     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5465     return setRange(UDiv, SignHint,
5466                     ConservativeResult.intersectWith(X.udiv(Y)));
5467   }
5468 
5469   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5470     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5471     return setRange(ZExt, SignHint,
5472                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5473   }
5474 
5475   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5476     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5477     return setRange(SExt, SignHint,
5478                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5479   }
5480 
5481   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5482     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5483     return setRange(Trunc, SignHint,
5484                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5485   }
5486 
5487   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5488     // If there's no unsigned wrap, the value will never be less than its
5489     // initial value.
5490     if (AddRec->hasNoUnsignedWrap())
5491       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5492         if (!C->getValue()->isZero())
5493           ConservativeResult = ConservativeResult.intersectWith(
5494               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5495 
5496     // If there's no signed wrap, and all the operands have the same sign or
5497     // zero, the value won't ever change sign.
5498     if (AddRec->hasNoSignedWrap()) {
5499       bool AllNonNeg = true;
5500       bool AllNonPos = true;
5501       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5502         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5503         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5504       }
5505       if (AllNonNeg)
5506         ConservativeResult = ConservativeResult.intersectWith(
5507           ConstantRange(APInt(BitWidth, 0),
5508                         APInt::getSignedMinValue(BitWidth)));
5509       else if (AllNonPos)
5510         ConservativeResult = ConservativeResult.intersectWith(
5511           ConstantRange(APInt::getSignedMinValue(BitWidth),
5512                         APInt(BitWidth, 1)));
5513     }
5514 
5515     // TODO: non-affine addrec
5516     if (AddRec->isAffine()) {
5517       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5518       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5519           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5520         auto RangeFromAffine = getRangeForAffineAR(
5521             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5522             BitWidth);
5523         if (!RangeFromAffine.isFullSet())
5524           ConservativeResult =
5525               ConservativeResult.intersectWith(RangeFromAffine);
5526 
5527         auto RangeFromFactoring = getRangeViaFactoring(
5528             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5529             BitWidth);
5530         if (!RangeFromFactoring.isFullSet())
5531           ConservativeResult =
5532               ConservativeResult.intersectWith(RangeFromFactoring);
5533       }
5534     }
5535 
5536     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5537   }
5538 
5539   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5540     // Check if the IR explicitly contains !range metadata.
5541     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5542     if (MDRange.hasValue())
5543       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5544 
5545     // Split here to avoid paying the compile-time cost of calling both
5546     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5547     // if needed.
5548     const DataLayout &DL = getDataLayout();
5549     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5550       // For a SCEVUnknown, ask ValueTracking.
5551       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5552       if (Known.One != ~Known.Zero + 1)
5553         ConservativeResult =
5554             ConservativeResult.intersectWith(ConstantRange(Known.One,
5555                                                            ~Known.Zero + 1));
5556     } else {
5557       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5558              "generalize as needed!");
5559       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5560       if (NS > 1)
5561         ConservativeResult = ConservativeResult.intersectWith(
5562             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5563                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5564     }
5565 
5566     // A range of Phi is a subset of union of all ranges of its input.
5567     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5568       // Make sure that we do not run over cycled Phis.
5569       if (PendingPhiRanges.insert(Phi).second) {
5570         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5571         for (auto &Op : Phi->operands()) {
5572           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5573           RangeFromOps = RangeFromOps.unionWith(OpRange);
5574           // No point to continue if we already have a full set.
5575           if (RangeFromOps.isFullSet())
5576             break;
5577         }
5578         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5579         bool Erased = PendingPhiRanges.erase(Phi);
5580         assert(Erased && "Failed to erase Phi properly?");
5581         (void) Erased;
5582       }
5583     }
5584 
5585     return setRange(U, SignHint, std::move(ConservativeResult));
5586   }
5587 
5588   return setRange(S, SignHint, std::move(ConservativeResult));
5589 }
5590 
5591 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5592 // values that the expression can take. Initially, the expression has a value
5593 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5594 // argument defines if we treat Step as signed or unsigned.
5595 static ConstantRange getRangeForAffineARHelper(APInt Step,
5596                                                const ConstantRange &StartRange,
5597                                                const APInt &MaxBECount,
5598                                                unsigned BitWidth, bool Signed) {
5599   // If either Step or MaxBECount is 0, then the expression won't change, and we
5600   // just need to return the initial range.
5601   if (Step == 0 || MaxBECount == 0)
5602     return StartRange;
5603 
5604   // If we don't know anything about the initial value (i.e. StartRange is
5605   // FullRange), then we don't know anything about the final range either.
5606   // Return FullRange.
5607   if (StartRange.isFullSet())
5608     return ConstantRange(BitWidth, /* isFullSet = */ true);
5609 
5610   // If Step is signed and negative, then we use its absolute value, but we also
5611   // note that we're moving in the opposite direction.
5612   bool Descending = Signed && Step.isNegative();
5613 
5614   if (Signed)
5615     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5616     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5617     // This equations hold true due to the well-defined wrap-around behavior of
5618     // APInt.
5619     Step = Step.abs();
5620 
5621   // Check if Offset is more than full span of BitWidth. If it is, the
5622   // expression is guaranteed to overflow.
5623   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5624     return ConstantRange(BitWidth, /* isFullSet = */ true);
5625 
5626   // Offset is by how much the expression can change. Checks above guarantee no
5627   // overflow here.
5628   APInt Offset = Step * MaxBECount;
5629 
5630   // Minimum value of the final range will match the minimal value of StartRange
5631   // if the expression is increasing and will be decreased by Offset otherwise.
5632   // Maximum value of the final range will match the maximal value of StartRange
5633   // if the expression is decreasing and will be increased by Offset otherwise.
5634   APInt StartLower = StartRange.getLower();
5635   APInt StartUpper = StartRange.getUpper() - 1;
5636   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5637                                    : (StartUpper + std::move(Offset));
5638 
5639   // It's possible that the new minimum/maximum value will fall into the initial
5640   // range (due to wrap around). This means that the expression can take any
5641   // value in this bitwidth, and we have to return full range.
5642   if (StartRange.contains(MovedBoundary))
5643     return ConstantRange(BitWidth, /* isFullSet = */ true);
5644 
5645   APInt NewLower =
5646       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5647   APInt NewUpper =
5648       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5649   NewUpper += 1;
5650 
5651   // If we end up with full range, return a proper full range.
5652   if (NewLower == NewUpper)
5653     return ConstantRange(BitWidth, /* isFullSet = */ true);
5654 
5655   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5656   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5657 }
5658 
5659 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5660                                                    const SCEV *Step,
5661                                                    const SCEV *MaxBECount,
5662                                                    unsigned BitWidth) {
5663   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5664          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5665          "Precondition!");
5666 
5667   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5668   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5669 
5670   // First, consider step signed.
5671   ConstantRange StartSRange = getSignedRange(Start);
5672   ConstantRange StepSRange = getSignedRange(Step);
5673 
5674   // If Step can be both positive and negative, we need to find ranges for the
5675   // maximum absolute step values in both directions and union them.
5676   ConstantRange SR =
5677       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5678                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5679   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5680                                               StartSRange, MaxBECountValue,
5681                                               BitWidth, /* Signed = */ true));
5682 
5683   // Next, consider step unsigned.
5684   ConstantRange UR = getRangeForAffineARHelper(
5685       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5686       MaxBECountValue, BitWidth, /* Signed = */ false);
5687 
5688   // Finally, intersect signed and unsigned ranges.
5689   return SR.intersectWith(UR);
5690 }
5691 
5692 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5693                                                     const SCEV *Step,
5694                                                     const SCEV *MaxBECount,
5695                                                     unsigned BitWidth) {
5696   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5697   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5698 
5699   struct SelectPattern {
5700     Value *Condition = nullptr;
5701     APInt TrueValue;
5702     APInt FalseValue;
5703 
5704     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5705                            const SCEV *S) {
5706       Optional<unsigned> CastOp;
5707       APInt Offset(BitWidth, 0);
5708 
5709       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5710              "Should be!");
5711 
5712       // Peel off a constant offset:
5713       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5714         // In the future we could consider being smarter here and handle
5715         // {Start+Step,+,Step} too.
5716         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5717           return;
5718 
5719         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5720         S = SA->getOperand(1);
5721       }
5722 
5723       // Peel off a cast operation
5724       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5725         CastOp = SCast->getSCEVType();
5726         S = SCast->getOperand();
5727       }
5728 
5729       using namespace llvm::PatternMatch;
5730 
5731       auto *SU = dyn_cast<SCEVUnknown>(S);
5732       const APInt *TrueVal, *FalseVal;
5733       if (!SU ||
5734           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5735                                           m_APInt(FalseVal)))) {
5736         Condition = nullptr;
5737         return;
5738       }
5739 
5740       TrueValue = *TrueVal;
5741       FalseValue = *FalseVal;
5742 
5743       // Re-apply the cast we peeled off earlier
5744       if (CastOp.hasValue())
5745         switch (*CastOp) {
5746         default:
5747           llvm_unreachable("Unknown SCEV cast type!");
5748 
5749         case scTruncate:
5750           TrueValue = TrueValue.trunc(BitWidth);
5751           FalseValue = FalseValue.trunc(BitWidth);
5752           break;
5753         case scZeroExtend:
5754           TrueValue = TrueValue.zext(BitWidth);
5755           FalseValue = FalseValue.zext(BitWidth);
5756           break;
5757         case scSignExtend:
5758           TrueValue = TrueValue.sext(BitWidth);
5759           FalseValue = FalseValue.sext(BitWidth);
5760           break;
5761         }
5762 
5763       // Re-apply the constant offset we peeled off earlier
5764       TrueValue += Offset;
5765       FalseValue += Offset;
5766     }
5767 
5768     bool isRecognized() { return Condition != nullptr; }
5769   };
5770 
5771   SelectPattern StartPattern(*this, BitWidth, Start);
5772   if (!StartPattern.isRecognized())
5773     return ConstantRange(BitWidth, /* isFullSet = */ true);
5774 
5775   SelectPattern StepPattern(*this, BitWidth, Step);
5776   if (!StepPattern.isRecognized())
5777     return ConstantRange(BitWidth, /* isFullSet = */ true);
5778 
5779   if (StartPattern.Condition != StepPattern.Condition) {
5780     // We don't handle this case today; but we could, by considering four
5781     // possibilities below instead of two. I'm not sure if there are cases where
5782     // that will help over what getRange already does, though.
5783     return ConstantRange(BitWidth, /* isFullSet = */ true);
5784   }
5785 
5786   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5787   // construct arbitrary general SCEV expressions here.  This function is called
5788   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5789   // say) can end up caching a suboptimal value.
5790 
5791   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5792   // C2352 and C2512 (otherwise it isn't needed).
5793 
5794   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5795   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5796   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5797   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5798 
5799   ConstantRange TrueRange =
5800       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5801   ConstantRange FalseRange =
5802       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5803 
5804   return TrueRange.unionWith(FalseRange);
5805 }
5806 
5807 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5808   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5809   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5810 
5811   // Return early if there are no flags to propagate to the SCEV.
5812   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5813   if (BinOp->hasNoUnsignedWrap())
5814     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5815   if (BinOp->hasNoSignedWrap())
5816     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5817   if (Flags == SCEV::FlagAnyWrap)
5818     return SCEV::FlagAnyWrap;
5819 
5820   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5821 }
5822 
5823 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5824   // Here we check that I is in the header of the innermost loop containing I,
5825   // since we only deal with instructions in the loop header. The actual loop we
5826   // need to check later will come from an add recurrence, but getting that
5827   // requires computing the SCEV of the operands, which can be expensive. This
5828   // check we can do cheaply to rule out some cases early.
5829   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5830   if (InnermostContainingLoop == nullptr ||
5831       InnermostContainingLoop->getHeader() != I->getParent())
5832     return false;
5833 
5834   // Only proceed if we can prove that I does not yield poison.
5835   if (!programUndefinedIfFullPoison(I))
5836     return false;
5837 
5838   // At this point we know that if I is executed, then it does not wrap
5839   // according to at least one of NSW or NUW. If I is not executed, then we do
5840   // not know if the calculation that I represents would wrap. Multiple
5841   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5842   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5843   // derived from other instructions that map to the same SCEV. We cannot make
5844   // that guarantee for cases where I is not executed. So we need to find the
5845   // loop that I is considered in relation to and prove that I is executed for
5846   // every iteration of that loop. That implies that the value that I
5847   // calculates does not wrap anywhere in the loop, so then we can apply the
5848   // flags to the SCEV.
5849   //
5850   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5851   // from different loops, so that we know which loop to prove that I is
5852   // executed in.
5853   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5854     // I could be an extractvalue from a call to an overflow intrinsic.
5855     // TODO: We can do better here in some cases.
5856     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5857       return false;
5858     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5859     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5860       bool AllOtherOpsLoopInvariant = true;
5861       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5862            ++OtherOpIndex) {
5863         if (OtherOpIndex != OpIndex) {
5864           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5865           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5866             AllOtherOpsLoopInvariant = false;
5867             break;
5868           }
5869         }
5870       }
5871       if (AllOtherOpsLoopInvariant &&
5872           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5873         return true;
5874     }
5875   }
5876   return false;
5877 }
5878 
5879 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5880   // If we know that \c I can never be poison period, then that's enough.
5881   if (isSCEVExprNeverPoison(I))
5882     return true;
5883 
5884   // For an add recurrence specifically, we assume that infinite loops without
5885   // side effects are undefined behavior, and then reason as follows:
5886   //
5887   // If the add recurrence is poison in any iteration, it is poison on all
5888   // future iterations (since incrementing poison yields poison). If the result
5889   // of the add recurrence is fed into the loop latch condition and the loop
5890   // does not contain any throws or exiting blocks other than the latch, we now
5891   // have the ability to "choose" whether the backedge is taken or not (by
5892   // choosing a sufficiently evil value for the poison feeding into the branch)
5893   // for every iteration including and after the one in which \p I first became
5894   // poison.  There are two possibilities (let's call the iteration in which \p
5895   // I first became poison as K):
5896   //
5897   //  1. In the set of iterations including and after K, the loop body executes
5898   //     no side effects.  In this case executing the backege an infinte number
5899   //     of times will yield undefined behavior.
5900   //
5901   //  2. In the set of iterations including and after K, the loop body executes
5902   //     at least one side effect.  In this case, that specific instance of side
5903   //     effect is control dependent on poison, which also yields undefined
5904   //     behavior.
5905 
5906   auto *ExitingBB = L->getExitingBlock();
5907   auto *LatchBB = L->getLoopLatch();
5908   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5909     return false;
5910 
5911   SmallPtrSet<const Instruction *, 16> Pushed;
5912   SmallVector<const Instruction *, 8> PoisonStack;
5913 
5914   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5915   // things that are known to be fully poison under that assumption go on the
5916   // PoisonStack.
5917   Pushed.insert(I);
5918   PoisonStack.push_back(I);
5919 
5920   bool LatchControlDependentOnPoison = false;
5921   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5922     const Instruction *Poison = PoisonStack.pop_back_val();
5923 
5924     for (auto *PoisonUser : Poison->users()) {
5925       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5926         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5927           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5928       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5929         assert(BI->isConditional() && "Only possibility!");
5930         if (BI->getParent() == LatchBB) {
5931           LatchControlDependentOnPoison = true;
5932           break;
5933         }
5934       }
5935     }
5936   }
5937 
5938   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5939 }
5940 
5941 ScalarEvolution::LoopProperties
5942 ScalarEvolution::getLoopProperties(const Loop *L) {
5943   using LoopProperties = ScalarEvolution::LoopProperties;
5944 
5945   auto Itr = LoopPropertiesCache.find(L);
5946   if (Itr == LoopPropertiesCache.end()) {
5947     auto HasSideEffects = [](Instruction *I) {
5948       if (auto *SI = dyn_cast<StoreInst>(I))
5949         return !SI->isSimple();
5950 
5951       return I->mayHaveSideEffects();
5952     };
5953 
5954     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5955                          /*HasNoSideEffects*/ true};
5956 
5957     for (auto *BB : L->getBlocks())
5958       for (auto &I : *BB) {
5959         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5960           LP.HasNoAbnormalExits = false;
5961         if (HasSideEffects(&I))
5962           LP.HasNoSideEffects = false;
5963         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5964           break; // We're already as pessimistic as we can get.
5965       }
5966 
5967     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5968     assert(InsertPair.second && "We just checked!");
5969     Itr = InsertPair.first;
5970   }
5971 
5972   return Itr->second;
5973 }
5974 
5975 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5976   if (!isSCEVable(V->getType()))
5977     return getUnknown(V);
5978 
5979   if (Instruction *I = dyn_cast<Instruction>(V)) {
5980     // Don't attempt to analyze instructions in blocks that aren't
5981     // reachable. Such instructions don't matter, and they aren't required
5982     // to obey basic rules for definitions dominating uses which this
5983     // analysis depends on.
5984     if (!DT.isReachableFromEntry(I->getParent()))
5985       return getUnknown(V);
5986   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5987     return getConstant(CI);
5988   else if (isa<ConstantPointerNull>(V))
5989     return getZero(V->getType());
5990   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5991     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5992   else if (!isa<ConstantExpr>(V))
5993     return getUnknown(V);
5994 
5995   Operator *U = cast<Operator>(V);
5996   if (auto BO = MatchBinaryOp(U, DT)) {
5997     switch (BO->Opcode) {
5998     case Instruction::Add: {
5999       // The simple thing to do would be to just call getSCEV on both operands
6000       // and call getAddExpr with the result. However if we're looking at a
6001       // bunch of things all added together, this can be quite inefficient,
6002       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6003       // Instead, gather up all the operands and make a single getAddExpr call.
6004       // LLVM IR canonical form means we need only traverse the left operands.
6005       SmallVector<const SCEV *, 4> AddOps;
6006       do {
6007         if (BO->Op) {
6008           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6009             AddOps.push_back(OpSCEV);
6010             break;
6011           }
6012 
6013           // If a NUW or NSW flag can be applied to the SCEV for this
6014           // addition, then compute the SCEV for this addition by itself
6015           // with a separate call to getAddExpr. We need to do that
6016           // instead of pushing the operands of the addition onto AddOps,
6017           // since the flags are only known to apply to this particular
6018           // addition - they may not apply to other additions that can be
6019           // formed with operands from AddOps.
6020           const SCEV *RHS = getSCEV(BO->RHS);
6021           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6022           if (Flags != SCEV::FlagAnyWrap) {
6023             const SCEV *LHS = getSCEV(BO->LHS);
6024             if (BO->Opcode == Instruction::Sub)
6025               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6026             else
6027               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6028             break;
6029           }
6030         }
6031 
6032         if (BO->Opcode == Instruction::Sub)
6033           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6034         else
6035           AddOps.push_back(getSCEV(BO->RHS));
6036 
6037         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6038         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6039                        NewBO->Opcode != Instruction::Sub)) {
6040           AddOps.push_back(getSCEV(BO->LHS));
6041           break;
6042         }
6043         BO = NewBO;
6044       } while (true);
6045 
6046       return getAddExpr(AddOps);
6047     }
6048 
6049     case Instruction::Mul: {
6050       SmallVector<const SCEV *, 4> MulOps;
6051       do {
6052         if (BO->Op) {
6053           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6054             MulOps.push_back(OpSCEV);
6055             break;
6056           }
6057 
6058           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6059           if (Flags != SCEV::FlagAnyWrap) {
6060             MulOps.push_back(
6061                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6062             break;
6063           }
6064         }
6065 
6066         MulOps.push_back(getSCEV(BO->RHS));
6067         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6068         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6069           MulOps.push_back(getSCEV(BO->LHS));
6070           break;
6071         }
6072         BO = NewBO;
6073       } while (true);
6074 
6075       return getMulExpr(MulOps);
6076     }
6077     case Instruction::UDiv:
6078       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6079     case Instruction::URem:
6080       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6081     case Instruction::Sub: {
6082       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6083       if (BO->Op)
6084         Flags = getNoWrapFlagsFromUB(BO->Op);
6085       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6086     }
6087     case Instruction::And:
6088       // For an expression like x&255 that merely masks off the high bits,
6089       // use zext(trunc(x)) as the SCEV expression.
6090       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6091         if (CI->isZero())
6092           return getSCEV(BO->RHS);
6093         if (CI->isMinusOne())
6094           return getSCEV(BO->LHS);
6095         const APInt &A = CI->getValue();
6096 
6097         // Instcombine's ShrinkDemandedConstant may strip bits out of
6098         // constants, obscuring what would otherwise be a low-bits mask.
6099         // Use computeKnownBits to compute what ShrinkDemandedConstant
6100         // knew about to reconstruct a low-bits mask value.
6101         unsigned LZ = A.countLeadingZeros();
6102         unsigned TZ = A.countTrailingZeros();
6103         unsigned BitWidth = A.getBitWidth();
6104         KnownBits Known(BitWidth);
6105         computeKnownBits(BO->LHS, Known, getDataLayout(),
6106                          0, &AC, nullptr, &DT);
6107 
6108         APInt EffectiveMask =
6109             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6110         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6111           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6112           const SCEV *LHS = getSCEV(BO->LHS);
6113           const SCEV *ShiftedLHS = nullptr;
6114           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6115             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6116               // For an expression like (x * 8) & 8, simplify the multiply.
6117               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6118               unsigned GCD = std::min(MulZeros, TZ);
6119               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6120               SmallVector<const SCEV*, 4> MulOps;
6121               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6122               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6123               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6124               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6125             }
6126           }
6127           if (!ShiftedLHS)
6128             ShiftedLHS = getUDivExpr(LHS, MulCount);
6129           return getMulExpr(
6130               getZeroExtendExpr(
6131                   getTruncateExpr(ShiftedLHS,
6132                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6133                   BO->LHS->getType()),
6134               MulCount);
6135         }
6136       }
6137       break;
6138 
6139     case Instruction::Or:
6140       // If the RHS of the Or is a constant, we may have something like:
6141       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6142       // optimizations will transparently handle this case.
6143       //
6144       // In order for this transformation to be safe, the LHS must be of the
6145       // form X*(2^n) and the Or constant must be less than 2^n.
6146       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6147         const SCEV *LHS = getSCEV(BO->LHS);
6148         const APInt &CIVal = CI->getValue();
6149         if (GetMinTrailingZeros(LHS) >=
6150             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6151           // Build a plain add SCEV.
6152           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6153           // If the LHS of the add was an addrec and it has no-wrap flags,
6154           // transfer the no-wrap flags, since an or won't introduce a wrap.
6155           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6156             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6157             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6158                 OldAR->getNoWrapFlags());
6159           }
6160           return S;
6161         }
6162       }
6163       break;
6164 
6165     case Instruction::Xor:
6166       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6167         // If the RHS of xor is -1, then this is a not operation.
6168         if (CI->isMinusOne())
6169           return getNotSCEV(getSCEV(BO->LHS));
6170 
6171         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6172         // This is a variant of the check for xor with -1, and it handles
6173         // the case where instcombine has trimmed non-demanded bits out
6174         // of an xor with -1.
6175         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6176           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6177             if (LBO->getOpcode() == Instruction::And &&
6178                 LCI->getValue() == CI->getValue())
6179               if (const SCEVZeroExtendExpr *Z =
6180                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6181                 Type *UTy = BO->LHS->getType();
6182                 const SCEV *Z0 = Z->getOperand();
6183                 Type *Z0Ty = Z0->getType();
6184                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6185 
6186                 // If C is a low-bits mask, the zero extend is serving to
6187                 // mask off the high bits. Complement the operand and
6188                 // re-apply the zext.
6189                 if (CI->getValue().isMask(Z0TySize))
6190                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6191 
6192                 // If C is a single bit, it may be in the sign-bit position
6193                 // before the zero-extend. In this case, represent the xor
6194                 // using an add, which is equivalent, and re-apply the zext.
6195                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6196                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6197                     Trunc.isSignMask())
6198                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6199                                            UTy);
6200               }
6201       }
6202       break;
6203 
6204   case Instruction::Shl:
6205     // Turn shift left of a constant amount into a multiply.
6206     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6207       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6208 
6209       // If the shift count is not less than the bitwidth, the result of
6210       // the shift is undefined. Don't try to analyze it, because the
6211       // resolution chosen here may differ from the resolution chosen in
6212       // other parts of the compiler.
6213       if (SA->getValue().uge(BitWidth))
6214         break;
6215 
6216       // It is currently not resolved how to interpret NSW for left
6217       // shift by BitWidth - 1, so we avoid applying flags in that
6218       // case. Remove this check (or this comment) once the situation
6219       // is resolved. See
6220       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6221       // and http://reviews.llvm.org/D8890 .
6222       auto Flags = SCEV::FlagAnyWrap;
6223       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6224         Flags = getNoWrapFlagsFromUB(BO->Op);
6225 
6226       Constant *X = ConstantInt::get(getContext(),
6227         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6228       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6229     }
6230     break;
6231 
6232     case Instruction::AShr: {
6233       // AShr X, C, where C is a constant.
6234       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6235       if (!CI)
6236         break;
6237 
6238       Type *OuterTy = BO->LHS->getType();
6239       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6240       // If the shift count is not less than the bitwidth, the result of
6241       // the shift is undefined. Don't try to analyze it, because the
6242       // resolution chosen here may differ from the resolution chosen in
6243       // other parts of the compiler.
6244       if (CI->getValue().uge(BitWidth))
6245         break;
6246 
6247       if (CI->isZero())
6248         return getSCEV(BO->LHS); // shift by zero --> noop
6249 
6250       uint64_t AShrAmt = CI->getZExtValue();
6251       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6252 
6253       Operator *L = dyn_cast<Operator>(BO->LHS);
6254       if (L && L->getOpcode() == Instruction::Shl) {
6255         // X = Shl A, n
6256         // Y = AShr X, m
6257         // Both n and m are constant.
6258 
6259         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6260         if (L->getOperand(1) == BO->RHS)
6261           // For a two-shift sext-inreg, i.e. n = m,
6262           // use sext(trunc(x)) as the SCEV expression.
6263           return getSignExtendExpr(
6264               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6265 
6266         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6267         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6268           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6269           if (ShlAmt > AShrAmt) {
6270             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6271             // expression. We already checked that ShlAmt < BitWidth, so
6272             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6273             // ShlAmt - AShrAmt < Amt.
6274             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6275                                             ShlAmt - AShrAmt);
6276             return getSignExtendExpr(
6277                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6278                 getConstant(Mul)), OuterTy);
6279           }
6280         }
6281       }
6282       break;
6283     }
6284     }
6285   }
6286 
6287   switch (U->getOpcode()) {
6288   case Instruction::Trunc:
6289     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6290 
6291   case Instruction::ZExt:
6292     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6293 
6294   case Instruction::SExt:
6295     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6296       // The NSW flag of a subtract does not always survive the conversion to
6297       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6298       // more likely to preserve NSW and allow later AddRec optimisations.
6299       //
6300       // NOTE: This is effectively duplicating this logic from getSignExtend:
6301       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6302       // but by that point the NSW information has potentially been lost.
6303       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6304         Type *Ty = U->getType();
6305         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6306         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6307         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6308       }
6309     }
6310     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6311 
6312   case Instruction::BitCast:
6313     // BitCasts are no-op casts so we just eliminate the cast.
6314     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6315       return getSCEV(U->getOperand(0));
6316     break;
6317 
6318   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6319   // lead to pointer expressions which cannot safely be expanded to GEPs,
6320   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6321   // simplifying integer expressions.
6322 
6323   case Instruction::GetElementPtr:
6324     return createNodeForGEP(cast<GEPOperator>(U));
6325 
6326   case Instruction::PHI:
6327     return createNodeForPHI(cast<PHINode>(U));
6328 
6329   case Instruction::Select:
6330     // U can also be a select constant expr, which let fall through.  Since
6331     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6332     // constant expressions cannot have instructions as operands, we'd have
6333     // returned getUnknown for a select constant expressions anyway.
6334     if (isa<Instruction>(U))
6335       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6336                                       U->getOperand(1), U->getOperand(2));
6337     break;
6338 
6339   case Instruction::Call:
6340   case Instruction::Invoke:
6341     if (Value *RV = CallSite(U).getReturnedArgOperand())
6342       return getSCEV(RV);
6343     break;
6344   }
6345 
6346   return getUnknown(V);
6347 }
6348 
6349 //===----------------------------------------------------------------------===//
6350 //                   Iteration Count Computation Code
6351 //
6352 
6353 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6354   if (!ExitCount)
6355     return 0;
6356 
6357   ConstantInt *ExitConst = ExitCount->getValue();
6358 
6359   // Guard against huge trip counts.
6360   if (ExitConst->getValue().getActiveBits() > 32)
6361     return 0;
6362 
6363   // In case of integer overflow, this returns 0, which is correct.
6364   return ((unsigned)ExitConst->getZExtValue()) + 1;
6365 }
6366 
6367 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6368   if (BasicBlock *ExitingBB = L->getExitingBlock())
6369     return getSmallConstantTripCount(L, ExitingBB);
6370 
6371   // No trip count information for multiple exits.
6372   return 0;
6373 }
6374 
6375 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6376                                                     BasicBlock *ExitingBlock) {
6377   assert(ExitingBlock && "Must pass a non-null exiting block!");
6378   assert(L->isLoopExiting(ExitingBlock) &&
6379          "Exiting block must actually branch out of the loop!");
6380   const SCEVConstant *ExitCount =
6381       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6382   return getConstantTripCount(ExitCount);
6383 }
6384 
6385 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6386   const auto *MaxExitCount =
6387       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6388   return getConstantTripCount(MaxExitCount);
6389 }
6390 
6391 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6392   if (BasicBlock *ExitingBB = L->getExitingBlock())
6393     return getSmallConstantTripMultiple(L, ExitingBB);
6394 
6395   // No trip multiple information for multiple exits.
6396   return 0;
6397 }
6398 
6399 /// Returns the largest constant divisor of the trip count of this loop as a
6400 /// normal unsigned value, if possible. This means that the actual trip count is
6401 /// always a multiple of the returned value (don't forget the trip count could
6402 /// very well be zero as well!).
6403 ///
6404 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6405 /// multiple of a constant (which is also the case if the trip count is simply
6406 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6407 /// if the trip count is very large (>= 2^32).
6408 ///
6409 /// As explained in the comments for getSmallConstantTripCount, this assumes
6410 /// that control exits the loop via ExitingBlock.
6411 unsigned
6412 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6413                                               BasicBlock *ExitingBlock) {
6414   assert(ExitingBlock && "Must pass a non-null exiting block!");
6415   assert(L->isLoopExiting(ExitingBlock) &&
6416          "Exiting block must actually branch out of the loop!");
6417   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6418   if (ExitCount == getCouldNotCompute())
6419     return 1;
6420 
6421   // Get the trip count from the BE count by adding 1.
6422   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6423 
6424   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6425   if (!TC)
6426     // Attempt to factor more general cases. Returns the greatest power of
6427     // two divisor. If overflow happens, the trip count expression is still
6428     // divisible by the greatest power of 2 divisor returned.
6429     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6430 
6431   ConstantInt *Result = TC->getValue();
6432 
6433   // Guard against huge trip counts (this requires checking
6434   // for zero to handle the case where the trip count == -1 and the
6435   // addition wraps).
6436   if (!Result || Result->getValue().getActiveBits() > 32 ||
6437       Result->getValue().getActiveBits() == 0)
6438     return 1;
6439 
6440   return (unsigned)Result->getZExtValue();
6441 }
6442 
6443 /// Get the expression for the number of loop iterations for which this loop is
6444 /// guaranteed not to exit via ExitingBlock. Otherwise return
6445 /// SCEVCouldNotCompute.
6446 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6447                                           BasicBlock *ExitingBlock) {
6448   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6449 }
6450 
6451 const SCEV *
6452 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6453                                                  SCEVUnionPredicate &Preds) {
6454   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6455 }
6456 
6457 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6458   return getBackedgeTakenInfo(L).getExact(L, this);
6459 }
6460 
6461 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6462 /// known never to be less than the actual backedge taken count.
6463 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6464   return getBackedgeTakenInfo(L).getMax(this);
6465 }
6466 
6467 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6468   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6469 }
6470 
6471 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6472 static void
6473 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6474   BasicBlock *Header = L->getHeader();
6475 
6476   // Push all Loop-header PHIs onto the Worklist stack.
6477   for (PHINode &PN : Header->phis())
6478     Worklist.push_back(&PN);
6479 }
6480 
6481 const ScalarEvolution::BackedgeTakenInfo &
6482 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6483   auto &BTI = getBackedgeTakenInfo(L);
6484   if (BTI.hasFullInfo())
6485     return BTI;
6486 
6487   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6488 
6489   if (!Pair.second)
6490     return Pair.first->second;
6491 
6492   BackedgeTakenInfo Result =
6493       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6494 
6495   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6496 }
6497 
6498 const ScalarEvolution::BackedgeTakenInfo &
6499 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6500   // Initially insert an invalid entry for this loop. If the insertion
6501   // succeeds, proceed to actually compute a backedge-taken count and
6502   // update the value. The temporary CouldNotCompute value tells SCEV
6503   // code elsewhere that it shouldn't attempt to request a new
6504   // backedge-taken count, which could result in infinite recursion.
6505   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6506       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6507   if (!Pair.second)
6508     return Pair.first->second;
6509 
6510   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6511   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6512   // must be cleared in this scope.
6513   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6514 
6515   if (Result.getExact(L, this) != getCouldNotCompute()) {
6516     assert(isLoopInvariant(Result.getExact(L, this), L) &&
6517            isLoopInvariant(Result.getMax(this), L) &&
6518            "Computed backedge-taken count isn't loop invariant for loop!");
6519     ++NumTripCountsComputed;
6520   }
6521   else if (Result.getMax(this) == getCouldNotCompute() &&
6522            isa<PHINode>(L->getHeader()->begin())) {
6523     // Only count loops that have phi nodes as not being computable.
6524     ++NumTripCountsNotComputed;
6525   }
6526 
6527   // Now that we know more about the trip count for this loop, forget any
6528   // existing SCEV values for PHI nodes in this loop since they are only
6529   // conservative estimates made without the benefit of trip count
6530   // information. This is similar to the code in forgetLoop, except that
6531   // it handles SCEVUnknown PHI nodes specially.
6532   if (Result.hasAnyInfo()) {
6533     SmallVector<Instruction *, 16> Worklist;
6534     PushLoopPHIs(L, Worklist);
6535 
6536     SmallPtrSet<Instruction *, 8> Discovered;
6537     while (!Worklist.empty()) {
6538       Instruction *I = Worklist.pop_back_val();
6539 
6540       ValueExprMapType::iterator It =
6541         ValueExprMap.find_as(static_cast<Value *>(I));
6542       if (It != ValueExprMap.end()) {
6543         const SCEV *Old = It->second;
6544 
6545         // SCEVUnknown for a PHI either means that it has an unrecognized
6546         // structure, or it's a PHI that's in the progress of being computed
6547         // by createNodeForPHI.  In the former case, additional loop trip
6548         // count information isn't going to change anything. In the later
6549         // case, createNodeForPHI will perform the necessary updates on its
6550         // own when it gets to that point.
6551         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6552           eraseValueFromMap(It->first);
6553           forgetMemoizedResults(Old);
6554         }
6555         if (PHINode *PN = dyn_cast<PHINode>(I))
6556           ConstantEvolutionLoopExitValue.erase(PN);
6557       }
6558 
6559       // Since we don't need to invalidate anything for correctness and we're
6560       // only invalidating to make SCEV's results more precise, we get to stop
6561       // early to avoid invalidating too much.  This is especially important in
6562       // cases like:
6563       //
6564       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6565       // loop0:
6566       //   %pn0 = phi
6567       //   ...
6568       // loop1:
6569       //   %pn1 = phi
6570       //   ...
6571       //
6572       // where both loop0 and loop1's backedge taken count uses the SCEV
6573       // expression for %v.  If we don't have the early stop below then in cases
6574       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6575       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6576       // count for loop1, effectively nullifying SCEV's trip count cache.
6577       for (auto *U : I->users())
6578         if (auto *I = dyn_cast<Instruction>(U)) {
6579           auto *LoopForUser = LI.getLoopFor(I->getParent());
6580           if (LoopForUser && L->contains(LoopForUser) &&
6581               Discovered.insert(I).second)
6582             Worklist.push_back(I);
6583         }
6584     }
6585   }
6586 
6587   // Re-lookup the insert position, since the call to
6588   // computeBackedgeTakenCount above could result in a
6589   // recusive call to getBackedgeTakenInfo (on a different
6590   // loop), which would invalidate the iterator computed
6591   // earlier.
6592   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6593 }
6594 
6595 void ScalarEvolution::forgetLoop(const Loop *L) {
6596   // Drop any stored trip count value.
6597   auto RemoveLoopFromBackedgeMap =
6598       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6599         auto BTCPos = Map.find(L);
6600         if (BTCPos != Map.end()) {
6601           BTCPos->second.clear();
6602           Map.erase(BTCPos);
6603         }
6604       };
6605 
6606   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6607   SmallVector<Instruction *, 32> Worklist;
6608   SmallPtrSet<Instruction *, 16> Visited;
6609 
6610   // Iterate over all the loops and sub-loops to drop SCEV information.
6611   while (!LoopWorklist.empty()) {
6612     auto *CurrL = LoopWorklist.pop_back_val();
6613 
6614     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6615     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6616 
6617     // Drop information about predicated SCEV rewrites for this loop.
6618     for (auto I = PredicatedSCEVRewrites.begin();
6619          I != PredicatedSCEVRewrites.end();) {
6620       std::pair<const SCEV *, const Loop *> Entry = I->first;
6621       if (Entry.second == CurrL)
6622         PredicatedSCEVRewrites.erase(I++);
6623       else
6624         ++I;
6625     }
6626 
6627     auto LoopUsersItr = LoopUsers.find(CurrL);
6628     if (LoopUsersItr != LoopUsers.end()) {
6629       for (auto *S : LoopUsersItr->second)
6630         forgetMemoizedResults(S);
6631       LoopUsers.erase(LoopUsersItr);
6632     }
6633 
6634     // Drop information about expressions based on loop-header PHIs.
6635     PushLoopPHIs(CurrL, Worklist);
6636 
6637     while (!Worklist.empty()) {
6638       Instruction *I = Worklist.pop_back_val();
6639       if (!Visited.insert(I).second)
6640         continue;
6641 
6642       ValueExprMapType::iterator It =
6643           ValueExprMap.find_as(static_cast<Value *>(I));
6644       if (It != ValueExprMap.end()) {
6645         eraseValueFromMap(It->first);
6646         forgetMemoizedResults(It->second);
6647         if (PHINode *PN = dyn_cast<PHINode>(I))
6648           ConstantEvolutionLoopExitValue.erase(PN);
6649       }
6650 
6651       PushDefUseChildren(I, Worklist);
6652     }
6653 
6654     LoopPropertiesCache.erase(CurrL);
6655     // Forget all contained loops too, to avoid dangling entries in the
6656     // ValuesAtScopes map.
6657     LoopWorklist.append(CurrL->begin(), CurrL->end());
6658   }
6659 }
6660 
6661 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6662   while (Loop *Parent = L->getParentLoop())
6663     L = Parent;
6664   forgetLoop(L);
6665 }
6666 
6667 void ScalarEvolution::forgetValue(Value *V) {
6668   Instruction *I = dyn_cast<Instruction>(V);
6669   if (!I) return;
6670 
6671   // Drop information about expressions based on loop-header PHIs.
6672   SmallVector<Instruction *, 16> Worklist;
6673   Worklist.push_back(I);
6674 
6675   SmallPtrSet<Instruction *, 8> Visited;
6676   while (!Worklist.empty()) {
6677     I = Worklist.pop_back_val();
6678     if (!Visited.insert(I).second)
6679       continue;
6680 
6681     ValueExprMapType::iterator It =
6682       ValueExprMap.find_as(static_cast<Value *>(I));
6683     if (It != ValueExprMap.end()) {
6684       eraseValueFromMap(It->first);
6685       forgetMemoizedResults(It->second);
6686       if (PHINode *PN = dyn_cast<PHINode>(I))
6687         ConstantEvolutionLoopExitValue.erase(PN);
6688     }
6689 
6690     PushDefUseChildren(I, Worklist);
6691   }
6692 }
6693 
6694 /// Get the exact loop backedge taken count considering all loop exits. A
6695 /// computable result can only be returned for loops with all exiting blocks
6696 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6697 /// is never skipped. This is a valid assumption as long as the loop exits via
6698 /// that test. For precise results, it is the caller's responsibility to specify
6699 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6700 const SCEV *
6701 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6702                                              SCEVUnionPredicate *Preds) const {
6703   // If any exits were not computable, the loop is not computable.
6704   if (!isComplete() || ExitNotTaken.empty())
6705     return SE->getCouldNotCompute();
6706 
6707   const BasicBlock *Latch = L->getLoopLatch();
6708   // All exiting blocks we have collected must dominate the only backedge.
6709   if (!Latch)
6710     return SE->getCouldNotCompute();
6711 
6712   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6713   // count is simply a minimum out of all these calculated exit counts.
6714   SmallVector<const SCEV *, 2> Ops;
6715   for (auto &ENT : ExitNotTaken) {
6716     const SCEV *BECount = ENT.ExactNotTaken;
6717     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6718     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6719            "We should only have known counts for exiting blocks that dominate "
6720            "latch!");
6721 
6722     Ops.push_back(BECount);
6723 
6724     if (Preds && !ENT.hasAlwaysTruePredicate())
6725       Preds->add(ENT.Predicate.get());
6726 
6727     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6728            "Predicate should be always true!");
6729   }
6730 
6731   return SE->getUMinFromMismatchedTypes(Ops);
6732 }
6733 
6734 /// Get the exact not taken count for this loop exit.
6735 const SCEV *
6736 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6737                                              ScalarEvolution *SE) const {
6738   for (auto &ENT : ExitNotTaken)
6739     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6740       return ENT.ExactNotTaken;
6741 
6742   return SE->getCouldNotCompute();
6743 }
6744 
6745 /// getMax - Get the max backedge taken count for the loop.
6746 const SCEV *
6747 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6748   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6749     return !ENT.hasAlwaysTruePredicate();
6750   };
6751 
6752   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6753     return SE->getCouldNotCompute();
6754 
6755   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6756          "No point in having a non-constant max backedge taken count!");
6757   return getMax();
6758 }
6759 
6760 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6761   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6762     return !ENT.hasAlwaysTruePredicate();
6763   };
6764   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6765 }
6766 
6767 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6768                                                     ScalarEvolution *SE) const {
6769   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6770       SE->hasOperand(getMax(), S))
6771     return true;
6772 
6773   for (auto &ENT : ExitNotTaken)
6774     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6775         SE->hasOperand(ENT.ExactNotTaken, S))
6776       return true;
6777 
6778   return false;
6779 }
6780 
6781 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6782     : ExactNotTaken(E), MaxNotTaken(E) {
6783   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6784           isa<SCEVConstant>(MaxNotTaken)) &&
6785          "No point in having a non-constant max backedge taken count!");
6786 }
6787 
6788 ScalarEvolution::ExitLimit::ExitLimit(
6789     const SCEV *E, const SCEV *M, bool MaxOrZero,
6790     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6791     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6792   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6793           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6794          "Exact is not allowed to be less precise than Max");
6795   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6796           isa<SCEVConstant>(MaxNotTaken)) &&
6797          "No point in having a non-constant max backedge taken count!");
6798   for (auto *PredSet : PredSetList)
6799     for (auto *P : *PredSet)
6800       addPredicate(P);
6801 }
6802 
6803 ScalarEvolution::ExitLimit::ExitLimit(
6804     const SCEV *E, const SCEV *M, bool MaxOrZero,
6805     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6806     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6807   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6808           isa<SCEVConstant>(MaxNotTaken)) &&
6809          "No point in having a non-constant max backedge taken count!");
6810 }
6811 
6812 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6813                                       bool MaxOrZero)
6814     : ExitLimit(E, M, MaxOrZero, None) {
6815   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6816           isa<SCEVConstant>(MaxNotTaken)) &&
6817          "No point in having a non-constant max backedge taken count!");
6818 }
6819 
6820 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6821 /// computable exit into a persistent ExitNotTakenInfo array.
6822 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6823     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6824         &&ExitCounts,
6825     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6826     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6827   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6828 
6829   ExitNotTaken.reserve(ExitCounts.size());
6830   std::transform(
6831       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6832       [&](const EdgeExitInfo &EEI) {
6833         BasicBlock *ExitBB = EEI.first;
6834         const ExitLimit &EL = EEI.second;
6835         if (EL.Predicates.empty())
6836           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6837 
6838         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6839         for (auto *Pred : EL.Predicates)
6840           Predicate->add(Pred);
6841 
6842         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6843       });
6844   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6845          "No point in having a non-constant max backedge taken count!");
6846 }
6847 
6848 /// Invalidate this result and free the ExitNotTakenInfo array.
6849 void ScalarEvolution::BackedgeTakenInfo::clear() {
6850   ExitNotTaken.clear();
6851 }
6852 
6853 /// Compute the number of times the backedge of the specified loop will execute.
6854 ScalarEvolution::BackedgeTakenInfo
6855 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6856                                            bool AllowPredicates) {
6857   SmallVector<BasicBlock *, 8> ExitingBlocks;
6858   L->getExitingBlocks(ExitingBlocks);
6859 
6860   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6861 
6862   SmallVector<EdgeExitInfo, 4> ExitCounts;
6863   bool CouldComputeBECount = true;
6864   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6865   const SCEV *MustExitMaxBECount = nullptr;
6866   const SCEV *MayExitMaxBECount = nullptr;
6867   bool MustExitMaxOrZero = false;
6868 
6869   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6870   // and compute maxBECount.
6871   // Do a union of all the predicates here.
6872   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6873     BasicBlock *ExitBB = ExitingBlocks[i];
6874     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6875 
6876     assert((AllowPredicates || EL.Predicates.empty()) &&
6877            "Predicated exit limit when predicates are not allowed!");
6878 
6879     // 1. For each exit that can be computed, add an entry to ExitCounts.
6880     // CouldComputeBECount is true only if all exits can be computed.
6881     if (EL.ExactNotTaken == getCouldNotCompute())
6882       // We couldn't compute an exact value for this exit, so
6883       // we won't be able to compute an exact value for the loop.
6884       CouldComputeBECount = false;
6885     else
6886       ExitCounts.emplace_back(ExitBB, EL);
6887 
6888     // 2. Derive the loop's MaxBECount from each exit's max number of
6889     // non-exiting iterations. Partition the loop exits into two kinds:
6890     // LoopMustExits and LoopMayExits.
6891     //
6892     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6893     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6894     // MaxBECount is the minimum EL.MaxNotTaken of computable
6895     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6896     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6897     // computable EL.MaxNotTaken.
6898     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6899         DT.dominates(ExitBB, Latch)) {
6900       if (!MustExitMaxBECount) {
6901         MustExitMaxBECount = EL.MaxNotTaken;
6902         MustExitMaxOrZero = EL.MaxOrZero;
6903       } else {
6904         MustExitMaxBECount =
6905             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6906       }
6907     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6908       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6909         MayExitMaxBECount = EL.MaxNotTaken;
6910       else {
6911         MayExitMaxBECount =
6912             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6913       }
6914     }
6915   }
6916   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6917     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6918   // The loop backedge will be taken the maximum or zero times if there's
6919   // a single exit that must be taken the maximum or zero times.
6920   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6921   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6922                            MaxBECount, MaxOrZero);
6923 }
6924 
6925 ScalarEvolution::ExitLimit
6926 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6927                                       bool AllowPredicates) {
6928   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6929   // at this block and remember the exit block and whether all other targets
6930   // lead to the loop header.
6931   bool MustExecuteLoopHeader = true;
6932   BasicBlock *Exit = nullptr;
6933   for (auto *SBB : successors(ExitingBlock))
6934     if (!L->contains(SBB)) {
6935       if (Exit) // Multiple exit successors.
6936         return getCouldNotCompute();
6937       Exit = SBB;
6938     } else if (SBB != L->getHeader()) {
6939       MustExecuteLoopHeader = false;
6940     }
6941 
6942   // At this point, we know we have a conditional branch that determines whether
6943   // the loop is exited.  However, we don't know if the branch is executed each
6944   // time through the loop.  If not, then the execution count of the branch will
6945   // not be equal to the trip count of the loop.
6946   //
6947   // Currently we check for this by checking to see if the Exit branch goes to
6948   // the loop header.  If so, we know it will always execute the same number of
6949   // times as the loop.  We also handle the case where the exit block *is* the
6950   // loop header.  This is common for un-rotated loops.
6951   //
6952   // If both of those tests fail, walk up the unique predecessor chain to the
6953   // header, stopping if there is an edge that doesn't exit the loop. If the
6954   // header is reached, the execution count of the branch will be equal to the
6955   // trip count of the loop.
6956   //
6957   //  More extensive analysis could be done to handle more cases here.
6958   //
6959   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6960     // The simple checks failed, try climbing the unique predecessor chain
6961     // up to the header.
6962     bool Ok = false;
6963     for (BasicBlock *BB = ExitingBlock; BB; ) {
6964       BasicBlock *Pred = BB->getUniquePredecessor();
6965       if (!Pred)
6966         return getCouldNotCompute();
6967       TerminatorInst *PredTerm = Pred->getTerminator();
6968       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6969         if (PredSucc == BB)
6970           continue;
6971         // If the predecessor has a successor that isn't BB and isn't
6972         // outside the loop, assume the worst.
6973         if (L->contains(PredSucc))
6974           return getCouldNotCompute();
6975       }
6976       if (Pred == L->getHeader()) {
6977         Ok = true;
6978         break;
6979       }
6980       BB = Pred;
6981     }
6982     if (!Ok)
6983       return getCouldNotCompute();
6984   }
6985 
6986   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6987   TerminatorInst *Term = ExitingBlock->getTerminator();
6988   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6989     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6990     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
6991     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
6992            "It should have one successor in loop and one exit block!");
6993     // Proceed to the next level to examine the exit condition expression.
6994     return computeExitLimitFromCond(
6995         L, BI->getCondition(), ExitIfTrue,
6996         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6997   }
6998 
6999   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
7000     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7001                                                 /*ControlsExit=*/IsOnlyExit);
7002 
7003   return getCouldNotCompute();
7004 }
7005 
7006 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7007     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7008     bool ControlsExit, bool AllowPredicates) {
7009   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7010   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7011                                         ControlsExit, AllowPredicates);
7012 }
7013 
7014 Optional<ScalarEvolution::ExitLimit>
7015 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7016                                       bool ExitIfTrue, bool ControlsExit,
7017                                       bool AllowPredicates) {
7018   (void)this->L;
7019   (void)this->ExitIfTrue;
7020   (void)this->AllowPredicates;
7021 
7022   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7023          this->AllowPredicates == AllowPredicates &&
7024          "Variance in assumed invariant key components!");
7025   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7026   if (Itr == TripCountMap.end())
7027     return None;
7028   return Itr->second;
7029 }
7030 
7031 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7032                                              bool ExitIfTrue,
7033                                              bool ControlsExit,
7034                                              bool AllowPredicates,
7035                                              const ExitLimit &EL) {
7036   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7037          this->AllowPredicates == AllowPredicates &&
7038          "Variance in assumed invariant key components!");
7039 
7040   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7041   assert(InsertResult.second && "Expected successful insertion!");
7042   (void)InsertResult;
7043   (void)ExitIfTrue;
7044 }
7045 
7046 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7047     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7048     bool ControlsExit, bool AllowPredicates) {
7049 
7050   if (auto MaybeEL =
7051           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7052     return *MaybeEL;
7053 
7054   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7055                                               ControlsExit, AllowPredicates);
7056   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7057   return EL;
7058 }
7059 
7060 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7061     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7062     bool ControlsExit, bool AllowPredicates) {
7063   // Check if the controlling expression for this loop is an And or Or.
7064   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7065     if (BO->getOpcode() == Instruction::And) {
7066       // Recurse on the operands of the and.
7067       bool EitherMayExit = !ExitIfTrue;
7068       ExitLimit EL0 = computeExitLimitFromCondCached(
7069           Cache, L, BO->getOperand(0), ExitIfTrue,
7070           ControlsExit && !EitherMayExit, AllowPredicates);
7071       ExitLimit EL1 = computeExitLimitFromCondCached(
7072           Cache, L, BO->getOperand(1), ExitIfTrue,
7073           ControlsExit && !EitherMayExit, AllowPredicates);
7074       const SCEV *BECount = getCouldNotCompute();
7075       const SCEV *MaxBECount = getCouldNotCompute();
7076       if (EitherMayExit) {
7077         // Both conditions must be true for the loop to continue executing.
7078         // Choose the less conservative count.
7079         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7080             EL1.ExactNotTaken == getCouldNotCompute())
7081           BECount = getCouldNotCompute();
7082         else
7083           BECount =
7084               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7085         if (EL0.MaxNotTaken == getCouldNotCompute())
7086           MaxBECount = EL1.MaxNotTaken;
7087         else if (EL1.MaxNotTaken == getCouldNotCompute())
7088           MaxBECount = EL0.MaxNotTaken;
7089         else
7090           MaxBECount =
7091               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7092       } else {
7093         // Both conditions must be true at the same time for the loop to exit.
7094         // For now, be conservative.
7095         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7096           MaxBECount = EL0.MaxNotTaken;
7097         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7098           BECount = EL0.ExactNotTaken;
7099       }
7100 
7101       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7102       // to be more aggressive when computing BECount than when computing
7103       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7104       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7105       // to not.
7106       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7107           !isa<SCEVCouldNotCompute>(BECount))
7108         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7109 
7110       return ExitLimit(BECount, MaxBECount, false,
7111                        {&EL0.Predicates, &EL1.Predicates});
7112     }
7113     if (BO->getOpcode() == Instruction::Or) {
7114       // Recurse on the operands of the or.
7115       bool EitherMayExit = ExitIfTrue;
7116       ExitLimit EL0 = computeExitLimitFromCondCached(
7117           Cache, L, BO->getOperand(0), ExitIfTrue,
7118           ControlsExit && !EitherMayExit, AllowPredicates);
7119       ExitLimit EL1 = computeExitLimitFromCondCached(
7120           Cache, L, BO->getOperand(1), ExitIfTrue,
7121           ControlsExit && !EitherMayExit, AllowPredicates);
7122       const SCEV *BECount = getCouldNotCompute();
7123       const SCEV *MaxBECount = getCouldNotCompute();
7124       if (EitherMayExit) {
7125         // Both conditions must be false for the loop to continue executing.
7126         // Choose the less conservative count.
7127         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7128             EL1.ExactNotTaken == getCouldNotCompute())
7129           BECount = getCouldNotCompute();
7130         else
7131           BECount =
7132               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7133         if (EL0.MaxNotTaken == getCouldNotCompute())
7134           MaxBECount = EL1.MaxNotTaken;
7135         else if (EL1.MaxNotTaken == getCouldNotCompute())
7136           MaxBECount = EL0.MaxNotTaken;
7137         else
7138           MaxBECount =
7139               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7140       } else {
7141         // Both conditions must be false at the same time for the loop to exit.
7142         // For now, be conservative.
7143         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7144           MaxBECount = EL0.MaxNotTaken;
7145         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7146           BECount = EL0.ExactNotTaken;
7147       }
7148 
7149       return ExitLimit(BECount, MaxBECount, false,
7150                        {&EL0.Predicates, &EL1.Predicates});
7151     }
7152   }
7153 
7154   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7155   // Proceed to the next level to examine the icmp.
7156   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7157     ExitLimit EL =
7158         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7159     if (EL.hasFullInfo() || !AllowPredicates)
7160       return EL;
7161 
7162     // Try again, but use SCEV predicates this time.
7163     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7164                                     /*AllowPredicates=*/true);
7165   }
7166 
7167   // Check for a constant condition. These are normally stripped out by
7168   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7169   // preserve the CFG and is temporarily leaving constant conditions
7170   // in place.
7171   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7172     if (ExitIfTrue == !CI->getZExtValue())
7173       // The backedge is always taken.
7174       return getCouldNotCompute();
7175     else
7176       // The backedge is never taken.
7177       return getZero(CI->getType());
7178   }
7179 
7180   // If it's not an integer or pointer comparison then compute it the hard way.
7181   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7182 }
7183 
7184 ScalarEvolution::ExitLimit
7185 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7186                                           ICmpInst *ExitCond,
7187                                           bool ExitIfTrue,
7188                                           bool ControlsExit,
7189                                           bool AllowPredicates) {
7190   // If the condition was exit on true, convert the condition to exit on false
7191   ICmpInst::Predicate Pred;
7192   if (!ExitIfTrue)
7193     Pred = ExitCond->getPredicate();
7194   else
7195     Pred = ExitCond->getInversePredicate();
7196   const ICmpInst::Predicate OriginalPred = Pred;
7197 
7198   // Handle common loops like: for (X = "string"; *X; ++X)
7199   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7200     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7201       ExitLimit ItCnt =
7202         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7203       if (ItCnt.hasAnyInfo())
7204         return ItCnt;
7205     }
7206 
7207   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7208   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7209 
7210   // Try to evaluate any dependencies out of the loop.
7211   LHS = getSCEVAtScope(LHS, L);
7212   RHS = getSCEVAtScope(RHS, L);
7213 
7214   // At this point, we would like to compute how many iterations of the
7215   // loop the predicate will return true for these inputs.
7216   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7217     // If there is a loop-invariant, force it into the RHS.
7218     std::swap(LHS, RHS);
7219     Pred = ICmpInst::getSwappedPredicate(Pred);
7220   }
7221 
7222   // Simplify the operands before analyzing them.
7223   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7224 
7225   // If we have a comparison of a chrec against a constant, try to use value
7226   // ranges to answer this query.
7227   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7228     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7229       if (AddRec->getLoop() == L) {
7230         // Form the constant range.
7231         ConstantRange CompRange =
7232             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7233 
7234         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7235         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7236       }
7237 
7238   switch (Pred) {
7239   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7240     // Convert to: while (X-Y != 0)
7241     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7242                                 AllowPredicates);
7243     if (EL.hasAnyInfo()) return EL;
7244     break;
7245   }
7246   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7247     // Convert to: while (X-Y == 0)
7248     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7249     if (EL.hasAnyInfo()) return EL;
7250     break;
7251   }
7252   case ICmpInst::ICMP_SLT:
7253   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7254     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7255     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7256                                     AllowPredicates);
7257     if (EL.hasAnyInfo()) return EL;
7258     break;
7259   }
7260   case ICmpInst::ICMP_SGT:
7261   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7262     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7263     ExitLimit EL =
7264         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7265                             AllowPredicates);
7266     if (EL.hasAnyInfo()) return EL;
7267     break;
7268   }
7269   default:
7270     break;
7271   }
7272 
7273   auto *ExhaustiveCount =
7274       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7275 
7276   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7277     return ExhaustiveCount;
7278 
7279   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7280                                       ExitCond->getOperand(1), L, OriginalPred);
7281 }
7282 
7283 ScalarEvolution::ExitLimit
7284 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7285                                                       SwitchInst *Switch,
7286                                                       BasicBlock *ExitingBlock,
7287                                                       bool ControlsExit) {
7288   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7289 
7290   // Give up if the exit is the default dest of a switch.
7291   if (Switch->getDefaultDest() == ExitingBlock)
7292     return getCouldNotCompute();
7293 
7294   assert(L->contains(Switch->getDefaultDest()) &&
7295          "Default case must not exit the loop!");
7296   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7297   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7298 
7299   // while (X != Y) --> while (X-Y != 0)
7300   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7301   if (EL.hasAnyInfo())
7302     return EL;
7303 
7304   return getCouldNotCompute();
7305 }
7306 
7307 static ConstantInt *
7308 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7309                                 ScalarEvolution &SE) {
7310   const SCEV *InVal = SE.getConstant(C);
7311   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7312   assert(isa<SCEVConstant>(Val) &&
7313          "Evaluation of SCEV at constant didn't fold correctly?");
7314   return cast<SCEVConstant>(Val)->getValue();
7315 }
7316 
7317 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7318 /// compute the backedge execution count.
7319 ScalarEvolution::ExitLimit
7320 ScalarEvolution::computeLoadConstantCompareExitLimit(
7321   LoadInst *LI,
7322   Constant *RHS,
7323   const Loop *L,
7324   ICmpInst::Predicate predicate) {
7325   if (LI->isVolatile()) return getCouldNotCompute();
7326 
7327   // Check to see if the loaded pointer is a getelementptr of a global.
7328   // TODO: Use SCEV instead of manually grubbing with GEPs.
7329   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7330   if (!GEP) return getCouldNotCompute();
7331 
7332   // Make sure that it is really a constant global we are gepping, with an
7333   // initializer, and make sure the first IDX is really 0.
7334   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7335   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7336       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7337       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7338     return getCouldNotCompute();
7339 
7340   // Okay, we allow one non-constant index into the GEP instruction.
7341   Value *VarIdx = nullptr;
7342   std::vector<Constant*> Indexes;
7343   unsigned VarIdxNum = 0;
7344   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7345     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7346       Indexes.push_back(CI);
7347     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7348       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7349       VarIdx = GEP->getOperand(i);
7350       VarIdxNum = i-2;
7351       Indexes.push_back(nullptr);
7352     }
7353 
7354   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7355   if (!VarIdx)
7356     return getCouldNotCompute();
7357 
7358   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7359   // Check to see if X is a loop variant variable value now.
7360   const SCEV *Idx = getSCEV(VarIdx);
7361   Idx = getSCEVAtScope(Idx, L);
7362 
7363   // We can only recognize very limited forms of loop index expressions, in
7364   // particular, only affine AddRec's like {C1,+,C2}.
7365   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7366   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7367       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7368       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7369     return getCouldNotCompute();
7370 
7371   unsigned MaxSteps = MaxBruteForceIterations;
7372   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7373     ConstantInt *ItCst = ConstantInt::get(
7374                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7375     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7376 
7377     // Form the GEP offset.
7378     Indexes[VarIdxNum] = Val;
7379 
7380     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7381                                                          Indexes);
7382     if (!Result) break;  // Cannot compute!
7383 
7384     // Evaluate the condition for this iteration.
7385     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7386     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7387     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7388       ++NumArrayLenItCounts;
7389       return getConstant(ItCst);   // Found terminating iteration!
7390     }
7391   }
7392   return getCouldNotCompute();
7393 }
7394 
7395 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7396     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7397   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7398   if (!RHS)
7399     return getCouldNotCompute();
7400 
7401   const BasicBlock *Latch = L->getLoopLatch();
7402   if (!Latch)
7403     return getCouldNotCompute();
7404 
7405   const BasicBlock *Predecessor = L->getLoopPredecessor();
7406   if (!Predecessor)
7407     return getCouldNotCompute();
7408 
7409   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7410   // Return LHS in OutLHS and shift_opt in OutOpCode.
7411   auto MatchPositiveShift =
7412       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7413 
7414     using namespace PatternMatch;
7415 
7416     ConstantInt *ShiftAmt;
7417     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7418       OutOpCode = Instruction::LShr;
7419     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7420       OutOpCode = Instruction::AShr;
7421     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7422       OutOpCode = Instruction::Shl;
7423     else
7424       return false;
7425 
7426     return ShiftAmt->getValue().isStrictlyPositive();
7427   };
7428 
7429   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7430   //
7431   // loop:
7432   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7433   //   %iv.shifted = lshr i32 %iv, <positive constant>
7434   //
7435   // Return true on a successful match.  Return the corresponding PHI node (%iv
7436   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7437   auto MatchShiftRecurrence =
7438       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7439     Optional<Instruction::BinaryOps> PostShiftOpCode;
7440 
7441     {
7442       Instruction::BinaryOps OpC;
7443       Value *V;
7444 
7445       // If we encounter a shift instruction, "peel off" the shift operation,
7446       // and remember that we did so.  Later when we inspect %iv's backedge
7447       // value, we will make sure that the backedge value uses the same
7448       // operation.
7449       //
7450       // Note: the peeled shift operation does not have to be the same
7451       // instruction as the one feeding into the PHI's backedge value.  We only
7452       // really care about it being the same *kind* of shift instruction --
7453       // that's all that is required for our later inferences to hold.
7454       if (MatchPositiveShift(LHS, V, OpC)) {
7455         PostShiftOpCode = OpC;
7456         LHS = V;
7457       }
7458     }
7459 
7460     PNOut = dyn_cast<PHINode>(LHS);
7461     if (!PNOut || PNOut->getParent() != L->getHeader())
7462       return false;
7463 
7464     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7465     Value *OpLHS;
7466 
7467     return
7468         // The backedge value for the PHI node must be a shift by a positive
7469         // amount
7470         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7471 
7472         // of the PHI node itself
7473         OpLHS == PNOut &&
7474 
7475         // and the kind of shift should be match the kind of shift we peeled
7476         // off, if any.
7477         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7478   };
7479 
7480   PHINode *PN;
7481   Instruction::BinaryOps OpCode;
7482   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7483     return getCouldNotCompute();
7484 
7485   const DataLayout &DL = getDataLayout();
7486 
7487   // The key rationale for this optimization is that for some kinds of shift
7488   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7489   // within a finite number of iterations.  If the condition guarding the
7490   // backedge (in the sense that the backedge is taken if the condition is true)
7491   // is false for the value the shift recurrence stabilizes to, then we know
7492   // that the backedge is taken only a finite number of times.
7493 
7494   ConstantInt *StableValue = nullptr;
7495   switch (OpCode) {
7496   default:
7497     llvm_unreachable("Impossible case!");
7498 
7499   case Instruction::AShr: {
7500     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7501     // bitwidth(K) iterations.
7502     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7503     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7504                                        Predecessor->getTerminator(), &DT);
7505     auto *Ty = cast<IntegerType>(RHS->getType());
7506     if (Known.isNonNegative())
7507       StableValue = ConstantInt::get(Ty, 0);
7508     else if (Known.isNegative())
7509       StableValue = ConstantInt::get(Ty, -1, true);
7510     else
7511       return getCouldNotCompute();
7512 
7513     break;
7514   }
7515   case Instruction::LShr:
7516   case Instruction::Shl:
7517     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7518     // stabilize to 0 in at most bitwidth(K) iterations.
7519     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7520     break;
7521   }
7522 
7523   auto *Result =
7524       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7525   assert(Result->getType()->isIntegerTy(1) &&
7526          "Otherwise cannot be an operand to a branch instruction");
7527 
7528   if (Result->isZeroValue()) {
7529     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7530     const SCEV *UpperBound =
7531         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7532     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7533   }
7534 
7535   return getCouldNotCompute();
7536 }
7537 
7538 /// Return true if we can constant fold an instruction of the specified type,
7539 /// assuming that all operands were constants.
7540 static bool CanConstantFold(const Instruction *I) {
7541   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7542       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7543       isa<LoadInst>(I))
7544     return true;
7545 
7546   if (const CallInst *CI = dyn_cast<CallInst>(I))
7547     if (const Function *F = CI->getCalledFunction())
7548       return canConstantFoldCallTo(CI, F);
7549   return false;
7550 }
7551 
7552 /// Determine whether this instruction can constant evolve within this loop
7553 /// assuming its operands can all constant evolve.
7554 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7555   // An instruction outside of the loop can't be derived from a loop PHI.
7556   if (!L->contains(I)) return false;
7557 
7558   if (isa<PHINode>(I)) {
7559     // We don't currently keep track of the control flow needed to evaluate
7560     // PHIs, so we cannot handle PHIs inside of loops.
7561     return L->getHeader() == I->getParent();
7562   }
7563 
7564   // If we won't be able to constant fold this expression even if the operands
7565   // are constants, bail early.
7566   return CanConstantFold(I);
7567 }
7568 
7569 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7570 /// recursing through each instruction operand until reaching a loop header phi.
7571 static PHINode *
7572 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7573                                DenseMap<Instruction *, PHINode *> &PHIMap,
7574                                unsigned Depth) {
7575   if (Depth > MaxConstantEvolvingDepth)
7576     return nullptr;
7577 
7578   // Otherwise, we can evaluate this instruction if all of its operands are
7579   // constant or derived from a PHI node themselves.
7580   PHINode *PHI = nullptr;
7581   for (Value *Op : UseInst->operands()) {
7582     if (isa<Constant>(Op)) continue;
7583 
7584     Instruction *OpInst = dyn_cast<Instruction>(Op);
7585     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7586 
7587     PHINode *P = dyn_cast<PHINode>(OpInst);
7588     if (!P)
7589       // If this operand is already visited, reuse the prior result.
7590       // We may have P != PHI if this is the deepest point at which the
7591       // inconsistent paths meet.
7592       P = PHIMap.lookup(OpInst);
7593     if (!P) {
7594       // Recurse and memoize the results, whether a phi is found or not.
7595       // This recursive call invalidates pointers into PHIMap.
7596       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7597       PHIMap[OpInst] = P;
7598     }
7599     if (!P)
7600       return nullptr;  // Not evolving from PHI
7601     if (PHI && PHI != P)
7602       return nullptr;  // Evolving from multiple different PHIs.
7603     PHI = P;
7604   }
7605   // This is a expression evolving from a constant PHI!
7606   return PHI;
7607 }
7608 
7609 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7610 /// in the loop that V is derived from.  We allow arbitrary operations along the
7611 /// way, but the operands of an operation must either be constants or a value
7612 /// derived from a constant PHI.  If this expression does not fit with these
7613 /// constraints, return null.
7614 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7615   Instruction *I = dyn_cast<Instruction>(V);
7616   if (!I || !canConstantEvolve(I, L)) return nullptr;
7617 
7618   if (PHINode *PN = dyn_cast<PHINode>(I))
7619     return PN;
7620 
7621   // Record non-constant instructions contained by the loop.
7622   DenseMap<Instruction *, PHINode *> PHIMap;
7623   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7624 }
7625 
7626 /// EvaluateExpression - Given an expression that passes the
7627 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7628 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7629 /// reason, return null.
7630 static Constant *EvaluateExpression(Value *V, const Loop *L,
7631                                     DenseMap<Instruction *, Constant *> &Vals,
7632                                     const DataLayout &DL,
7633                                     const TargetLibraryInfo *TLI) {
7634   // Convenient constant check, but redundant for recursive calls.
7635   if (Constant *C = dyn_cast<Constant>(V)) return C;
7636   Instruction *I = dyn_cast<Instruction>(V);
7637   if (!I) return nullptr;
7638 
7639   if (Constant *C = Vals.lookup(I)) return C;
7640 
7641   // An instruction inside the loop depends on a value outside the loop that we
7642   // weren't given a mapping for, or a value such as a call inside the loop.
7643   if (!canConstantEvolve(I, L)) return nullptr;
7644 
7645   // An unmapped PHI can be due to a branch or another loop inside this loop,
7646   // or due to this not being the initial iteration through a loop where we
7647   // couldn't compute the evolution of this particular PHI last time.
7648   if (isa<PHINode>(I)) return nullptr;
7649 
7650   std::vector<Constant*> Operands(I->getNumOperands());
7651 
7652   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7653     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7654     if (!Operand) {
7655       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7656       if (!Operands[i]) return nullptr;
7657       continue;
7658     }
7659     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7660     Vals[Operand] = C;
7661     if (!C) return nullptr;
7662     Operands[i] = C;
7663   }
7664 
7665   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7666     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7667                                            Operands[1], DL, TLI);
7668   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7669     if (!LI->isVolatile())
7670       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7671   }
7672   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7673 }
7674 
7675 
7676 // If every incoming value to PN except the one for BB is a specific Constant,
7677 // return that, else return nullptr.
7678 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7679   Constant *IncomingVal = nullptr;
7680 
7681   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7682     if (PN->getIncomingBlock(i) == BB)
7683       continue;
7684 
7685     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7686     if (!CurrentVal)
7687       return nullptr;
7688 
7689     if (IncomingVal != CurrentVal) {
7690       if (IncomingVal)
7691         return nullptr;
7692       IncomingVal = CurrentVal;
7693     }
7694   }
7695 
7696   return IncomingVal;
7697 }
7698 
7699 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7700 /// in the header of its containing loop, we know the loop executes a
7701 /// constant number of times, and the PHI node is just a recurrence
7702 /// involving constants, fold it.
7703 Constant *
7704 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7705                                                    const APInt &BEs,
7706                                                    const Loop *L) {
7707   auto I = ConstantEvolutionLoopExitValue.find(PN);
7708   if (I != ConstantEvolutionLoopExitValue.end())
7709     return I->second;
7710 
7711   if (BEs.ugt(MaxBruteForceIterations))
7712     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7713 
7714   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7715 
7716   DenseMap<Instruction *, Constant *> CurrentIterVals;
7717   BasicBlock *Header = L->getHeader();
7718   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7719 
7720   BasicBlock *Latch = L->getLoopLatch();
7721   if (!Latch)
7722     return nullptr;
7723 
7724   for (PHINode &PHI : Header->phis()) {
7725     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7726       CurrentIterVals[&PHI] = StartCST;
7727   }
7728   if (!CurrentIterVals.count(PN))
7729     return RetVal = nullptr;
7730 
7731   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7732 
7733   // Execute the loop symbolically to determine the exit value.
7734   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7735          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7736 
7737   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7738   unsigned IterationNum = 0;
7739   const DataLayout &DL = getDataLayout();
7740   for (; ; ++IterationNum) {
7741     if (IterationNum == NumIterations)
7742       return RetVal = CurrentIterVals[PN];  // Got exit value!
7743 
7744     // Compute the value of the PHIs for the next iteration.
7745     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7746     DenseMap<Instruction *, Constant *> NextIterVals;
7747     Constant *NextPHI =
7748         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7749     if (!NextPHI)
7750       return nullptr;        // Couldn't evaluate!
7751     NextIterVals[PN] = NextPHI;
7752 
7753     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7754 
7755     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7756     // cease to be able to evaluate one of them or if they stop evolving,
7757     // because that doesn't necessarily prevent us from computing PN.
7758     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7759     for (const auto &I : CurrentIterVals) {
7760       PHINode *PHI = dyn_cast<PHINode>(I.first);
7761       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7762       PHIsToCompute.emplace_back(PHI, I.second);
7763     }
7764     // We use two distinct loops because EvaluateExpression may invalidate any
7765     // iterators into CurrentIterVals.
7766     for (const auto &I : PHIsToCompute) {
7767       PHINode *PHI = I.first;
7768       Constant *&NextPHI = NextIterVals[PHI];
7769       if (!NextPHI) {   // Not already computed.
7770         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7771         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7772       }
7773       if (NextPHI != I.second)
7774         StoppedEvolving = false;
7775     }
7776 
7777     // If all entries in CurrentIterVals == NextIterVals then we can stop
7778     // iterating, the loop can't continue to change.
7779     if (StoppedEvolving)
7780       return RetVal = CurrentIterVals[PN];
7781 
7782     CurrentIterVals.swap(NextIterVals);
7783   }
7784 }
7785 
7786 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7787                                                           Value *Cond,
7788                                                           bool ExitWhen) {
7789   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7790   if (!PN) return getCouldNotCompute();
7791 
7792   // If the loop is canonicalized, the PHI will have exactly two entries.
7793   // That's the only form we support here.
7794   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7795 
7796   DenseMap<Instruction *, Constant *> CurrentIterVals;
7797   BasicBlock *Header = L->getHeader();
7798   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7799 
7800   BasicBlock *Latch = L->getLoopLatch();
7801   assert(Latch && "Should follow from NumIncomingValues == 2!");
7802 
7803   for (PHINode &PHI : Header->phis()) {
7804     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7805       CurrentIterVals[&PHI] = StartCST;
7806   }
7807   if (!CurrentIterVals.count(PN))
7808     return getCouldNotCompute();
7809 
7810   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7811   // the loop symbolically to determine when the condition gets a value of
7812   // "ExitWhen".
7813   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7814   const DataLayout &DL = getDataLayout();
7815   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7816     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7817         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7818 
7819     // Couldn't symbolically evaluate.
7820     if (!CondVal) return getCouldNotCompute();
7821 
7822     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7823       ++NumBruteForceTripCountsComputed;
7824       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7825     }
7826 
7827     // Update all the PHI nodes for the next iteration.
7828     DenseMap<Instruction *, Constant *> NextIterVals;
7829 
7830     // Create a list of which PHIs we need to compute. We want to do this before
7831     // calling EvaluateExpression on them because that may invalidate iterators
7832     // into CurrentIterVals.
7833     SmallVector<PHINode *, 8> PHIsToCompute;
7834     for (const auto &I : CurrentIterVals) {
7835       PHINode *PHI = dyn_cast<PHINode>(I.first);
7836       if (!PHI || PHI->getParent() != Header) continue;
7837       PHIsToCompute.push_back(PHI);
7838     }
7839     for (PHINode *PHI : PHIsToCompute) {
7840       Constant *&NextPHI = NextIterVals[PHI];
7841       if (NextPHI) continue;    // Already computed!
7842 
7843       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7844       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7845     }
7846     CurrentIterVals.swap(NextIterVals);
7847   }
7848 
7849   // Too many iterations were needed to evaluate.
7850   return getCouldNotCompute();
7851 }
7852 
7853 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7854   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7855       ValuesAtScopes[V];
7856   // Check to see if we've folded this expression at this loop before.
7857   for (auto &LS : Values)
7858     if (LS.first == L)
7859       return LS.second ? LS.second : V;
7860 
7861   Values.emplace_back(L, nullptr);
7862 
7863   // Otherwise compute it.
7864   const SCEV *C = computeSCEVAtScope(V, L);
7865   for (auto &LS : reverse(ValuesAtScopes[V]))
7866     if (LS.first == L) {
7867       LS.second = C;
7868       break;
7869     }
7870   return C;
7871 }
7872 
7873 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7874 /// will return Constants for objects which aren't represented by a
7875 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7876 /// Returns NULL if the SCEV isn't representable as a Constant.
7877 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7878   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7879     case scCouldNotCompute:
7880     case scAddRecExpr:
7881       break;
7882     case scConstant:
7883       return cast<SCEVConstant>(V)->getValue();
7884     case scUnknown:
7885       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7886     case scSignExtend: {
7887       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7888       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7889         return ConstantExpr::getSExt(CastOp, SS->getType());
7890       break;
7891     }
7892     case scZeroExtend: {
7893       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7894       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7895         return ConstantExpr::getZExt(CastOp, SZ->getType());
7896       break;
7897     }
7898     case scTruncate: {
7899       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7900       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7901         return ConstantExpr::getTrunc(CastOp, ST->getType());
7902       break;
7903     }
7904     case scAddExpr: {
7905       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7906       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7907         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7908           unsigned AS = PTy->getAddressSpace();
7909           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7910           C = ConstantExpr::getBitCast(C, DestPtrTy);
7911         }
7912         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7913           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7914           if (!C2) return nullptr;
7915 
7916           // First pointer!
7917           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7918             unsigned AS = C2->getType()->getPointerAddressSpace();
7919             std::swap(C, C2);
7920             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7921             // The offsets have been converted to bytes.  We can add bytes to an
7922             // i8* by GEP with the byte count in the first index.
7923             C = ConstantExpr::getBitCast(C, DestPtrTy);
7924           }
7925 
7926           // Don't bother trying to sum two pointers. We probably can't
7927           // statically compute a load that results from it anyway.
7928           if (C2->getType()->isPointerTy())
7929             return nullptr;
7930 
7931           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7932             if (PTy->getElementType()->isStructTy())
7933               C2 = ConstantExpr::getIntegerCast(
7934                   C2, Type::getInt32Ty(C->getContext()), true);
7935             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7936           } else
7937             C = ConstantExpr::getAdd(C, C2);
7938         }
7939         return C;
7940       }
7941       break;
7942     }
7943     case scMulExpr: {
7944       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7945       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7946         // Don't bother with pointers at all.
7947         if (C->getType()->isPointerTy()) return nullptr;
7948         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7949           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7950           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7951           C = ConstantExpr::getMul(C, C2);
7952         }
7953         return C;
7954       }
7955       break;
7956     }
7957     case scUDivExpr: {
7958       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7959       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7960         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7961           if (LHS->getType() == RHS->getType())
7962             return ConstantExpr::getUDiv(LHS, RHS);
7963       break;
7964     }
7965     case scSMaxExpr:
7966     case scUMaxExpr:
7967       break; // TODO: smax, umax.
7968   }
7969   return nullptr;
7970 }
7971 
7972 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7973   if (isa<SCEVConstant>(V)) return V;
7974 
7975   // If this instruction is evolved from a constant-evolving PHI, compute the
7976   // exit value from the loop without using SCEVs.
7977   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7978     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7979       const Loop *LI = this->LI[I->getParent()];
7980       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7981         if (PHINode *PN = dyn_cast<PHINode>(I))
7982           if (PN->getParent() == LI->getHeader()) {
7983             // Okay, there is no closed form solution for the PHI node.  Check
7984             // to see if the loop that contains it has a known backedge-taken
7985             // count.  If so, we may be able to force computation of the exit
7986             // value.
7987             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7988             if (const SCEVConstant *BTCC =
7989                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7990 
7991               // This trivial case can show up in some degenerate cases where
7992               // the incoming IR has not yet been fully simplified.
7993               if (BTCC->getValue()->isZero()) {
7994                 Value *InitValue = nullptr;
7995                 bool MultipleInitValues = false;
7996                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7997                   if (!LI->contains(PN->getIncomingBlock(i))) {
7998                     if (!InitValue)
7999                       InitValue = PN->getIncomingValue(i);
8000                     else if (InitValue != PN->getIncomingValue(i)) {
8001                       MultipleInitValues = true;
8002                       break;
8003                     }
8004                   }
8005                   if (!MultipleInitValues && InitValue)
8006                     return getSCEV(InitValue);
8007                 }
8008               }
8009               // Okay, we know how many times the containing loop executes.  If
8010               // this is a constant evolving PHI node, get the final value at
8011               // the specified iteration number.
8012               Constant *RV =
8013                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8014               if (RV) return getSCEV(RV);
8015             }
8016           }
8017 
8018       // Okay, this is an expression that we cannot symbolically evaluate
8019       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8020       // the arguments into constants, and if so, try to constant propagate the
8021       // result.  This is particularly useful for computing loop exit values.
8022       if (CanConstantFold(I)) {
8023         SmallVector<Constant *, 4> Operands;
8024         bool MadeImprovement = false;
8025         for (Value *Op : I->operands()) {
8026           if (Constant *C = dyn_cast<Constant>(Op)) {
8027             Operands.push_back(C);
8028             continue;
8029           }
8030 
8031           // If any of the operands is non-constant and if they are
8032           // non-integer and non-pointer, don't even try to analyze them
8033           // with scev techniques.
8034           if (!isSCEVable(Op->getType()))
8035             return V;
8036 
8037           const SCEV *OrigV = getSCEV(Op);
8038           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8039           MadeImprovement |= OrigV != OpV;
8040 
8041           Constant *C = BuildConstantFromSCEV(OpV);
8042           if (!C) return V;
8043           if (C->getType() != Op->getType())
8044             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8045                                                               Op->getType(),
8046                                                               false),
8047                                       C, Op->getType());
8048           Operands.push_back(C);
8049         }
8050 
8051         // Check to see if getSCEVAtScope actually made an improvement.
8052         if (MadeImprovement) {
8053           Constant *C = nullptr;
8054           const DataLayout &DL = getDataLayout();
8055           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8056             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8057                                                 Operands[1], DL, &TLI);
8058           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8059             if (!LI->isVolatile())
8060               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8061           } else
8062             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8063           if (!C) return V;
8064           return getSCEV(C);
8065         }
8066       }
8067     }
8068 
8069     // This is some other type of SCEVUnknown, just return it.
8070     return V;
8071   }
8072 
8073   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8074     // Avoid performing the look-up in the common case where the specified
8075     // expression has no loop-variant portions.
8076     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8077       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8078       if (OpAtScope != Comm->getOperand(i)) {
8079         // Okay, at least one of these operands is loop variant but might be
8080         // foldable.  Build a new instance of the folded commutative expression.
8081         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8082                                             Comm->op_begin()+i);
8083         NewOps.push_back(OpAtScope);
8084 
8085         for (++i; i != e; ++i) {
8086           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8087           NewOps.push_back(OpAtScope);
8088         }
8089         if (isa<SCEVAddExpr>(Comm))
8090           return getAddExpr(NewOps);
8091         if (isa<SCEVMulExpr>(Comm))
8092           return getMulExpr(NewOps);
8093         if (isa<SCEVSMaxExpr>(Comm))
8094           return getSMaxExpr(NewOps);
8095         if (isa<SCEVUMaxExpr>(Comm))
8096           return getUMaxExpr(NewOps);
8097         llvm_unreachable("Unknown commutative SCEV type!");
8098       }
8099     }
8100     // If we got here, all operands are loop invariant.
8101     return Comm;
8102   }
8103 
8104   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8105     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8106     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8107     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8108       return Div;   // must be loop invariant
8109     return getUDivExpr(LHS, RHS);
8110   }
8111 
8112   // If this is a loop recurrence for a loop that does not contain L, then we
8113   // are dealing with the final value computed by the loop.
8114   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8115     // First, attempt to evaluate each operand.
8116     // Avoid performing the look-up in the common case where the specified
8117     // expression has no loop-variant portions.
8118     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8119       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8120       if (OpAtScope == AddRec->getOperand(i))
8121         continue;
8122 
8123       // Okay, at least one of these operands is loop variant but might be
8124       // foldable.  Build a new instance of the folded commutative expression.
8125       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8126                                           AddRec->op_begin()+i);
8127       NewOps.push_back(OpAtScope);
8128       for (++i; i != e; ++i)
8129         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8130 
8131       const SCEV *FoldedRec =
8132         getAddRecExpr(NewOps, AddRec->getLoop(),
8133                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8134       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8135       // The addrec may be folded to a nonrecurrence, for example, if the
8136       // induction variable is multiplied by zero after constant folding. Go
8137       // ahead and return the folded value.
8138       if (!AddRec)
8139         return FoldedRec;
8140       break;
8141     }
8142 
8143     // If the scope is outside the addrec's loop, evaluate it by using the
8144     // loop exit value of the addrec.
8145     if (!AddRec->getLoop()->contains(L)) {
8146       // To evaluate this recurrence, we need to know how many times the AddRec
8147       // loop iterates.  Compute this now.
8148       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8149       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8150 
8151       // Then, evaluate the AddRec.
8152       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8153     }
8154 
8155     return AddRec;
8156   }
8157 
8158   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8159     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8160     if (Op == Cast->getOperand())
8161       return Cast;  // must be loop invariant
8162     return getZeroExtendExpr(Op, Cast->getType());
8163   }
8164 
8165   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8166     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8167     if (Op == Cast->getOperand())
8168       return Cast;  // must be loop invariant
8169     return getSignExtendExpr(Op, Cast->getType());
8170   }
8171 
8172   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8173     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8174     if (Op == Cast->getOperand())
8175       return Cast;  // must be loop invariant
8176     return getTruncateExpr(Op, Cast->getType());
8177   }
8178 
8179   llvm_unreachable("Unknown SCEV type!");
8180 }
8181 
8182 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8183   return getSCEVAtScope(getSCEV(V), L);
8184 }
8185 
8186 /// Finds the minimum unsigned root of the following equation:
8187 ///
8188 ///     A * X = B (mod N)
8189 ///
8190 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8191 /// A and B isn't important.
8192 ///
8193 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8194 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8195                                                ScalarEvolution &SE) {
8196   uint32_t BW = A.getBitWidth();
8197   assert(BW == SE.getTypeSizeInBits(B->getType()));
8198   assert(A != 0 && "A must be non-zero.");
8199 
8200   // 1. D = gcd(A, N)
8201   //
8202   // The gcd of A and N may have only one prime factor: 2. The number of
8203   // trailing zeros in A is its multiplicity
8204   uint32_t Mult2 = A.countTrailingZeros();
8205   // D = 2^Mult2
8206 
8207   // 2. Check if B is divisible by D.
8208   //
8209   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8210   // is not less than multiplicity of this prime factor for D.
8211   if (SE.GetMinTrailingZeros(B) < Mult2)
8212     return SE.getCouldNotCompute();
8213 
8214   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8215   // modulo (N / D).
8216   //
8217   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8218   // (N / D) in general. The inverse itself always fits into BW bits, though,
8219   // so we immediately truncate it.
8220   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8221   APInt Mod(BW + 1, 0);
8222   Mod.setBit(BW - Mult2);  // Mod = N / D
8223   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8224 
8225   // 4. Compute the minimum unsigned root of the equation:
8226   // I * (B / D) mod (N / D)
8227   // To simplify the computation, we factor out the divide by D:
8228   // (I * B mod N) / D
8229   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8230   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8231 }
8232 
8233 /// Find the roots of the quadratic equation for the given quadratic chrec
8234 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8235 /// two SCEVCouldNotCompute objects.
8236 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8237 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8238   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8239   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8240   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8241   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8242 
8243   // We currently can only solve this if the coefficients are constants.
8244   if (!LC || !MC || !NC)
8245     return None;
8246 
8247   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8248   const APInt &L = LC->getAPInt();
8249   const APInt &M = MC->getAPInt();
8250   const APInt &N = NC->getAPInt();
8251   APInt Two(BitWidth, 2);
8252 
8253   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8254 
8255   // The A coefficient is N/2
8256   APInt A = N.sdiv(Two);
8257 
8258   // The B coefficient is M-N/2
8259   APInt B = M;
8260   B -= A; // A is the same as N/2.
8261 
8262   // The C coefficient is L.
8263   const APInt& C = L;
8264 
8265   // Compute the B^2-4ac term.
8266   APInt SqrtTerm = B;
8267   SqrtTerm *= B;
8268   SqrtTerm -= 4 * (A * C);
8269 
8270   if (SqrtTerm.isNegative()) {
8271     // The loop is provably infinite.
8272     return None;
8273   }
8274 
8275   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8276   // integer value or else APInt::sqrt() will assert.
8277   APInt SqrtVal = SqrtTerm.sqrt();
8278 
8279   // Compute the two solutions for the quadratic formula.
8280   // The divisions must be performed as signed divisions.
8281   APInt NegB = -std::move(B);
8282   APInt TwoA = std::move(A);
8283   TwoA <<= 1;
8284   if (TwoA.isNullValue())
8285     return None;
8286 
8287   LLVMContext &Context = SE.getContext();
8288 
8289   ConstantInt *Solution1 =
8290     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8291   ConstantInt *Solution2 =
8292     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8293 
8294   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8295                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8296 }
8297 
8298 ScalarEvolution::ExitLimit
8299 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8300                               bool AllowPredicates) {
8301 
8302   // This is only used for loops with a "x != y" exit test. The exit condition
8303   // is now expressed as a single expression, V = x-y. So the exit test is
8304   // effectively V != 0.  We know and take advantage of the fact that this
8305   // expression only being used in a comparison by zero context.
8306 
8307   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8308   // If the value is a constant
8309   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8310     // If the value is already zero, the branch will execute zero times.
8311     if (C->getValue()->isZero()) return C;
8312     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8313   }
8314 
8315   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8316   if (!AddRec && AllowPredicates)
8317     // Try to make this an AddRec using runtime tests, in the first X
8318     // iterations of this loop, where X is the SCEV expression found by the
8319     // algorithm below.
8320     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8321 
8322   if (!AddRec || AddRec->getLoop() != L)
8323     return getCouldNotCompute();
8324 
8325   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8326   // the quadratic equation to solve it.
8327   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8328     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8329       const SCEVConstant *R1 = Roots->first;
8330       const SCEVConstant *R2 = Roots->second;
8331       // Pick the smallest positive root value.
8332       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8333               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8334         if (!CB->getZExtValue())
8335           std::swap(R1, R2); // R1 is the minimum root now.
8336 
8337         // We can only use this value if the chrec ends up with an exact zero
8338         // value at this index.  When solving for "X*X != 5", for example, we
8339         // should not accept a root of 2.
8340         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8341         if (Val->isZero())
8342           // We found a quadratic root!
8343           return ExitLimit(R1, R1, false, Predicates);
8344       }
8345     }
8346     return getCouldNotCompute();
8347   }
8348 
8349   // Otherwise we can only handle this if it is affine.
8350   if (!AddRec->isAffine())
8351     return getCouldNotCompute();
8352 
8353   // If this is an affine expression, the execution count of this branch is
8354   // the minimum unsigned root of the following equation:
8355   //
8356   //     Start + Step*N = 0 (mod 2^BW)
8357   //
8358   // equivalent to:
8359   //
8360   //             Step*N = -Start (mod 2^BW)
8361   //
8362   // where BW is the common bit width of Start and Step.
8363 
8364   // Get the initial value for the loop.
8365   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8366   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8367 
8368   // For now we handle only constant steps.
8369   //
8370   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8371   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8372   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8373   // We have not yet seen any such cases.
8374   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8375   if (!StepC || StepC->getValue()->isZero())
8376     return getCouldNotCompute();
8377 
8378   // For positive steps (counting up until unsigned overflow):
8379   //   N = -Start/Step (as unsigned)
8380   // For negative steps (counting down to zero):
8381   //   N = Start/-Step
8382   // First compute the unsigned distance from zero in the direction of Step.
8383   bool CountDown = StepC->getAPInt().isNegative();
8384   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8385 
8386   // Handle unitary steps, which cannot wraparound.
8387   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8388   //   N = Distance (as unsigned)
8389   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8390     APInt MaxBECount = getUnsignedRangeMax(Distance);
8391 
8392     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8393     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8394     // case, and see if we can improve the bound.
8395     //
8396     // Explicitly handling this here is necessary because getUnsignedRange
8397     // isn't context-sensitive; it doesn't know that we only care about the
8398     // range inside the loop.
8399     const SCEV *Zero = getZero(Distance->getType());
8400     const SCEV *One = getOne(Distance->getType());
8401     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8402     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8403       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8404       // as "unsigned_max(Distance + 1) - 1".
8405       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8406       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8407     }
8408     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8409   }
8410 
8411   // If the condition controls loop exit (the loop exits only if the expression
8412   // is true) and the addition is no-wrap we can use unsigned divide to
8413   // compute the backedge count.  In this case, the step may not divide the
8414   // distance, but we don't care because if the condition is "missed" the loop
8415   // will have undefined behavior due to wrapping.
8416   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8417       loopHasNoAbnormalExits(AddRec->getLoop())) {
8418     const SCEV *Exact =
8419         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8420     const SCEV *Max =
8421         Exact == getCouldNotCompute()
8422             ? Exact
8423             : getConstant(getUnsignedRangeMax(Exact));
8424     return ExitLimit(Exact, Max, false, Predicates);
8425   }
8426 
8427   // Solve the general equation.
8428   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8429                                                getNegativeSCEV(Start), *this);
8430   const SCEV *M = E == getCouldNotCompute()
8431                       ? E
8432                       : getConstant(getUnsignedRangeMax(E));
8433   return ExitLimit(E, M, false, Predicates);
8434 }
8435 
8436 ScalarEvolution::ExitLimit
8437 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8438   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8439   // handle them yet except for the trivial case.  This could be expanded in the
8440   // future as needed.
8441 
8442   // If the value is a constant, check to see if it is known to be non-zero
8443   // already.  If so, the backedge will execute zero times.
8444   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8445     if (!C->getValue()->isZero())
8446       return getZero(C->getType());
8447     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8448   }
8449 
8450   // We could implement others, but I really doubt anyone writes loops like
8451   // this, and if they did, they would already be constant folded.
8452   return getCouldNotCompute();
8453 }
8454 
8455 std::pair<BasicBlock *, BasicBlock *>
8456 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8457   // If the block has a unique predecessor, then there is no path from the
8458   // predecessor to the block that does not go through the direct edge
8459   // from the predecessor to the block.
8460   if (BasicBlock *Pred = BB->getSinglePredecessor())
8461     return {Pred, BB};
8462 
8463   // A loop's header is defined to be a block that dominates the loop.
8464   // If the header has a unique predecessor outside the loop, it must be
8465   // a block that has exactly one successor that can reach the loop.
8466   if (Loop *L = LI.getLoopFor(BB))
8467     return {L->getLoopPredecessor(), L->getHeader()};
8468 
8469   return {nullptr, nullptr};
8470 }
8471 
8472 /// SCEV structural equivalence is usually sufficient for testing whether two
8473 /// expressions are equal, however for the purposes of looking for a condition
8474 /// guarding a loop, it can be useful to be a little more general, since a
8475 /// front-end may have replicated the controlling expression.
8476 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8477   // Quick check to see if they are the same SCEV.
8478   if (A == B) return true;
8479 
8480   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8481     // Not all instructions that are "identical" compute the same value.  For
8482     // instance, two distinct alloca instructions allocating the same type are
8483     // identical and do not read memory; but compute distinct values.
8484     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8485   };
8486 
8487   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8488   // two different instructions with the same value. Check for this case.
8489   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8490     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8491       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8492         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8493           if (ComputesEqualValues(AI, BI))
8494             return true;
8495 
8496   // Otherwise assume they may have a different value.
8497   return false;
8498 }
8499 
8500 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8501                                            const SCEV *&LHS, const SCEV *&RHS,
8502                                            unsigned Depth) {
8503   bool Changed = false;
8504 
8505   // If we hit the max recursion limit bail out.
8506   if (Depth >= 3)
8507     return false;
8508 
8509   // Canonicalize a constant to the right side.
8510   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8511     // Check for both operands constant.
8512     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8513       if (ConstantExpr::getICmp(Pred,
8514                                 LHSC->getValue(),
8515                                 RHSC->getValue())->isNullValue())
8516         goto trivially_false;
8517       else
8518         goto trivially_true;
8519     }
8520     // Otherwise swap the operands to put the constant on the right.
8521     std::swap(LHS, RHS);
8522     Pred = ICmpInst::getSwappedPredicate(Pred);
8523     Changed = true;
8524   }
8525 
8526   // If we're comparing an addrec with a value which is loop-invariant in the
8527   // addrec's loop, put the addrec on the left. Also make a dominance check,
8528   // as both operands could be addrecs loop-invariant in each other's loop.
8529   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8530     const Loop *L = AR->getLoop();
8531     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8532       std::swap(LHS, RHS);
8533       Pred = ICmpInst::getSwappedPredicate(Pred);
8534       Changed = true;
8535     }
8536   }
8537 
8538   // If there's a constant operand, canonicalize comparisons with boundary
8539   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8540   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8541     const APInt &RA = RC->getAPInt();
8542 
8543     bool SimplifiedByConstantRange = false;
8544 
8545     if (!ICmpInst::isEquality(Pred)) {
8546       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8547       if (ExactCR.isFullSet())
8548         goto trivially_true;
8549       else if (ExactCR.isEmptySet())
8550         goto trivially_false;
8551 
8552       APInt NewRHS;
8553       CmpInst::Predicate NewPred;
8554       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8555           ICmpInst::isEquality(NewPred)) {
8556         // We were able to convert an inequality to an equality.
8557         Pred = NewPred;
8558         RHS = getConstant(NewRHS);
8559         Changed = SimplifiedByConstantRange = true;
8560       }
8561     }
8562 
8563     if (!SimplifiedByConstantRange) {
8564       switch (Pred) {
8565       default:
8566         break;
8567       case ICmpInst::ICMP_EQ:
8568       case ICmpInst::ICMP_NE:
8569         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8570         if (!RA)
8571           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8572             if (const SCEVMulExpr *ME =
8573                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8574               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8575                   ME->getOperand(0)->isAllOnesValue()) {
8576                 RHS = AE->getOperand(1);
8577                 LHS = ME->getOperand(1);
8578                 Changed = true;
8579               }
8580         break;
8581 
8582 
8583         // The "Should have been caught earlier!" messages refer to the fact
8584         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8585         // should have fired on the corresponding cases, and canonicalized the
8586         // check to trivially_true or trivially_false.
8587 
8588       case ICmpInst::ICMP_UGE:
8589         assert(!RA.isMinValue() && "Should have been caught earlier!");
8590         Pred = ICmpInst::ICMP_UGT;
8591         RHS = getConstant(RA - 1);
8592         Changed = true;
8593         break;
8594       case ICmpInst::ICMP_ULE:
8595         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8596         Pred = ICmpInst::ICMP_ULT;
8597         RHS = getConstant(RA + 1);
8598         Changed = true;
8599         break;
8600       case ICmpInst::ICMP_SGE:
8601         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8602         Pred = ICmpInst::ICMP_SGT;
8603         RHS = getConstant(RA - 1);
8604         Changed = true;
8605         break;
8606       case ICmpInst::ICMP_SLE:
8607         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8608         Pred = ICmpInst::ICMP_SLT;
8609         RHS = getConstant(RA + 1);
8610         Changed = true;
8611         break;
8612       }
8613     }
8614   }
8615 
8616   // Check for obvious equality.
8617   if (HasSameValue(LHS, RHS)) {
8618     if (ICmpInst::isTrueWhenEqual(Pred))
8619       goto trivially_true;
8620     if (ICmpInst::isFalseWhenEqual(Pred))
8621       goto trivially_false;
8622   }
8623 
8624   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8625   // adding or subtracting 1 from one of the operands.
8626   switch (Pred) {
8627   case ICmpInst::ICMP_SLE:
8628     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8629       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8630                        SCEV::FlagNSW);
8631       Pred = ICmpInst::ICMP_SLT;
8632       Changed = true;
8633     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8634       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8635                        SCEV::FlagNSW);
8636       Pred = ICmpInst::ICMP_SLT;
8637       Changed = true;
8638     }
8639     break;
8640   case ICmpInst::ICMP_SGE:
8641     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8642       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8643                        SCEV::FlagNSW);
8644       Pred = ICmpInst::ICMP_SGT;
8645       Changed = true;
8646     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8647       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8648                        SCEV::FlagNSW);
8649       Pred = ICmpInst::ICMP_SGT;
8650       Changed = true;
8651     }
8652     break;
8653   case ICmpInst::ICMP_ULE:
8654     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8655       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8656                        SCEV::FlagNUW);
8657       Pred = ICmpInst::ICMP_ULT;
8658       Changed = true;
8659     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8660       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8661       Pred = ICmpInst::ICMP_ULT;
8662       Changed = true;
8663     }
8664     break;
8665   case ICmpInst::ICMP_UGE:
8666     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8667       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8668       Pred = ICmpInst::ICMP_UGT;
8669       Changed = true;
8670     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8671       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8672                        SCEV::FlagNUW);
8673       Pred = ICmpInst::ICMP_UGT;
8674       Changed = true;
8675     }
8676     break;
8677   default:
8678     break;
8679   }
8680 
8681   // TODO: More simplifications are possible here.
8682 
8683   // Recursively simplify until we either hit a recursion limit or nothing
8684   // changes.
8685   if (Changed)
8686     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8687 
8688   return Changed;
8689 
8690 trivially_true:
8691   // Return 0 == 0.
8692   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8693   Pred = ICmpInst::ICMP_EQ;
8694   return true;
8695 
8696 trivially_false:
8697   // Return 0 != 0.
8698   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8699   Pred = ICmpInst::ICMP_NE;
8700   return true;
8701 }
8702 
8703 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8704   return getSignedRangeMax(S).isNegative();
8705 }
8706 
8707 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8708   return getSignedRangeMin(S).isStrictlyPositive();
8709 }
8710 
8711 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8712   return !getSignedRangeMin(S).isNegative();
8713 }
8714 
8715 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8716   return !getSignedRangeMax(S).isStrictlyPositive();
8717 }
8718 
8719 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8720   return isKnownNegative(S) || isKnownPositive(S);
8721 }
8722 
8723 std::pair<const SCEV *, const SCEV *>
8724 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
8725   // Compute SCEV on entry of loop L.
8726   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
8727   if (Start == getCouldNotCompute())
8728     return { Start, Start };
8729   // Compute post increment SCEV for loop L.
8730   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
8731   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
8732   return { Start, PostInc };
8733 }
8734 
8735 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
8736                                           const SCEV *LHS, const SCEV *RHS) {
8737   // First collect all loops.
8738   SmallPtrSet<const Loop *, 8> LoopsUsed;
8739   getUsedLoops(LHS, LoopsUsed);
8740   getUsedLoops(RHS, LoopsUsed);
8741 
8742   if (LoopsUsed.empty())
8743     return false;
8744 
8745   // Domination relationship must be a linear order on collected loops.
8746 #ifndef NDEBUG
8747   for (auto *L1 : LoopsUsed)
8748     for (auto *L2 : LoopsUsed)
8749       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
8750               DT.dominates(L2->getHeader(), L1->getHeader())) &&
8751              "Domination relationship is not a linear order");
8752 #endif
8753 
8754   const Loop *MDL =
8755       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
8756                         [&](const Loop *L1, const Loop *L2) {
8757          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
8758        });
8759 
8760   // Get init and post increment value for LHS.
8761   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
8762   // if LHS contains unknown non-invariant SCEV then bail out.
8763   if (SplitLHS.first == getCouldNotCompute())
8764     return false;
8765   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
8766   // Get init and post increment value for RHS.
8767   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
8768   // if RHS contains unknown non-invariant SCEV then bail out.
8769   if (SplitRHS.first == getCouldNotCompute())
8770     return false;
8771   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
8772   // It is possible that init SCEV contains an invariant load but it does
8773   // not dominate MDL and is not available at MDL loop entry, so we should
8774   // check it here.
8775   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
8776       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
8777     return false;
8778 
8779   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
8780          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
8781                                      SplitRHS.second);
8782 }
8783 
8784 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8785                                        const SCEV *LHS, const SCEV *RHS) {
8786   // Canonicalize the inputs first.
8787   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8788 
8789   if (isKnownViaInduction(Pred, LHS, RHS))
8790     return true;
8791 
8792   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8793     return true;
8794 
8795   // Otherwise see what can be done with some simple reasoning.
8796   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
8797 }
8798 
8799 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
8800                                               const SCEVAddRecExpr *LHS,
8801                                               const SCEV *RHS) {
8802   const Loop *L = LHS->getLoop();
8803   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
8804          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
8805 }
8806 
8807 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8808                                            ICmpInst::Predicate Pred,
8809                                            bool &Increasing) {
8810   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8811 
8812 #ifndef NDEBUG
8813   // Verify an invariant: inverting the predicate should turn a monotonically
8814   // increasing change to a monotonically decreasing one, and vice versa.
8815   bool IncreasingSwapped;
8816   bool ResultSwapped = isMonotonicPredicateImpl(
8817       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8818 
8819   assert(Result == ResultSwapped && "should be able to analyze both!");
8820   if (ResultSwapped)
8821     assert(Increasing == !IncreasingSwapped &&
8822            "monotonicity should flip as we flip the predicate");
8823 #endif
8824 
8825   return Result;
8826 }
8827 
8828 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8829                                                ICmpInst::Predicate Pred,
8830                                                bool &Increasing) {
8831 
8832   // A zero step value for LHS means the induction variable is essentially a
8833   // loop invariant value. We don't really depend on the predicate actually
8834   // flipping from false to true (for increasing predicates, and the other way
8835   // around for decreasing predicates), all we care about is that *if* the
8836   // predicate changes then it only changes from false to true.
8837   //
8838   // A zero step value in itself is not very useful, but there may be places
8839   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8840   // as general as possible.
8841 
8842   switch (Pred) {
8843   default:
8844     return false; // Conservative answer
8845 
8846   case ICmpInst::ICMP_UGT:
8847   case ICmpInst::ICMP_UGE:
8848   case ICmpInst::ICMP_ULT:
8849   case ICmpInst::ICMP_ULE:
8850     if (!LHS->hasNoUnsignedWrap())
8851       return false;
8852 
8853     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8854     return true;
8855 
8856   case ICmpInst::ICMP_SGT:
8857   case ICmpInst::ICMP_SGE:
8858   case ICmpInst::ICMP_SLT:
8859   case ICmpInst::ICMP_SLE: {
8860     if (!LHS->hasNoSignedWrap())
8861       return false;
8862 
8863     const SCEV *Step = LHS->getStepRecurrence(*this);
8864 
8865     if (isKnownNonNegative(Step)) {
8866       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8867       return true;
8868     }
8869 
8870     if (isKnownNonPositive(Step)) {
8871       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8872       return true;
8873     }
8874 
8875     return false;
8876   }
8877 
8878   }
8879 
8880   llvm_unreachable("switch has default clause!");
8881 }
8882 
8883 bool ScalarEvolution::isLoopInvariantPredicate(
8884     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8885     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8886     const SCEV *&InvariantRHS) {
8887 
8888   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8889   if (!isLoopInvariant(RHS, L)) {
8890     if (!isLoopInvariant(LHS, L))
8891       return false;
8892 
8893     std::swap(LHS, RHS);
8894     Pred = ICmpInst::getSwappedPredicate(Pred);
8895   }
8896 
8897   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8898   if (!ArLHS || ArLHS->getLoop() != L)
8899     return false;
8900 
8901   bool Increasing;
8902   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8903     return false;
8904 
8905   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8906   // true as the loop iterates, and the backedge is control dependent on
8907   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8908   //
8909   //   * if the predicate was false in the first iteration then the predicate
8910   //     is never evaluated again, since the loop exits without taking the
8911   //     backedge.
8912   //   * if the predicate was true in the first iteration then it will
8913   //     continue to be true for all future iterations since it is
8914   //     monotonically increasing.
8915   //
8916   // For both the above possibilities, we can replace the loop varying
8917   // predicate with its value on the first iteration of the loop (which is
8918   // loop invariant).
8919   //
8920   // A similar reasoning applies for a monotonically decreasing predicate, by
8921   // replacing true with false and false with true in the above two bullets.
8922 
8923   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8924 
8925   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8926     return false;
8927 
8928   InvariantPred = Pred;
8929   InvariantLHS = ArLHS->getStart();
8930   InvariantRHS = RHS;
8931   return true;
8932 }
8933 
8934 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8935     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8936   if (HasSameValue(LHS, RHS))
8937     return ICmpInst::isTrueWhenEqual(Pred);
8938 
8939   // This code is split out from isKnownPredicate because it is called from
8940   // within isLoopEntryGuardedByCond.
8941 
8942   auto CheckRanges =
8943       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8944     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8945         .contains(RangeLHS);
8946   };
8947 
8948   // The check at the top of the function catches the case where the values are
8949   // known to be equal.
8950   if (Pred == CmpInst::ICMP_EQ)
8951     return false;
8952 
8953   if (Pred == CmpInst::ICMP_NE)
8954     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8955            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8956            isKnownNonZero(getMinusSCEV(LHS, RHS));
8957 
8958   if (CmpInst::isSigned(Pred))
8959     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8960 
8961   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8962 }
8963 
8964 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8965                                                     const SCEV *LHS,
8966                                                     const SCEV *RHS) {
8967   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8968   // Return Y via OutY.
8969   auto MatchBinaryAddToConst =
8970       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8971              SCEV::NoWrapFlags ExpectedFlags) {
8972     const SCEV *NonConstOp, *ConstOp;
8973     SCEV::NoWrapFlags FlagsPresent;
8974 
8975     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8976         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8977       return false;
8978 
8979     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8980     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8981   };
8982 
8983   APInt C;
8984 
8985   switch (Pred) {
8986   default:
8987     break;
8988 
8989   case ICmpInst::ICMP_SGE:
8990     std::swap(LHS, RHS);
8991     LLVM_FALLTHROUGH;
8992   case ICmpInst::ICMP_SLE:
8993     // X s<= (X + C)<nsw> if C >= 0
8994     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8995       return true;
8996 
8997     // (X + C)<nsw> s<= X if C <= 0
8998     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8999         !C.isStrictlyPositive())
9000       return true;
9001     break;
9002 
9003   case ICmpInst::ICMP_SGT:
9004     std::swap(LHS, RHS);
9005     LLVM_FALLTHROUGH;
9006   case ICmpInst::ICMP_SLT:
9007     // X s< (X + C)<nsw> if C > 0
9008     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9009         C.isStrictlyPositive())
9010       return true;
9011 
9012     // (X + C)<nsw> s< X if C < 0
9013     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9014       return true;
9015     break;
9016   }
9017 
9018   return false;
9019 }
9020 
9021 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9022                                                    const SCEV *LHS,
9023                                                    const SCEV *RHS) {
9024   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9025     return false;
9026 
9027   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9028   // the stack can result in exponential time complexity.
9029   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9030 
9031   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9032   //
9033   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9034   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9035   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9036   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9037   // use isKnownPredicate later if needed.
9038   return isKnownNonNegative(RHS) &&
9039          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9040          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9041 }
9042 
9043 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9044                                         ICmpInst::Predicate Pred,
9045                                         const SCEV *LHS, const SCEV *RHS) {
9046   // No need to even try if we know the module has no guards.
9047   if (!HasGuards)
9048     return false;
9049 
9050   return any_of(*BB, [&](Instruction &I) {
9051     using namespace llvm::PatternMatch;
9052 
9053     Value *Condition;
9054     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9055                          m_Value(Condition))) &&
9056            isImpliedCond(Pred, LHS, RHS, Condition, false);
9057   });
9058 }
9059 
9060 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9061 /// protected by a conditional between LHS and RHS.  This is used to
9062 /// to eliminate casts.
9063 bool
9064 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9065                                              ICmpInst::Predicate Pred,
9066                                              const SCEV *LHS, const SCEV *RHS) {
9067   // Interpret a null as meaning no loop, where there is obviously no guard
9068   // (interprocedural conditions notwithstanding).
9069   if (!L) return true;
9070 
9071   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9072     return true;
9073 
9074   BasicBlock *Latch = L->getLoopLatch();
9075   if (!Latch)
9076     return false;
9077 
9078   BranchInst *LoopContinuePredicate =
9079     dyn_cast<BranchInst>(Latch->getTerminator());
9080   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9081       isImpliedCond(Pred, LHS, RHS,
9082                     LoopContinuePredicate->getCondition(),
9083                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9084     return true;
9085 
9086   // We don't want more than one activation of the following loops on the stack
9087   // -- that can lead to O(n!) time complexity.
9088   if (WalkingBEDominatingConds)
9089     return false;
9090 
9091   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9092 
9093   // See if we can exploit a trip count to prove the predicate.
9094   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9095   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9096   if (LatchBECount != getCouldNotCompute()) {
9097     // We know that Latch branches back to the loop header exactly
9098     // LatchBECount times.  This means the backdege condition at Latch is
9099     // equivalent to  "{0,+,1} u< LatchBECount".
9100     Type *Ty = LatchBECount->getType();
9101     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9102     const SCEV *LoopCounter =
9103       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9104     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9105                       LatchBECount))
9106       return true;
9107   }
9108 
9109   // Check conditions due to any @llvm.assume intrinsics.
9110   for (auto &AssumeVH : AC.assumptions()) {
9111     if (!AssumeVH)
9112       continue;
9113     auto *CI = cast<CallInst>(AssumeVH);
9114     if (!DT.dominates(CI, Latch->getTerminator()))
9115       continue;
9116 
9117     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9118       return true;
9119   }
9120 
9121   // If the loop is not reachable from the entry block, we risk running into an
9122   // infinite loop as we walk up into the dom tree.  These loops do not matter
9123   // anyway, so we just return a conservative answer when we see them.
9124   if (!DT.isReachableFromEntry(L->getHeader()))
9125     return false;
9126 
9127   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9128     return true;
9129 
9130   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9131        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9132     assert(DTN && "should reach the loop header before reaching the root!");
9133 
9134     BasicBlock *BB = DTN->getBlock();
9135     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9136       return true;
9137 
9138     BasicBlock *PBB = BB->getSinglePredecessor();
9139     if (!PBB)
9140       continue;
9141 
9142     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9143     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9144       continue;
9145 
9146     Value *Condition = ContinuePredicate->getCondition();
9147 
9148     // If we have an edge `E` within the loop body that dominates the only
9149     // latch, the condition guarding `E` also guards the backedge.  This
9150     // reasoning works only for loops with a single latch.
9151 
9152     BasicBlockEdge DominatingEdge(PBB, BB);
9153     if (DominatingEdge.isSingleEdge()) {
9154       // We're constructively (and conservatively) enumerating edges within the
9155       // loop body that dominate the latch.  The dominator tree better agree
9156       // with us on this:
9157       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9158 
9159       if (isImpliedCond(Pred, LHS, RHS, Condition,
9160                         BB != ContinuePredicate->getSuccessor(0)))
9161         return true;
9162     }
9163   }
9164 
9165   return false;
9166 }
9167 
9168 bool
9169 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9170                                           ICmpInst::Predicate Pred,
9171                                           const SCEV *LHS, const SCEV *RHS) {
9172   // Interpret a null as meaning no loop, where there is obviously no guard
9173   // (interprocedural conditions notwithstanding).
9174   if (!L) return false;
9175 
9176   // Both LHS and RHS must be available at loop entry.
9177   assert(isAvailableAtLoopEntry(LHS, L) &&
9178          "LHS is not available at Loop Entry");
9179   assert(isAvailableAtLoopEntry(RHS, L) &&
9180          "RHS is not available at Loop Entry");
9181 
9182   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9183     return true;
9184 
9185   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9186   // the facts (a >= b && a != b) separately. A typical situation is when the
9187   // non-strict comparison is known from ranges and non-equality is known from
9188   // dominating predicates. If we are proving strict comparison, we always try
9189   // to prove non-equality and non-strict comparison separately.
9190   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9191   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9192   bool ProvedNonStrictComparison = false;
9193   bool ProvedNonEquality = false;
9194 
9195   if (ProvingStrictComparison) {
9196     ProvedNonStrictComparison =
9197         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9198     ProvedNonEquality =
9199         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9200     if (ProvedNonStrictComparison && ProvedNonEquality)
9201       return true;
9202   }
9203 
9204   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9205   auto ProveViaGuard = [&](BasicBlock *Block) {
9206     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9207       return true;
9208     if (ProvingStrictComparison) {
9209       if (!ProvedNonStrictComparison)
9210         ProvedNonStrictComparison =
9211             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9212       if (!ProvedNonEquality)
9213         ProvedNonEquality =
9214             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9215       if (ProvedNonStrictComparison && ProvedNonEquality)
9216         return true;
9217     }
9218     return false;
9219   };
9220 
9221   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9222   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9223     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9224       return true;
9225     if (ProvingStrictComparison) {
9226       if (!ProvedNonStrictComparison)
9227         ProvedNonStrictComparison =
9228             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9229       if (!ProvedNonEquality)
9230         ProvedNonEquality =
9231             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9232       if (ProvedNonStrictComparison && ProvedNonEquality)
9233         return true;
9234     }
9235     return false;
9236   };
9237 
9238   // Starting at the loop predecessor, climb up the predecessor chain, as long
9239   // as there are predecessors that can be found that have unique successors
9240   // leading to the original header.
9241   for (std::pair<BasicBlock *, BasicBlock *>
9242          Pair(L->getLoopPredecessor(), L->getHeader());
9243        Pair.first;
9244        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9245 
9246     if (ProveViaGuard(Pair.first))
9247       return true;
9248 
9249     BranchInst *LoopEntryPredicate =
9250       dyn_cast<BranchInst>(Pair.first->getTerminator());
9251     if (!LoopEntryPredicate ||
9252         LoopEntryPredicate->isUnconditional())
9253       continue;
9254 
9255     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9256                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9257       return true;
9258   }
9259 
9260   // Check conditions due to any @llvm.assume intrinsics.
9261   for (auto &AssumeVH : AC.assumptions()) {
9262     if (!AssumeVH)
9263       continue;
9264     auto *CI = cast<CallInst>(AssumeVH);
9265     if (!DT.dominates(CI, L->getHeader()))
9266       continue;
9267 
9268     if (ProveViaCond(CI->getArgOperand(0), false))
9269       return true;
9270   }
9271 
9272   return false;
9273 }
9274 
9275 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9276                                     const SCEV *LHS, const SCEV *RHS,
9277                                     Value *FoundCondValue,
9278                                     bool Inverse) {
9279   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9280     return false;
9281 
9282   auto ClearOnExit =
9283       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9284 
9285   // Recursively handle And and Or conditions.
9286   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9287     if (BO->getOpcode() == Instruction::And) {
9288       if (!Inverse)
9289         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9290                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9291     } else if (BO->getOpcode() == Instruction::Or) {
9292       if (Inverse)
9293         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9294                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9295     }
9296   }
9297 
9298   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9299   if (!ICI) return false;
9300 
9301   // Now that we found a conditional branch that dominates the loop or controls
9302   // the loop latch. Check to see if it is the comparison we are looking for.
9303   ICmpInst::Predicate FoundPred;
9304   if (Inverse)
9305     FoundPred = ICI->getInversePredicate();
9306   else
9307     FoundPred = ICI->getPredicate();
9308 
9309   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9310   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9311 
9312   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9313 }
9314 
9315 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9316                                     const SCEV *RHS,
9317                                     ICmpInst::Predicate FoundPred,
9318                                     const SCEV *FoundLHS,
9319                                     const SCEV *FoundRHS) {
9320   // Balance the types.
9321   if (getTypeSizeInBits(LHS->getType()) <
9322       getTypeSizeInBits(FoundLHS->getType())) {
9323     if (CmpInst::isSigned(Pred)) {
9324       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9325       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9326     } else {
9327       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9328       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9329     }
9330   } else if (getTypeSizeInBits(LHS->getType()) >
9331       getTypeSizeInBits(FoundLHS->getType())) {
9332     if (CmpInst::isSigned(FoundPred)) {
9333       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9334       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9335     } else {
9336       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9337       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9338     }
9339   }
9340 
9341   // Canonicalize the query to match the way instcombine will have
9342   // canonicalized the comparison.
9343   if (SimplifyICmpOperands(Pred, LHS, RHS))
9344     if (LHS == RHS)
9345       return CmpInst::isTrueWhenEqual(Pred);
9346   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9347     if (FoundLHS == FoundRHS)
9348       return CmpInst::isFalseWhenEqual(FoundPred);
9349 
9350   // Check to see if we can make the LHS or RHS match.
9351   if (LHS == FoundRHS || RHS == FoundLHS) {
9352     if (isa<SCEVConstant>(RHS)) {
9353       std::swap(FoundLHS, FoundRHS);
9354       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9355     } else {
9356       std::swap(LHS, RHS);
9357       Pred = ICmpInst::getSwappedPredicate(Pred);
9358     }
9359   }
9360 
9361   // Check whether the found predicate is the same as the desired predicate.
9362   if (FoundPred == Pred)
9363     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9364 
9365   // Check whether swapping the found predicate makes it the same as the
9366   // desired predicate.
9367   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9368     if (isa<SCEVConstant>(RHS))
9369       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9370     else
9371       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9372                                    RHS, LHS, FoundLHS, FoundRHS);
9373   }
9374 
9375   // Unsigned comparison is the same as signed comparison when both the operands
9376   // are non-negative.
9377   if (CmpInst::isUnsigned(FoundPred) &&
9378       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9379       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9380     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9381 
9382   // Check if we can make progress by sharpening ranges.
9383   if (FoundPred == ICmpInst::ICMP_NE &&
9384       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9385 
9386     const SCEVConstant *C = nullptr;
9387     const SCEV *V = nullptr;
9388 
9389     if (isa<SCEVConstant>(FoundLHS)) {
9390       C = cast<SCEVConstant>(FoundLHS);
9391       V = FoundRHS;
9392     } else {
9393       C = cast<SCEVConstant>(FoundRHS);
9394       V = FoundLHS;
9395     }
9396 
9397     // The guarding predicate tells us that C != V. If the known range
9398     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9399     // range we consider has to correspond to same signedness as the
9400     // predicate we're interested in folding.
9401 
9402     APInt Min = ICmpInst::isSigned(Pred) ?
9403         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9404 
9405     if (Min == C->getAPInt()) {
9406       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9407       // This is true even if (Min + 1) wraps around -- in case of
9408       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9409 
9410       APInt SharperMin = Min + 1;
9411 
9412       switch (Pred) {
9413         case ICmpInst::ICMP_SGE:
9414         case ICmpInst::ICMP_UGE:
9415           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9416           // RHS, we're done.
9417           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9418                                     getConstant(SharperMin)))
9419             return true;
9420           LLVM_FALLTHROUGH;
9421 
9422         case ICmpInst::ICMP_SGT:
9423         case ICmpInst::ICMP_UGT:
9424           // We know from the range information that (V `Pred` Min ||
9425           // V == Min).  We know from the guarding condition that !(V
9426           // == Min).  This gives us
9427           //
9428           //       V `Pred` Min || V == Min && !(V == Min)
9429           //   =>  V `Pred` Min
9430           //
9431           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9432 
9433           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9434             return true;
9435           LLVM_FALLTHROUGH;
9436 
9437         default:
9438           // No change
9439           break;
9440       }
9441     }
9442   }
9443 
9444   // Check whether the actual condition is beyond sufficient.
9445   if (FoundPred == ICmpInst::ICMP_EQ)
9446     if (ICmpInst::isTrueWhenEqual(Pred))
9447       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9448         return true;
9449   if (Pred == ICmpInst::ICMP_NE)
9450     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9451       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9452         return true;
9453 
9454   // Otherwise assume the worst.
9455   return false;
9456 }
9457 
9458 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9459                                      const SCEV *&L, const SCEV *&R,
9460                                      SCEV::NoWrapFlags &Flags) {
9461   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9462   if (!AE || AE->getNumOperands() != 2)
9463     return false;
9464 
9465   L = AE->getOperand(0);
9466   R = AE->getOperand(1);
9467   Flags = AE->getNoWrapFlags();
9468   return true;
9469 }
9470 
9471 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9472                                                            const SCEV *Less) {
9473   // We avoid subtracting expressions here because this function is usually
9474   // fairly deep in the call stack (i.e. is called many times).
9475 
9476   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9477     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9478     const auto *MAR = cast<SCEVAddRecExpr>(More);
9479 
9480     if (LAR->getLoop() != MAR->getLoop())
9481       return None;
9482 
9483     // We look at affine expressions only; not for correctness but to keep
9484     // getStepRecurrence cheap.
9485     if (!LAR->isAffine() || !MAR->isAffine())
9486       return None;
9487 
9488     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9489       return None;
9490 
9491     Less = LAR->getStart();
9492     More = MAR->getStart();
9493 
9494     // fall through
9495   }
9496 
9497   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9498     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9499     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9500     return M - L;
9501   }
9502 
9503   SCEV::NoWrapFlags Flags;
9504   const SCEV *LLess = nullptr, *RLess = nullptr;
9505   const SCEV *LMore = nullptr, *RMore = nullptr;
9506   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9507   // Compare (X + C1) vs X.
9508   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9509     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9510       if (RLess == More)
9511         return -(C1->getAPInt());
9512 
9513   // Compare X vs (X + C2).
9514   if (splitBinaryAdd(More, LMore, RMore, Flags))
9515     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9516       if (RMore == Less)
9517         return C2->getAPInt();
9518 
9519   // Compare (X + C1) vs (X + C2).
9520   if (C1 && C2 && RLess == RMore)
9521     return C2->getAPInt() - C1->getAPInt();
9522 
9523   return None;
9524 }
9525 
9526 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9527     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9528     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9529   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9530     return false;
9531 
9532   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9533   if (!AddRecLHS)
9534     return false;
9535 
9536   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9537   if (!AddRecFoundLHS)
9538     return false;
9539 
9540   // We'd like to let SCEV reason about control dependencies, so we constrain
9541   // both the inequalities to be about add recurrences on the same loop.  This
9542   // way we can use isLoopEntryGuardedByCond later.
9543 
9544   const Loop *L = AddRecFoundLHS->getLoop();
9545   if (L != AddRecLHS->getLoop())
9546     return false;
9547 
9548   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9549   //
9550   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9551   //                                                                  ... (2)
9552   //
9553   // Informal proof for (2), assuming (1) [*]:
9554   //
9555   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9556   //
9557   // Then
9558   //
9559   //       FoundLHS s< FoundRHS s< INT_MIN - C
9560   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9561   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9562   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9563   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9564   // <=>  FoundLHS + C s< FoundRHS + C
9565   //
9566   // [*]: (1) can be proved by ruling out overflow.
9567   //
9568   // [**]: This can be proved by analyzing all the four possibilities:
9569   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9570   //    (A s>= 0, B s>= 0).
9571   //
9572   // Note:
9573   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9574   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9575   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9576   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9577   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9578   // C)".
9579 
9580   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9581   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9582   if (!LDiff || !RDiff || *LDiff != *RDiff)
9583     return false;
9584 
9585   if (LDiff->isMinValue())
9586     return true;
9587 
9588   APInt FoundRHSLimit;
9589 
9590   if (Pred == CmpInst::ICMP_ULT) {
9591     FoundRHSLimit = -(*RDiff);
9592   } else {
9593     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9594     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9595   }
9596 
9597   // Try to prove (1) or (2), as needed.
9598   return isAvailableAtLoopEntry(FoundRHS, L) &&
9599          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9600                                   getConstant(FoundRHSLimit));
9601 }
9602 
9603 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9604                                         const SCEV *LHS, const SCEV *RHS,
9605                                         const SCEV *FoundLHS,
9606                                         const SCEV *FoundRHS, unsigned Depth) {
9607   const PHINode *LPhi = nullptr, *RPhi = nullptr;
9608 
9609   auto ClearOnExit = make_scope_exit([&]() {
9610     if (LPhi) {
9611       bool Erased = PendingMerges.erase(LPhi);
9612       assert(Erased && "Failed to erase LPhi!");
9613       (void)Erased;
9614     }
9615     if (RPhi) {
9616       bool Erased = PendingMerges.erase(RPhi);
9617       assert(Erased && "Failed to erase RPhi!");
9618       (void)Erased;
9619     }
9620   });
9621 
9622   // Find respective Phis and check that they are not being pending.
9623   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9624     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9625       if (!PendingMerges.insert(Phi).second)
9626         return false;
9627       LPhi = Phi;
9628     }
9629   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9630     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9631       // If we detect a loop of Phi nodes being processed by this method, for
9632       // example:
9633       //
9634       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9635       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9636       //
9637       // we don't want to deal with a case that complex, so return conservative
9638       // answer false.
9639       if (!PendingMerges.insert(Phi).second)
9640         return false;
9641       RPhi = Phi;
9642     }
9643 
9644   // If none of LHS, RHS is a Phi, nothing to do here.
9645   if (!LPhi && !RPhi)
9646     return false;
9647 
9648   // If there is a SCEVUnknown Phi we are interested in, make it left.
9649   if (!LPhi) {
9650     std::swap(LHS, RHS);
9651     std::swap(FoundLHS, FoundRHS);
9652     std::swap(LPhi, RPhi);
9653     Pred = ICmpInst::getSwappedPredicate(Pred);
9654   }
9655 
9656   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
9657   const BasicBlock *LBB = LPhi->getParent();
9658   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9659 
9660   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
9661     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
9662            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
9663            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
9664   };
9665 
9666   if (RPhi && RPhi->getParent() == LBB) {
9667     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
9668     // If we compare two Phis from the same block, and for each entry block
9669     // the predicate is true for incoming values from this block, then the
9670     // predicate is also true for the Phis.
9671     for (const BasicBlock *IncBB : predecessors(LBB)) {
9672       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9673       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
9674       if (!ProvedEasily(L, R))
9675         return false;
9676     }
9677   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
9678     // Case two: RHS is also a Phi from the same basic block, and it is an
9679     // AddRec. It means that there is a loop which has both AddRec and Unknown
9680     // PHIs, for it we can compare incoming values of AddRec from above the loop
9681     // and latch with their respective incoming values of LPhi.
9682     assert(LPhi->getNumIncomingValues() == 2 &&
9683            "Phi node standing in loop header does not have exactly 2 inputs?");
9684     auto *RLoop = RAR->getLoop();
9685     auto *Predecessor = RLoop->getLoopPredecessor();
9686     assert(Predecessor && "Loop with AddRec with no predecessor?");
9687     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
9688     if (!ProvedEasily(L1, RAR->getStart()))
9689       return false;
9690     auto *Latch = RLoop->getLoopLatch();
9691     assert(Latch && "Loop with AddRec with no latch?");
9692     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
9693     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
9694       return false;
9695   } else {
9696     // In all other cases go over inputs of LHS and compare each of them to RHS,
9697     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
9698     // At this point RHS is either a non-Phi, or it is a Phi from some block
9699     // different from LBB.
9700     for (const BasicBlock *IncBB : predecessors(LBB)) {
9701       // Check that RHS is available in this block.
9702       if (!dominates(RHS, IncBB))
9703         return false;
9704       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9705       if (!ProvedEasily(L, RHS))
9706         return false;
9707     }
9708   }
9709   return true;
9710 }
9711 
9712 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9713                                             const SCEV *LHS, const SCEV *RHS,
9714                                             const SCEV *FoundLHS,
9715                                             const SCEV *FoundRHS) {
9716   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9717     return true;
9718 
9719   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9720     return true;
9721 
9722   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9723                                      FoundLHS, FoundRHS) ||
9724          // ~x < ~y --> x > y
9725          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9726                                      getNotSCEV(FoundRHS),
9727                                      getNotSCEV(FoundLHS));
9728 }
9729 
9730 /// If Expr computes ~A, return A else return nullptr
9731 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9732   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9733   if (!Add || Add->getNumOperands() != 2 ||
9734       !Add->getOperand(0)->isAllOnesValue())
9735     return nullptr;
9736 
9737   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9738   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9739       !AddRHS->getOperand(0)->isAllOnesValue())
9740     return nullptr;
9741 
9742   return AddRHS->getOperand(1);
9743 }
9744 
9745 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9746 template<typename MaxExprType>
9747 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9748                               const SCEV *Candidate) {
9749   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9750   if (!MaxExpr) return false;
9751 
9752   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9753 }
9754 
9755 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9756 template<typename MaxExprType>
9757 static bool IsMinConsistingOf(ScalarEvolution &SE,
9758                               const SCEV *MaybeMinExpr,
9759                               const SCEV *Candidate) {
9760   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9761   if (!MaybeMaxExpr)
9762     return false;
9763 
9764   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9765 }
9766 
9767 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9768                                            ICmpInst::Predicate Pred,
9769                                            const SCEV *LHS, const SCEV *RHS) {
9770   // If both sides are affine addrecs for the same loop, with equal
9771   // steps, and we know the recurrences don't wrap, then we only
9772   // need to check the predicate on the starting values.
9773 
9774   if (!ICmpInst::isRelational(Pred))
9775     return false;
9776 
9777   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9778   if (!LAR)
9779     return false;
9780   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9781   if (!RAR)
9782     return false;
9783   if (LAR->getLoop() != RAR->getLoop())
9784     return false;
9785   if (!LAR->isAffine() || !RAR->isAffine())
9786     return false;
9787 
9788   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9789     return false;
9790 
9791   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9792                          SCEV::FlagNSW : SCEV::FlagNUW;
9793   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9794     return false;
9795 
9796   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9797 }
9798 
9799 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9800 /// expression?
9801 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9802                                         ICmpInst::Predicate Pred,
9803                                         const SCEV *LHS, const SCEV *RHS) {
9804   switch (Pred) {
9805   default:
9806     return false;
9807 
9808   case ICmpInst::ICMP_SGE:
9809     std::swap(LHS, RHS);
9810     LLVM_FALLTHROUGH;
9811   case ICmpInst::ICMP_SLE:
9812     return
9813       // min(A, ...) <= A
9814       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9815       // A <= max(A, ...)
9816       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9817 
9818   case ICmpInst::ICMP_UGE:
9819     std::swap(LHS, RHS);
9820     LLVM_FALLTHROUGH;
9821   case ICmpInst::ICMP_ULE:
9822     return
9823       // min(A, ...) <= A
9824       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9825       // A <= max(A, ...)
9826       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9827   }
9828 
9829   llvm_unreachable("covered switch fell through?!");
9830 }
9831 
9832 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9833                                              const SCEV *LHS, const SCEV *RHS,
9834                                              const SCEV *FoundLHS,
9835                                              const SCEV *FoundRHS,
9836                                              unsigned Depth) {
9837   assert(getTypeSizeInBits(LHS->getType()) ==
9838              getTypeSizeInBits(RHS->getType()) &&
9839          "LHS and RHS have different sizes?");
9840   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9841              getTypeSizeInBits(FoundRHS->getType()) &&
9842          "FoundLHS and FoundRHS have different sizes?");
9843   // We want to avoid hurting the compile time with analysis of too big trees.
9844   if (Depth > MaxSCEVOperationsImplicationDepth)
9845     return false;
9846   // We only want to work with ICMP_SGT comparison so far.
9847   // TODO: Extend to ICMP_UGT?
9848   if (Pred == ICmpInst::ICMP_SLT) {
9849     Pred = ICmpInst::ICMP_SGT;
9850     std::swap(LHS, RHS);
9851     std::swap(FoundLHS, FoundRHS);
9852   }
9853   if (Pred != ICmpInst::ICMP_SGT)
9854     return false;
9855 
9856   auto GetOpFromSExt = [&](const SCEV *S) {
9857     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9858       return Ext->getOperand();
9859     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9860     // the constant in some cases.
9861     return S;
9862   };
9863 
9864   // Acquire values from extensions.
9865   auto *OrigLHS = LHS;
9866   auto *OrigFoundLHS = FoundLHS;
9867   LHS = GetOpFromSExt(LHS);
9868   FoundLHS = GetOpFromSExt(FoundLHS);
9869 
9870   // Is the SGT predicate can be proved trivially or using the found context.
9871   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9872     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9873            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9874                                   FoundRHS, Depth + 1);
9875   };
9876 
9877   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9878     // We want to avoid creation of any new non-constant SCEV. Since we are
9879     // going to compare the operands to RHS, we should be certain that we don't
9880     // need any size extensions for this. So let's decline all cases when the
9881     // sizes of types of LHS and RHS do not match.
9882     // TODO: Maybe try to get RHS from sext to catch more cases?
9883     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9884       return false;
9885 
9886     // Should not overflow.
9887     if (!LHSAddExpr->hasNoSignedWrap())
9888       return false;
9889 
9890     auto *LL = LHSAddExpr->getOperand(0);
9891     auto *LR = LHSAddExpr->getOperand(1);
9892     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9893 
9894     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9895     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9896       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9897     };
9898     // Try to prove the following rule:
9899     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9900     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9901     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9902       return true;
9903   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9904     Value *LL, *LR;
9905     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9906 
9907     using namespace llvm::PatternMatch;
9908 
9909     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9910       // Rules for division.
9911       // We are going to perform some comparisons with Denominator and its
9912       // derivative expressions. In general case, creating a SCEV for it may
9913       // lead to a complex analysis of the entire graph, and in particular it
9914       // can request trip count recalculation for the same loop. This would
9915       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9916       // this, we only want to create SCEVs that are constants in this section.
9917       // So we bail if Denominator is not a constant.
9918       if (!isa<ConstantInt>(LR))
9919         return false;
9920 
9921       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9922 
9923       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9924       // then a SCEV for the numerator already exists and matches with FoundLHS.
9925       auto *Numerator = getExistingSCEV(LL);
9926       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9927         return false;
9928 
9929       // Make sure that the numerator matches with FoundLHS and the denominator
9930       // is positive.
9931       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9932         return false;
9933 
9934       auto *DTy = Denominator->getType();
9935       auto *FRHSTy = FoundRHS->getType();
9936       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9937         // One of types is a pointer and another one is not. We cannot extend
9938         // them properly to a wider type, so let us just reject this case.
9939         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9940         // to avoid this check.
9941         return false;
9942 
9943       // Given that:
9944       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9945       auto *WTy = getWiderType(DTy, FRHSTy);
9946       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9947       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9948 
9949       // Try to prove the following rule:
9950       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9951       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9952       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9953       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9954       if (isKnownNonPositive(RHS) &&
9955           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9956         return true;
9957 
9958       // Try to prove the following rule:
9959       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9960       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9961       // If we divide it by Denominator > 2, then:
9962       // 1. If FoundLHS is negative, then the result is 0.
9963       // 2. If FoundLHS is non-negative, then the result is non-negative.
9964       // Anyways, the result is non-negative.
9965       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9966       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9967       if (isKnownNegative(RHS) &&
9968           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9969         return true;
9970     }
9971   }
9972 
9973   // If our expression contained SCEVUnknown Phis, and we split it down and now
9974   // need to prove something for them, try to prove the predicate for every
9975   // possible incoming values of those Phis.
9976   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
9977     return true;
9978 
9979   return false;
9980 }
9981 
9982 bool
9983 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
9984                                            const SCEV *LHS, const SCEV *RHS) {
9985   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9986          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9987          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9988          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9989 }
9990 
9991 bool
9992 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9993                                              const SCEV *LHS, const SCEV *RHS,
9994                                              const SCEV *FoundLHS,
9995                                              const SCEV *FoundRHS) {
9996   switch (Pred) {
9997   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9998   case ICmpInst::ICMP_EQ:
9999   case ICmpInst::ICMP_NE:
10000     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10001       return true;
10002     break;
10003   case ICmpInst::ICMP_SLT:
10004   case ICmpInst::ICMP_SLE:
10005     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10006         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10007       return true;
10008     break;
10009   case ICmpInst::ICMP_SGT:
10010   case ICmpInst::ICMP_SGE:
10011     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10012         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10013       return true;
10014     break;
10015   case ICmpInst::ICMP_ULT:
10016   case ICmpInst::ICMP_ULE:
10017     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10018         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10019       return true;
10020     break;
10021   case ICmpInst::ICMP_UGT:
10022   case ICmpInst::ICMP_UGE:
10023     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10024         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10025       return true;
10026     break;
10027   }
10028 
10029   // Maybe it can be proved via operations?
10030   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10031     return true;
10032 
10033   return false;
10034 }
10035 
10036 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10037                                                      const SCEV *LHS,
10038                                                      const SCEV *RHS,
10039                                                      const SCEV *FoundLHS,
10040                                                      const SCEV *FoundRHS) {
10041   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10042     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10043     // reduce the compile time impact of this optimization.
10044     return false;
10045 
10046   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10047   if (!Addend)
10048     return false;
10049 
10050   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10051 
10052   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10053   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10054   ConstantRange FoundLHSRange =
10055       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10056 
10057   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10058   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10059 
10060   // We can also compute the range of values for `LHS` that satisfy the
10061   // consequent, "`LHS` `Pred` `RHS`":
10062   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10063   ConstantRange SatisfyingLHSRange =
10064       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10065 
10066   // The antecedent implies the consequent if every value of `LHS` that
10067   // satisfies the antecedent also satisfies the consequent.
10068   return SatisfyingLHSRange.contains(LHSRange);
10069 }
10070 
10071 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10072                                          bool IsSigned, bool NoWrap) {
10073   assert(isKnownPositive(Stride) && "Positive stride expected!");
10074 
10075   if (NoWrap) return false;
10076 
10077   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10078   const SCEV *One = getOne(Stride->getType());
10079 
10080   if (IsSigned) {
10081     APInt MaxRHS = getSignedRangeMax(RHS);
10082     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10083     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10084 
10085     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10086     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10087   }
10088 
10089   APInt MaxRHS = getUnsignedRangeMax(RHS);
10090   APInt MaxValue = APInt::getMaxValue(BitWidth);
10091   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10092 
10093   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10094   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10095 }
10096 
10097 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10098                                          bool IsSigned, bool NoWrap) {
10099   if (NoWrap) return false;
10100 
10101   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10102   const SCEV *One = getOne(Stride->getType());
10103 
10104   if (IsSigned) {
10105     APInt MinRHS = getSignedRangeMin(RHS);
10106     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10107     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10108 
10109     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10110     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10111   }
10112 
10113   APInt MinRHS = getUnsignedRangeMin(RHS);
10114   APInt MinValue = APInt::getMinValue(BitWidth);
10115   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10116 
10117   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10118   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10119 }
10120 
10121 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10122                                             bool Equality) {
10123   const SCEV *One = getOne(Step->getType());
10124   Delta = Equality ? getAddExpr(Delta, Step)
10125                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10126   return getUDivExpr(Delta, Step);
10127 }
10128 
10129 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10130                                                     const SCEV *Stride,
10131                                                     const SCEV *End,
10132                                                     unsigned BitWidth,
10133                                                     bool IsSigned) {
10134 
10135   assert(!isKnownNonPositive(Stride) &&
10136          "Stride is expected strictly positive!");
10137   // Calculate the maximum backedge count based on the range of values
10138   // permitted by Start, End, and Stride.
10139   const SCEV *MaxBECount;
10140   APInt MinStart =
10141       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10142 
10143   APInt StrideForMaxBECount =
10144       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10145 
10146   // We already know that the stride is positive, so we paper over conservatism
10147   // in our range computation by forcing StrideForMaxBECount to be at least one.
10148   // In theory this is unnecessary, but we expect MaxBECount to be a
10149   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10150   // is nothing to constant fold it to).
10151   APInt One(BitWidth, 1, IsSigned);
10152   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10153 
10154   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10155                             : APInt::getMaxValue(BitWidth);
10156   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10157 
10158   // Although End can be a MAX expression we estimate MaxEnd considering only
10159   // the case End = RHS of the loop termination condition. This is safe because
10160   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10161   // taken count.
10162   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10163                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10164 
10165   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10166                               getConstant(StrideForMaxBECount) /* Step */,
10167                               false /* Equality */);
10168 
10169   return MaxBECount;
10170 }
10171 
10172 ScalarEvolution::ExitLimit
10173 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10174                                   const Loop *L, bool IsSigned,
10175                                   bool ControlsExit, bool AllowPredicates) {
10176   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10177 
10178   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10179   bool PredicatedIV = false;
10180 
10181   if (!IV && AllowPredicates) {
10182     // Try to make this an AddRec using runtime tests, in the first X
10183     // iterations of this loop, where X is the SCEV expression found by the
10184     // algorithm below.
10185     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10186     PredicatedIV = true;
10187   }
10188 
10189   // Avoid weird loops
10190   if (!IV || IV->getLoop() != L || !IV->isAffine())
10191     return getCouldNotCompute();
10192 
10193   bool NoWrap = ControlsExit &&
10194                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10195 
10196   const SCEV *Stride = IV->getStepRecurrence(*this);
10197 
10198   bool PositiveStride = isKnownPositive(Stride);
10199 
10200   // Avoid negative or zero stride values.
10201   if (!PositiveStride) {
10202     // We can compute the correct backedge taken count for loops with unknown
10203     // strides if we can prove that the loop is not an infinite loop with side
10204     // effects. Here's the loop structure we are trying to handle -
10205     //
10206     // i = start
10207     // do {
10208     //   A[i] = i;
10209     //   i += s;
10210     // } while (i < end);
10211     //
10212     // The backedge taken count for such loops is evaluated as -
10213     // (max(end, start + stride) - start - 1) /u stride
10214     //
10215     // The additional preconditions that we need to check to prove correctness
10216     // of the above formula is as follows -
10217     //
10218     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10219     //    NoWrap flag).
10220     // b) loop is single exit with no side effects.
10221     //
10222     //
10223     // Precondition a) implies that if the stride is negative, this is a single
10224     // trip loop. The backedge taken count formula reduces to zero in this case.
10225     //
10226     // Precondition b) implies that the unknown stride cannot be zero otherwise
10227     // we have UB.
10228     //
10229     // The positive stride case is the same as isKnownPositive(Stride) returning
10230     // true (original behavior of the function).
10231     //
10232     // We want to make sure that the stride is truly unknown as there are edge
10233     // cases where ScalarEvolution propagates no wrap flags to the
10234     // post-increment/decrement IV even though the increment/decrement operation
10235     // itself is wrapping. The computed backedge taken count may be wrong in
10236     // such cases. This is prevented by checking that the stride is not known to
10237     // be either positive or non-positive. For example, no wrap flags are
10238     // propagated to the post-increment IV of this loop with a trip count of 2 -
10239     //
10240     // unsigned char i;
10241     // for(i=127; i<128; i+=129)
10242     //   A[i] = i;
10243     //
10244     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10245         !loopHasNoSideEffects(L))
10246       return getCouldNotCompute();
10247   } else if (!Stride->isOne() &&
10248              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10249     // Avoid proven overflow cases: this will ensure that the backedge taken
10250     // count will not generate any unsigned overflow. Relaxed no-overflow
10251     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10252     // undefined behaviors like the case of C language.
10253     return getCouldNotCompute();
10254 
10255   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10256                                       : ICmpInst::ICMP_ULT;
10257   const SCEV *Start = IV->getStart();
10258   const SCEV *End = RHS;
10259   // When the RHS is not invariant, we do not know the end bound of the loop and
10260   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10261   // calculate the MaxBECount, given the start, stride and max value for the end
10262   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10263   // checked above).
10264   if (!isLoopInvariant(RHS, L)) {
10265     const SCEV *MaxBECount = computeMaxBECountForLT(
10266         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10267     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10268                      false /*MaxOrZero*/, Predicates);
10269   }
10270   // If the backedge is taken at least once, then it will be taken
10271   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10272   // is the LHS value of the less-than comparison the first time it is evaluated
10273   // and End is the RHS.
10274   const SCEV *BECountIfBackedgeTaken =
10275     computeBECount(getMinusSCEV(End, Start), Stride, false);
10276   // If the loop entry is guarded by the result of the backedge test of the
10277   // first loop iteration, then we know the backedge will be taken at least
10278   // once and so the backedge taken count is as above. If not then we use the
10279   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10280   // as if the backedge is taken at least once max(End,Start) is End and so the
10281   // result is as above, and if not max(End,Start) is Start so we get a backedge
10282   // count of zero.
10283   const SCEV *BECount;
10284   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10285     BECount = BECountIfBackedgeTaken;
10286   else {
10287     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10288     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10289   }
10290 
10291   const SCEV *MaxBECount;
10292   bool MaxOrZero = false;
10293   if (isa<SCEVConstant>(BECount))
10294     MaxBECount = BECount;
10295   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10296     // If we know exactly how many times the backedge will be taken if it's
10297     // taken at least once, then the backedge count will either be that or
10298     // zero.
10299     MaxBECount = BECountIfBackedgeTaken;
10300     MaxOrZero = true;
10301   } else {
10302     MaxBECount = computeMaxBECountForLT(
10303         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10304   }
10305 
10306   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10307       !isa<SCEVCouldNotCompute>(BECount))
10308     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10309 
10310   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10311 }
10312 
10313 ScalarEvolution::ExitLimit
10314 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10315                                      const Loop *L, bool IsSigned,
10316                                      bool ControlsExit, bool AllowPredicates) {
10317   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10318   // We handle only IV > Invariant
10319   if (!isLoopInvariant(RHS, L))
10320     return getCouldNotCompute();
10321 
10322   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10323   if (!IV && AllowPredicates)
10324     // Try to make this an AddRec using runtime tests, in the first X
10325     // iterations of this loop, where X is the SCEV expression found by the
10326     // algorithm below.
10327     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10328 
10329   // Avoid weird loops
10330   if (!IV || IV->getLoop() != L || !IV->isAffine())
10331     return getCouldNotCompute();
10332 
10333   bool NoWrap = ControlsExit &&
10334                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10335 
10336   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10337 
10338   // Avoid negative or zero stride values
10339   if (!isKnownPositive(Stride))
10340     return getCouldNotCompute();
10341 
10342   // Avoid proven overflow cases: this will ensure that the backedge taken count
10343   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10344   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10345   // behaviors like the case of C language.
10346   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10347     return getCouldNotCompute();
10348 
10349   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10350                                       : ICmpInst::ICMP_UGT;
10351 
10352   const SCEV *Start = IV->getStart();
10353   const SCEV *End = RHS;
10354   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10355     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10356 
10357   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10358 
10359   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10360                             : getUnsignedRangeMax(Start);
10361 
10362   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10363                              : getUnsignedRangeMin(Stride);
10364 
10365   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10366   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10367                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10368 
10369   // Although End can be a MIN expression we estimate MinEnd considering only
10370   // the case End = RHS. This is safe because in the other case (Start - End)
10371   // is zero, leading to a zero maximum backedge taken count.
10372   APInt MinEnd =
10373     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10374              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10375 
10376 
10377   const SCEV *MaxBECount = getCouldNotCompute();
10378   if (isa<SCEVConstant>(BECount))
10379     MaxBECount = BECount;
10380   else
10381     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10382                                 getConstant(MinStride), false);
10383 
10384   if (isa<SCEVCouldNotCompute>(MaxBECount))
10385     MaxBECount = BECount;
10386 
10387   return ExitLimit(BECount, MaxBECount, false, Predicates);
10388 }
10389 
10390 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10391                                                     ScalarEvolution &SE) const {
10392   if (Range.isFullSet())  // Infinite loop.
10393     return SE.getCouldNotCompute();
10394 
10395   // If the start is a non-zero constant, shift the range to simplify things.
10396   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10397     if (!SC->getValue()->isZero()) {
10398       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10399       Operands[0] = SE.getZero(SC->getType());
10400       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10401                                              getNoWrapFlags(FlagNW));
10402       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10403         return ShiftedAddRec->getNumIterationsInRange(
10404             Range.subtract(SC->getAPInt()), SE);
10405       // This is strange and shouldn't happen.
10406       return SE.getCouldNotCompute();
10407     }
10408 
10409   // The only time we can solve this is when we have all constant indices.
10410   // Otherwise, we cannot determine the overflow conditions.
10411   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10412     return SE.getCouldNotCompute();
10413 
10414   // Okay at this point we know that all elements of the chrec are constants and
10415   // that the start element is zero.
10416 
10417   // First check to see if the range contains zero.  If not, the first
10418   // iteration exits.
10419   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10420   if (!Range.contains(APInt(BitWidth, 0)))
10421     return SE.getZero(getType());
10422 
10423   if (isAffine()) {
10424     // If this is an affine expression then we have this situation:
10425     //   Solve {0,+,A} in Range  ===  Ax in Range
10426 
10427     // We know that zero is in the range.  If A is positive then we know that
10428     // the upper value of the range must be the first possible exit value.
10429     // If A is negative then the lower of the range is the last possible loop
10430     // value.  Also note that we already checked for a full range.
10431     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10432     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10433 
10434     // The exit value should be (End+A)/A.
10435     APInt ExitVal = (End + A).udiv(A);
10436     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10437 
10438     // Evaluate at the exit value.  If we really did fall out of the valid
10439     // range, then we computed our trip count, otherwise wrap around or other
10440     // things must have happened.
10441     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10442     if (Range.contains(Val->getValue()))
10443       return SE.getCouldNotCompute();  // Something strange happened
10444 
10445     // Ensure that the previous value is in the range.  This is a sanity check.
10446     assert(Range.contains(
10447            EvaluateConstantChrecAtConstant(this,
10448            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10449            "Linear scev computation is off in a bad way!");
10450     return SE.getConstant(ExitValue);
10451   } else if (isQuadratic()) {
10452     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10453     // quadratic equation to solve it.  To do this, we must frame our problem in
10454     // terms of figuring out when zero is crossed, instead of when
10455     // Range.getUpper() is crossed.
10456     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10457     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10458     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10459 
10460     // Next, solve the constructed addrec
10461     if (auto Roots =
10462             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10463       const SCEVConstant *R1 = Roots->first;
10464       const SCEVConstant *R2 = Roots->second;
10465       // Pick the smallest positive root value.
10466       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10467               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10468         if (!CB->getZExtValue())
10469           std::swap(R1, R2); // R1 is the minimum root now.
10470 
10471         // Make sure the root is not off by one.  The returned iteration should
10472         // not be in the range, but the previous one should be.  When solving
10473         // for "X*X < 5", for example, we should not return a root of 2.
10474         ConstantInt *R1Val =
10475             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10476         if (Range.contains(R1Val->getValue())) {
10477           // The next iteration must be out of the range...
10478           ConstantInt *NextVal =
10479               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10480 
10481           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10482           if (!Range.contains(R1Val->getValue()))
10483             return SE.getConstant(NextVal);
10484           return SE.getCouldNotCompute(); // Something strange happened
10485         }
10486 
10487         // If R1 was not in the range, then it is a good return value.  Make
10488         // sure that R1-1 WAS in the range though, just in case.
10489         ConstantInt *NextVal =
10490             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10491         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10492         if (Range.contains(R1Val->getValue()))
10493           return R1;
10494         return SE.getCouldNotCompute(); // Something strange happened
10495       }
10496     }
10497   }
10498 
10499   return SE.getCouldNotCompute();
10500 }
10501 
10502 const SCEVAddRecExpr *
10503 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10504   assert(getNumOperands() > 1 && "AddRec with zero step?");
10505   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10506   // but in this case we cannot guarantee that the value returned will be an
10507   // AddRec because SCEV does not have a fixed point where it stops
10508   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10509   // may happen if we reach arithmetic depth limit while simplifying. So we
10510   // construct the returned value explicitly.
10511   SmallVector<const SCEV *, 3> Ops;
10512   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10513   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10514   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10515     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10516   // We know that the last operand is not a constant zero (otherwise it would
10517   // have been popped out earlier). This guarantees us that if the result has
10518   // the same last operand, then it will also not be popped out, meaning that
10519   // the returned value will be an AddRec.
10520   const SCEV *Last = getOperand(getNumOperands() - 1);
10521   assert(!Last->isZero() && "Recurrency with zero step?");
10522   Ops.push_back(Last);
10523   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10524                                                SCEV::FlagAnyWrap));
10525 }
10526 
10527 // Return true when S contains at least an undef value.
10528 static inline bool containsUndefs(const SCEV *S) {
10529   return SCEVExprContains(S, [](const SCEV *S) {
10530     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10531       return isa<UndefValue>(SU->getValue());
10532     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10533       return isa<UndefValue>(SC->getValue());
10534     return false;
10535   });
10536 }
10537 
10538 namespace {
10539 
10540 // Collect all steps of SCEV expressions.
10541 struct SCEVCollectStrides {
10542   ScalarEvolution &SE;
10543   SmallVectorImpl<const SCEV *> &Strides;
10544 
10545   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10546       : SE(SE), Strides(S) {}
10547 
10548   bool follow(const SCEV *S) {
10549     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10550       Strides.push_back(AR->getStepRecurrence(SE));
10551     return true;
10552   }
10553 
10554   bool isDone() const { return false; }
10555 };
10556 
10557 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10558 struct SCEVCollectTerms {
10559   SmallVectorImpl<const SCEV *> &Terms;
10560 
10561   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10562 
10563   bool follow(const SCEV *S) {
10564     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10565         isa<SCEVSignExtendExpr>(S)) {
10566       if (!containsUndefs(S))
10567         Terms.push_back(S);
10568 
10569       // Stop recursion: once we collected a term, do not walk its operands.
10570       return false;
10571     }
10572 
10573     // Keep looking.
10574     return true;
10575   }
10576 
10577   bool isDone() const { return false; }
10578 };
10579 
10580 // Check if a SCEV contains an AddRecExpr.
10581 struct SCEVHasAddRec {
10582   bool &ContainsAddRec;
10583 
10584   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10585     ContainsAddRec = false;
10586   }
10587 
10588   bool follow(const SCEV *S) {
10589     if (isa<SCEVAddRecExpr>(S)) {
10590       ContainsAddRec = true;
10591 
10592       // Stop recursion: once we collected a term, do not walk its operands.
10593       return false;
10594     }
10595 
10596     // Keep looking.
10597     return true;
10598   }
10599 
10600   bool isDone() const { return false; }
10601 };
10602 
10603 // Find factors that are multiplied with an expression that (possibly as a
10604 // subexpression) contains an AddRecExpr. In the expression:
10605 //
10606 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10607 //
10608 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10609 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10610 // parameters as they form a product with an induction variable.
10611 //
10612 // This collector expects all array size parameters to be in the same MulExpr.
10613 // It might be necessary to later add support for collecting parameters that are
10614 // spread over different nested MulExpr.
10615 struct SCEVCollectAddRecMultiplies {
10616   SmallVectorImpl<const SCEV *> &Terms;
10617   ScalarEvolution &SE;
10618 
10619   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10620       : Terms(T), SE(SE) {}
10621 
10622   bool follow(const SCEV *S) {
10623     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10624       bool HasAddRec = false;
10625       SmallVector<const SCEV *, 0> Operands;
10626       for (auto Op : Mul->operands()) {
10627         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10628         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10629           Operands.push_back(Op);
10630         } else if (Unknown) {
10631           HasAddRec = true;
10632         } else {
10633           bool ContainsAddRec;
10634           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10635           visitAll(Op, ContiansAddRec);
10636           HasAddRec |= ContainsAddRec;
10637         }
10638       }
10639       if (Operands.size() == 0)
10640         return true;
10641 
10642       if (!HasAddRec)
10643         return false;
10644 
10645       Terms.push_back(SE.getMulExpr(Operands));
10646       // Stop recursion: once we collected a term, do not walk its operands.
10647       return false;
10648     }
10649 
10650     // Keep looking.
10651     return true;
10652   }
10653 
10654   bool isDone() const { return false; }
10655 };
10656 
10657 } // end anonymous namespace
10658 
10659 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10660 /// two places:
10661 ///   1) The strides of AddRec expressions.
10662 ///   2) Unknowns that are multiplied with AddRec expressions.
10663 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10664     SmallVectorImpl<const SCEV *> &Terms) {
10665   SmallVector<const SCEV *, 4> Strides;
10666   SCEVCollectStrides StrideCollector(*this, Strides);
10667   visitAll(Expr, StrideCollector);
10668 
10669   DEBUG({
10670       dbgs() << "Strides:\n";
10671       for (const SCEV *S : Strides)
10672         dbgs() << *S << "\n";
10673     });
10674 
10675   for (const SCEV *S : Strides) {
10676     SCEVCollectTerms TermCollector(Terms);
10677     visitAll(S, TermCollector);
10678   }
10679 
10680   DEBUG({
10681       dbgs() << "Terms:\n";
10682       for (const SCEV *T : Terms)
10683         dbgs() << *T << "\n";
10684     });
10685 
10686   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10687   visitAll(Expr, MulCollector);
10688 }
10689 
10690 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10691                                    SmallVectorImpl<const SCEV *> &Terms,
10692                                    SmallVectorImpl<const SCEV *> &Sizes) {
10693   int Last = Terms.size() - 1;
10694   const SCEV *Step = Terms[Last];
10695 
10696   // End of recursion.
10697   if (Last == 0) {
10698     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10699       SmallVector<const SCEV *, 2> Qs;
10700       for (const SCEV *Op : M->operands())
10701         if (!isa<SCEVConstant>(Op))
10702           Qs.push_back(Op);
10703 
10704       Step = SE.getMulExpr(Qs);
10705     }
10706 
10707     Sizes.push_back(Step);
10708     return true;
10709   }
10710 
10711   for (const SCEV *&Term : Terms) {
10712     // Normalize the terms before the next call to findArrayDimensionsRec.
10713     const SCEV *Q, *R;
10714     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10715 
10716     // Bail out when GCD does not evenly divide one of the terms.
10717     if (!R->isZero())
10718       return false;
10719 
10720     Term = Q;
10721   }
10722 
10723   // Remove all SCEVConstants.
10724   Terms.erase(
10725       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10726       Terms.end());
10727 
10728   if (Terms.size() > 0)
10729     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10730       return false;
10731 
10732   Sizes.push_back(Step);
10733   return true;
10734 }
10735 
10736 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10737 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10738   for (const SCEV *T : Terms)
10739     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10740       return true;
10741   return false;
10742 }
10743 
10744 // Return the number of product terms in S.
10745 static inline int numberOfTerms(const SCEV *S) {
10746   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10747     return Expr->getNumOperands();
10748   return 1;
10749 }
10750 
10751 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10752   if (isa<SCEVConstant>(T))
10753     return nullptr;
10754 
10755   if (isa<SCEVUnknown>(T))
10756     return T;
10757 
10758   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10759     SmallVector<const SCEV *, 2> Factors;
10760     for (const SCEV *Op : M->operands())
10761       if (!isa<SCEVConstant>(Op))
10762         Factors.push_back(Op);
10763 
10764     return SE.getMulExpr(Factors);
10765   }
10766 
10767   return T;
10768 }
10769 
10770 /// Return the size of an element read or written by Inst.
10771 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10772   Type *Ty;
10773   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10774     Ty = Store->getValueOperand()->getType();
10775   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10776     Ty = Load->getType();
10777   else
10778     return nullptr;
10779 
10780   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10781   return getSizeOfExpr(ETy, Ty);
10782 }
10783 
10784 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10785                                           SmallVectorImpl<const SCEV *> &Sizes,
10786                                           const SCEV *ElementSize) {
10787   if (Terms.size() < 1 || !ElementSize)
10788     return;
10789 
10790   // Early return when Terms do not contain parameters: we do not delinearize
10791   // non parametric SCEVs.
10792   if (!containsParameters(Terms))
10793     return;
10794 
10795   DEBUG({
10796       dbgs() << "Terms:\n";
10797       for (const SCEV *T : Terms)
10798         dbgs() << *T << "\n";
10799     });
10800 
10801   // Remove duplicates.
10802   array_pod_sort(Terms.begin(), Terms.end());
10803   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10804 
10805   // Put larger terms first.
10806   llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10807     return numberOfTerms(LHS) > numberOfTerms(RHS);
10808   });
10809 
10810   // Try to divide all terms by the element size. If term is not divisible by
10811   // element size, proceed with the original term.
10812   for (const SCEV *&Term : Terms) {
10813     const SCEV *Q, *R;
10814     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10815     if (!Q->isZero())
10816       Term = Q;
10817   }
10818 
10819   SmallVector<const SCEV *, 4> NewTerms;
10820 
10821   // Remove constant factors.
10822   for (const SCEV *T : Terms)
10823     if (const SCEV *NewT = removeConstantFactors(*this, T))
10824       NewTerms.push_back(NewT);
10825 
10826   DEBUG({
10827       dbgs() << "Terms after sorting:\n";
10828       for (const SCEV *T : NewTerms)
10829         dbgs() << *T << "\n";
10830     });
10831 
10832   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10833     Sizes.clear();
10834     return;
10835   }
10836 
10837   // The last element to be pushed into Sizes is the size of an element.
10838   Sizes.push_back(ElementSize);
10839 
10840   DEBUG({
10841       dbgs() << "Sizes:\n";
10842       for (const SCEV *S : Sizes)
10843         dbgs() << *S << "\n";
10844     });
10845 }
10846 
10847 void ScalarEvolution::computeAccessFunctions(
10848     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10849     SmallVectorImpl<const SCEV *> &Sizes) {
10850   // Early exit in case this SCEV is not an affine multivariate function.
10851   if (Sizes.empty())
10852     return;
10853 
10854   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10855     if (!AR->isAffine())
10856       return;
10857 
10858   const SCEV *Res = Expr;
10859   int Last = Sizes.size() - 1;
10860   for (int i = Last; i >= 0; i--) {
10861     const SCEV *Q, *R;
10862     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10863 
10864     DEBUG({
10865         dbgs() << "Res: " << *Res << "\n";
10866         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10867         dbgs() << "Res divided by Sizes[i]:\n";
10868         dbgs() << "Quotient: " << *Q << "\n";
10869         dbgs() << "Remainder: " << *R << "\n";
10870       });
10871 
10872     Res = Q;
10873 
10874     // Do not record the last subscript corresponding to the size of elements in
10875     // the array.
10876     if (i == Last) {
10877 
10878       // Bail out if the remainder is too complex.
10879       if (isa<SCEVAddRecExpr>(R)) {
10880         Subscripts.clear();
10881         Sizes.clear();
10882         return;
10883       }
10884 
10885       continue;
10886     }
10887 
10888     // Record the access function for the current subscript.
10889     Subscripts.push_back(R);
10890   }
10891 
10892   // Also push in last position the remainder of the last division: it will be
10893   // the access function of the innermost dimension.
10894   Subscripts.push_back(Res);
10895 
10896   std::reverse(Subscripts.begin(), Subscripts.end());
10897 
10898   DEBUG({
10899       dbgs() << "Subscripts:\n";
10900       for (const SCEV *S : Subscripts)
10901         dbgs() << *S << "\n";
10902     });
10903 }
10904 
10905 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10906 /// sizes of an array access. Returns the remainder of the delinearization that
10907 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10908 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10909 /// expressions in the stride and base of a SCEV corresponding to the
10910 /// computation of a GCD (greatest common divisor) of base and stride.  When
10911 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10912 ///
10913 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10914 ///
10915 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10916 ///
10917 ///    for (long i = 0; i < n; i++)
10918 ///      for (long j = 0; j < m; j++)
10919 ///        for (long k = 0; k < o; k++)
10920 ///          A[i][j][k] = 1.0;
10921 ///  }
10922 ///
10923 /// the delinearization input is the following AddRec SCEV:
10924 ///
10925 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10926 ///
10927 /// From this SCEV, we are able to say that the base offset of the access is %A
10928 /// because it appears as an offset that does not divide any of the strides in
10929 /// the loops:
10930 ///
10931 ///  CHECK: Base offset: %A
10932 ///
10933 /// and then SCEV->delinearize determines the size of some of the dimensions of
10934 /// the array as these are the multiples by which the strides are happening:
10935 ///
10936 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10937 ///
10938 /// Note that the outermost dimension remains of UnknownSize because there are
10939 /// no strides that would help identifying the size of the last dimension: when
10940 /// the array has been statically allocated, one could compute the size of that
10941 /// dimension by dividing the overall size of the array by the size of the known
10942 /// dimensions: %m * %o * 8.
10943 ///
10944 /// Finally delinearize provides the access functions for the array reference
10945 /// that does correspond to A[i][j][k] of the above C testcase:
10946 ///
10947 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10948 ///
10949 /// The testcases are checking the output of a function pass:
10950 /// DelinearizationPass that walks through all loads and stores of a function
10951 /// asking for the SCEV of the memory access with respect to all enclosing
10952 /// loops, calling SCEV->delinearize on that and printing the results.
10953 void ScalarEvolution::delinearize(const SCEV *Expr,
10954                                  SmallVectorImpl<const SCEV *> &Subscripts,
10955                                  SmallVectorImpl<const SCEV *> &Sizes,
10956                                  const SCEV *ElementSize) {
10957   // First step: collect parametric terms.
10958   SmallVector<const SCEV *, 4> Terms;
10959   collectParametricTerms(Expr, Terms);
10960 
10961   if (Terms.empty())
10962     return;
10963 
10964   // Second step: find subscript sizes.
10965   findArrayDimensions(Terms, Sizes, ElementSize);
10966 
10967   if (Sizes.empty())
10968     return;
10969 
10970   // Third step: compute the access functions for each subscript.
10971   computeAccessFunctions(Expr, Subscripts, Sizes);
10972 
10973   if (Subscripts.empty())
10974     return;
10975 
10976   DEBUG({
10977       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10978       dbgs() << "ArrayDecl[UnknownSize]";
10979       for (const SCEV *S : Sizes)
10980         dbgs() << "[" << *S << "]";
10981 
10982       dbgs() << "\nArrayRef";
10983       for (const SCEV *S : Subscripts)
10984         dbgs() << "[" << *S << "]";
10985       dbgs() << "\n";
10986     });
10987 }
10988 
10989 //===----------------------------------------------------------------------===//
10990 //                   SCEVCallbackVH Class Implementation
10991 //===----------------------------------------------------------------------===//
10992 
10993 void ScalarEvolution::SCEVCallbackVH::deleted() {
10994   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10995   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10996     SE->ConstantEvolutionLoopExitValue.erase(PN);
10997   SE->eraseValueFromMap(getValPtr());
10998   // this now dangles!
10999 }
11000 
11001 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11002   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11003 
11004   // Forget all the expressions associated with users of the old value,
11005   // so that future queries will recompute the expressions using the new
11006   // value.
11007   Value *Old = getValPtr();
11008   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11009   SmallPtrSet<User *, 8> Visited;
11010   while (!Worklist.empty()) {
11011     User *U = Worklist.pop_back_val();
11012     // Deleting the Old value will cause this to dangle. Postpone
11013     // that until everything else is done.
11014     if (U == Old)
11015       continue;
11016     if (!Visited.insert(U).second)
11017       continue;
11018     if (PHINode *PN = dyn_cast<PHINode>(U))
11019       SE->ConstantEvolutionLoopExitValue.erase(PN);
11020     SE->eraseValueFromMap(U);
11021     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11022   }
11023   // Delete the Old value.
11024   if (PHINode *PN = dyn_cast<PHINode>(Old))
11025     SE->ConstantEvolutionLoopExitValue.erase(PN);
11026   SE->eraseValueFromMap(Old);
11027   // this now dangles!
11028 }
11029 
11030 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11031   : CallbackVH(V), SE(se) {}
11032 
11033 //===----------------------------------------------------------------------===//
11034 //                   ScalarEvolution Class Implementation
11035 //===----------------------------------------------------------------------===//
11036 
11037 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11038                                  AssumptionCache &AC, DominatorTree &DT,
11039                                  LoopInfo &LI)
11040     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11041       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11042       LoopDispositions(64), BlockDispositions(64) {
11043   // To use guards for proving predicates, we need to scan every instruction in
11044   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11045   // time if the IR does not actually contain any calls to
11046   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11047   //
11048   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11049   // to _add_ guards to the module when there weren't any before, and wants
11050   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11051   // efficient in lieu of being smart in that rather obscure case.
11052 
11053   auto *GuardDecl = F.getParent()->getFunction(
11054       Intrinsic::getName(Intrinsic::experimental_guard));
11055   HasGuards = GuardDecl && !GuardDecl->use_empty();
11056 }
11057 
11058 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11059     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11060       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11061       ValueExprMap(std::move(Arg.ValueExprMap)),
11062       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11063       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11064       PendingMerges(std::move(Arg.PendingMerges)),
11065       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11066       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11067       PredicatedBackedgeTakenCounts(
11068           std::move(Arg.PredicatedBackedgeTakenCounts)),
11069       ConstantEvolutionLoopExitValue(
11070           std::move(Arg.ConstantEvolutionLoopExitValue)),
11071       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11072       LoopDispositions(std::move(Arg.LoopDispositions)),
11073       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11074       BlockDispositions(std::move(Arg.BlockDispositions)),
11075       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11076       SignedRanges(std::move(Arg.SignedRanges)),
11077       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11078       UniquePreds(std::move(Arg.UniquePreds)),
11079       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11080       LoopUsers(std::move(Arg.LoopUsers)),
11081       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11082       FirstUnknown(Arg.FirstUnknown) {
11083   Arg.FirstUnknown = nullptr;
11084 }
11085 
11086 ScalarEvolution::~ScalarEvolution() {
11087   // Iterate through all the SCEVUnknown instances and call their
11088   // destructors, so that they release their references to their values.
11089   for (SCEVUnknown *U = FirstUnknown; U;) {
11090     SCEVUnknown *Tmp = U;
11091     U = U->Next;
11092     Tmp->~SCEVUnknown();
11093   }
11094   FirstUnknown = nullptr;
11095 
11096   ExprValueMap.clear();
11097   ValueExprMap.clear();
11098   HasRecMap.clear();
11099 
11100   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11101   // that a loop had multiple computable exits.
11102   for (auto &BTCI : BackedgeTakenCounts)
11103     BTCI.second.clear();
11104   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11105     BTCI.second.clear();
11106 
11107   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11108   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11109   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11110   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11111   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11112 }
11113 
11114 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11115   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11116 }
11117 
11118 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11119                           const Loop *L) {
11120   // Print all inner loops first
11121   for (Loop *I : *L)
11122     PrintLoopInfo(OS, SE, I);
11123 
11124   OS << "Loop ";
11125   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11126   OS << ": ";
11127 
11128   SmallVector<BasicBlock *, 8> ExitBlocks;
11129   L->getExitBlocks(ExitBlocks);
11130   if (ExitBlocks.size() != 1)
11131     OS << "<multiple exits> ";
11132 
11133   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11134     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
11135   } else {
11136     OS << "Unpredictable backedge-taken count. ";
11137   }
11138 
11139   OS << "\n"
11140         "Loop ";
11141   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11142   OS << ": ";
11143 
11144   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
11145     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
11146     if (SE->isBackedgeTakenCountMaxOrZero(L))
11147       OS << ", actual taken count either this or zero.";
11148   } else {
11149     OS << "Unpredictable max backedge-taken count. ";
11150   }
11151 
11152   OS << "\n"
11153         "Loop ";
11154   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11155   OS << ": ";
11156 
11157   SCEVUnionPredicate Pred;
11158   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11159   if (!isa<SCEVCouldNotCompute>(PBT)) {
11160     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11161     OS << " Predicates:\n";
11162     Pred.print(OS, 4);
11163   } else {
11164     OS << "Unpredictable predicated backedge-taken count. ";
11165   }
11166   OS << "\n";
11167 
11168   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11169     OS << "Loop ";
11170     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11171     OS << ": ";
11172     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11173   }
11174 }
11175 
11176 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11177   switch (LD) {
11178   case ScalarEvolution::LoopVariant:
11179     return "Variant";
11180   case ScalarEvolution::LoopInvariant:
11181     return "Invariant";
11182   case ScalarEvolution::LoopComputable:
11183     return "Computable";
11184   }
11185   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11186 }
11187 
11188 void ScalarEvolution::print(raw_ostream &OS) const {
11189   // ScalarEvolution's implementation of the print method is to print
11190   // out SCEV values of all instructions that are interesting. Doing
11191   // this potentially causes it to create new SCEV objects though,
11192   // which technically conflicts with the const qualifier. This isn't
11193   // observable from outside the class though, so casting away the
11194   // const isn't dangerous.
11195   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11196 
11197   OS << "Classifying expressions for: ";
11198   F.printAsOperand(OS, /*PrintType=*/false);
11199   OS << "\n";
11200   for (Instruction &I : instructions(F))
11201     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11202       OS << I << '\n';
11203       OS << "  -->  ";
11204       const SCEV *SV = SE.getSCEV(&I);
11205       SV->print(OS);
11206       if (!isa<SCEVCouldNotCompute>(SV)) {
11207         OS << " U: ";
11208         SE.getUnsignedRange(SV).print(OS);
11209         OS << " S: ";
11210         SE.getSignedRange(SV).print(OS);
11211       }
11212 
11213       const Loop *L = LI.getLoopFor(I.getParent());
11214 
11215       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11216       if (AtUse != SV) {
11217         OS << "  -->  ";
11218         AtUse->print(OS);
11219         if (!isa<SCEVCouldNotCompute>(AtUse)) {
11220           OS << " U: ";
11221           SE.getUnsignedRange(AtUse).print(OS);
11222           OS << " S: ";
11223           SE.getSignedRange(AtUse).print(OS);
11224         }
11225       }
11226 
11227       if (L) {
11228         OS << "\t\t" "Exits: ";
11229         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11230         if (!SE.isLoopInvariant(ExitValue, L)) {
11231           OS << "<<Unknown>>";
11232         } else {
11233           OS << *ExitValue;
11234         }
11235 
11236         bool First = true;
11237         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11238           if (First) {
11239             OS << "\t\t" "LoopDispositions: { ";
11240             First = false;
11241           } else {
11242             OS << ", ";
11243           }
11244 
11245           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11246           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11247         }
11248 
11249         for (auto *InnerL : depth_first(L)) {
11250           if (InnerL == L)
11251             continue;
11252           if (First) {
11253             OS << "\t\t" "LoopDispositions: { ";
11254             First = false;
11255           } else {
11256             OS << ", ";
11257           }
11258 
11259           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11260           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11261         }
11262 
11263         OS << " }";
11264       }
11265 
11266       OS << "\n";
11267     }
11268 
11269   OS << "Determining loop execution counts for: ";
11270   F.printAsOperand(OS, /*PrintType=*/false);
11271   OS << "\n";
11272   for (Loop *I : LI)
11273     PrintLoopInfo(OS, &SE, I);
11274 }
11275 
11276 ScalarEvolution::LoopDisposition
11277 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11278   auto &Values = LoopDispositions[S];
11279   for (auto &V : Values) {
11280     if (V.getPointer() == L)
11281       return V.getInt();
11282   }
11283   Values.emplace_back(L, LoopVariant);
11284   LoopDisposition D = computeLoopDisposition(S, L);
11285   auto &Values2 = LoopDispositions[S];
11286   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11287     if (V.getPointer() == L) {
11288       V.setInt(D);
11289       break;
11290     }
11291   }
11292   return D;
11293 }
11294 
11295 ScalarEvolution::LoopDisposition
11296 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11297   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11298   case scConstant:
11299     return LoopInvariant;
11300   case scTruncate:
11301   case scZeroExtend:
11302   case scSignExtend:
11303     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11304   case scAddRecExpr: {
11305     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11306 
11307     // If L is the addrec's loop, it's computable.
11308     if (AR->getLoop() == L)
11309       return LoopComputable;
11310 
11311     // Add recurrences are never invariant in the function-body (null loop).
11312     if (!L)
11313       return LoopVariant;
11314 
11315     // Everything that is not defined at loop entry is variant.
11316     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11317       return LoopVariant;
11318     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11319            " dominate the contained loop's header?");
11320 
11321     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11322     if (AR->getLoop()->contains(L))
11323       return LoopInvariant;
11324 
11325     // This recurrence is variant w.r.t. L if any of its operands
11326     // are variant.
11327     for (auto *Op : AR->operands())
11328       if (!isLoopInvariant(Op, L))
11329         return LoopVariant;
11330 
11331     // Otherwise it's loop-invariant.
11332     return LoopInvariant;
11333   }
11334   case scAddExpr:
11335   case scMulExpr:
11336   case scUMaxExpr:
11337   case scSMaxExpr: {
11338     bool HasVarying = false;
11339     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11340       LoopDisposition D = getLoopDisposition(Op, L);
11341       if (D == LoopVariant)
11342         return LoopVariant;
11343       if (D == LoopComputable)
11344         HasVarying = true;
11345     }
11346     return HasVarying ? LoopComputable : LoopInvariant;
11347   }
11348   case scUDivExpr: {
11349     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11350     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11351     if (LD == LoopVariant)
11352       return LoopVariant;
11353     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11354     if (RD == LoopVariant)
11355       return LoopVariant;
11356     return (LD == LoopInvariant && RD == LoopInvariant) ?
11357            LoopInvariant : LoopComputable;
11358   }
11359   case scUnknown:
11360     // All non-instruction values are loop invariant.  All instructions are loop
11361     // invariant if they are not contained in the specified loop.
11362     // Instructions are never considered invariant in the function body
11363     // (null loop) because they are defined within the "loop".
11364     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11365       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11366     return LoopInvariant;
11367   case scCouldNotCompute:
11368     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11369   }
11370   llvm_unreachable("Unknown SCEV kind!");
11371 }
11372 
11373 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11374   return getLoopDisposition(S, L) == LoopInvariant;
11375 }
11376 
11377 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11378   return getLoopDisposition(S, L) == LoopComputable;
11379 }
11380 
11381 ScalarEvolution::BlockDisposition
11382 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11383   auto &Values = BlockDispositions[S];
11384   for (auto &V : Values) {
11385     if (V.getPointer() == BB)
11386       return V.getInt();
11387   }
11388   Values.emplace_back(BB, DoesNotDominateBlock);
11389   BlockDisposition D = computeBlockDisposition(S, BB);
11390   auto &Values2 = BlockDispositions[S];
11391   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11392     if (V.getPointer() == BB) {
11393       V.setInt(D);
11394       break;
11395     }
11396   }
11397   return D;
11398 }
11399 
11400 ScalarEvolution::BlockDisposition
11401 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11402   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11403   case scConstant:
11404     return ProperlyDominatesBlock;
11405   case scTruncate:
11406   case scZeroExtend:
11407   case scSignExtend:
11408     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11409   case scAddRecExpr: {
11410     // This uses a "dominates" query instead of "properly dominates" query
11411     // to test for proper dominance too, because the instruction which
11412     // produces the addrec's value is a PHI, and a PHI effectively properly
11413     // dominates its entire containing block.
11414     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11415     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11416       return DoesNotDominateBlock;
11417 
11418     // Fall through into SCEVNAryExpr handling.
11419     LLVM_FALLTHROUGH;
11420   }
11421   case scAddExpr:
11422   case scMulExpr:
11423   case scUMaxExpr:
11424   case scSMaxExpr: {
11425     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11426     bool Proper = true;
11427     for (const SCEV *NAryOp : NAry->operands()) {
11428       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11429       if (D == DoesNotDominateBlock)
11430         return DoesNotDominateBlock;
11431       if (D == DominatesBlock)
11432         Proper = false;
11433     }
11434     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11435   }
11436   case scUDivExpr: {
11437     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11438     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11439     BlockDisposition LD = getBlockDisposition(LHS, BB);
11440     if (LD == DoesNotDominateBlock)
11441       return DoesNotDominateBlock;
11442     BlockDisposition RD = getBlockDisposition(RHS, BB);
11443     if (RD == DoesNotDominateBlock)
11444       return DoesNotDominateBlock;
11445     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11446       ProperlyDominatesBlock : DominatesBlock;
11447   }
11448   case scUnknown:
11449     if (Instruction *I =
11450           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11451       if (I->getParent() == BB)
11452         return DominatesBlock;
11453       if (DT.properlyDominates(I->getParent(), BB))
11454         return ProperlyDominatesBlock;
11455       return DoesNotDominateBlock;
11456     }
11457     return ProperlyDominatesBlock;
11458   case scCouldNotCompute:
11459     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11460   }
11461   llvm_unreachable("Unknown SCEV kind!");
11462 }
11463 
11464 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11465   return getBlockDisposition(S, BB) >= DominatesBlock;
11466 }
11467 
11468 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11469   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11470 }
11471 
11472 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11473   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11474 }
11475 
11476 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11477   auto IsS = [&](const SCEV *X) { return S == X; };
11478   auto ContainsS = [&](const SCEV *X) {
11479     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11480   };
11481   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11482 }
11483 
11484 void
11485 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11486   ValuesAtScopes.erase(S);
11487   LoopDispositions.erase(S);
11488   BlockDispositions.erase(S);
11489   UnsignedRanges.erase(S);
11490   SignedRanges.erase(S);
11491   ExprValueMap.erase(S);
11492   HasRecMap.erase(S);
11493   MinTrailingZerosCache.erase(S);
11494 
11495   for (auto I = PredicatedSCEVRewrites.begin();
11496        I != PredicatedSCEVRewrites.end();) {
11497     std::pair<const SCEV *, const Loop *> Entry = I->first;
11498     if (Entry.first == S)
11499       PredicatedSCEVRewrites.erase(I++);
11500     else
11501       ++I;
11502   }
11503 
11504   auto RemoveSCEVFromBackedgeMap =
11505       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11506         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11507           BackedgeTakenInfo &BEInfo = I->second;
11508           if (BEInfo.hasOperand(S, this)) {
11509             BEInfo.clear();
11510             Map.erase(I++);
11511           } else
11512             ++I;
11513         }
11514       };
11515 
11516   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11517   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11518 }
11519 
11520 void
11521 ScalarEvolution::getUsedLoops(const SCEV *S,
11522                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11523   struct FindUsedLoops {
11524     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11525         : LoopsUsed(LoopsUsed) {}
11526     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11527     bool follow(const SCEV *S) {
11528       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11529         LoopsUsed.insert(AR->getLoop());
11530       return true;
11531     }
11532 
11533     bool isDone() const { return false; }
11534   };
11535 
11536   FindUsedLoops F(LoopsUsed);
11537   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11538 }
11539 
11540 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11541   SmallPtrSet<const Loop *, 8> LoopsUsed;
11542   getUsedLoops(S, LoopsUsed);
11543   for (auto *L : LoopsUsed)
11544     LoopUsers[L].push_back(S);
11545 }
11546 
11547 void ScalarEvolution::verify() const {
11548   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11549   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11550 
11551   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11552 
11553   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11554   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11555     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11556 
11557     const SCEV *visitConstant(const SCEVConstant *Constant) {
11558       return SE.getConstant(Constant->getAPInt());
11559     }
11560 
11561     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11562       return SE.getUnknown(Expr->getValue());
11563     }
11564 
11565     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11566       return SE.getCouldNotCompute();
11567     }
11568   };
11569 
11570   SCEVMapper SCM(SE2);
11571 
11572   while (!LoopStack.empty()) {
11573     auto *L = LoopStack.pop_back_val();
11574     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11575 
11576     auto *CurBECount = SCM.visit(
11577         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11578     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11579 
11580     if (CurBECount == SE2.getCouldNotCompute() ||
11581         NewBECount == SE2.getCouldNotCompute()) {
11582       // NB! This situation is legal, but is very suspicious -- whatever pass
11583       // change the loop to make a trip count go from could not compute to
11584       // computable or vice-versa *should have* invalidated SCEV.  However, we
11585       // choose not to assert here (for now) since we don't want false
11586       // positives.
11587       continue;
11588     }
11589 
11590     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11591       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11592       // not propagate undef aggressively).  This means we can (and do) fail
11593       // verification in cases where a transform makes the trip count of a loop
11594       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11595       // both cases the loop iterates "undef" times, but SCEV thinks we
11596       // increased the trip count of the loop by 1 incorrectly.
11597       continue;
11598     }
11599 
11600     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11601         SE.getTypeSizeInBits(NewBECount->getType()))
11602       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11603     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11604              SE.getTypeSizeInBits(NewBECount->getType()))
11605       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11606 
11607     auto *ConstantDelta =
11608         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11609 
11610     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11611       dbgs() << "Trip Count Changed!\n";
11612       dbgs() << "Old: " << *CurBECount << "\n";
11613       dbgs() << "New: " << *NewBECount << "\n";
11614       dbgs() << "Delta: " << *ConstantDelta << "\n";
11615       std::abort();
11616     }
11617   }
11618 }
11619 
11620 bool ScalarEvolution::invalidate(
11621     Function &F, const PreservedAnalyses &PA,
11622     FunctionAnalysisManager::Invalidator &Inv) {
11623   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11624   // of its dependencies is invalidated.
11625   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11626   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11627          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11628          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11629          Inv.invalidate<LoopAnalysis>(F, PA);
11630 }
11631 
11632 AnalysisKey ScalarEvolutionAnalysis::Key;
11633 
11634 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11635                                              FunctionAnalysisManager &AM) {
11636   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11637                          AM.getResult<AssumptionAnalysis>(F),
11638                          AM.getResult<DominatorTreeAnalysis>(F),
11639                          AM.getResult<LoopAnalysis>(F));
11640 }
11641 
11642 PreservedAnalyses
11643 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11644   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11645   return PreservedAnalyses::all();
11646 }
11647 
11648 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11649                       "Scalar Evolution Analysis", false, true)
11650 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11651 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11652 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11653 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11654 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11655                     "Scalar Evolution Analysis", false, true)
11656 
11657 char ScalarEvolutionWrapperPass::ID = 0;
11658 
11659 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11660   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11661 }
11662 
11663 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11664   SE.reset(new ScalarEvolution(
11665       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11666       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11667       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11668       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11669   return false;
11670 }
11671 
11672 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11673 
11674 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11675   SE->print(OS);
11676 }
11677 
11678 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11679   if (!VerifySCEV)
11680     return;
11681 
11682   SE->verify();
11683 }
11684 
11685 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11686   AU.setPreservesAll();
11687   AU.addRequiredTransitive<AssumptionCacheTracker>();
11688   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11689   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11690   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11691 }
11692 
11693 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11694                                                         const SCEV *RHS) {
11695   FoldingSetNodeID ID;
11696   assert(LHS->getType() == RHS->getType() &&
11697          "Type mismatch between LHS and RHS");
11698   // Unique this node based on the arguments
11699   ID.AddInteger(SCEVPredicate::P_Equal);
11700   ID.AddPointer(LHS);
11701   ID.AddPointer(RHS);
11702   void *IP = nullptr;
11703   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11704     return S;
11705   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11706       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11707   UniquePreds.InsertNode(Eq, IP);
11708   return Eq;
11709 }
11710 
11711 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11712     const SCEVAddRecExpr *AR,
11713     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11714   FoldingSetNodeID ID;
11715   // Unique this node based on the arguments
11716   ID.AddInteger(SCEVPredicate::P_Wrap);
11717   ID.AddPointer(AR);
11718   ID.AddInteger(AddedFlags);
11719   void *IP = nullptr;
11720   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11721     return S;
11722   auto *OF = new (SCEVAllocator)
11723       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11724   UniquePreds.InsertNode(OF, IP);
11725   return OF;
11726 }
11727 
11728 namespace {
11729 
11730 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11731 public:
11732 
11733   /// Rewrites \p S in the context of a loop L and the SCEV predication
11734   /// infrastructure.
11735   ///
11736   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11737   /// equivalences present in \p Pred.
11738   ///
11739   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11740   /// \p NewPreds such that the result will be an AddRecExpr.
11741   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11742                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11743                              SCEVUnionPredicate *Pred) {
11744     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11745     return Rewriter.visit(S);
11746   }
11747 
11748   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11749     if (Pred) {
11750       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11751       for (auto *Pred : ExprPreds)
11752         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11753           if (IPred->getLHS() == Expr)
11754             return IPred->getRHS();
11755     }
11756     return convertToAddRecWithPreds(Expr);
11757   }
11758 
11759   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11760     const SCEV *Operand = visit(Expr->getOperand());
11761     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11762     if (AR && AR->getLoop() == L && AR->isAffine()) {
11763       // This couldn't be folded because the operand didn't have the nuw
11764       // flag. Add the nusw flag as an assumption that we could make.
11765       const SCEV *Step = AR->getStepRecurrence(SE);
11766       Type *Ty = Expr->getType();
11767       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11768         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11769                                 SE.getSignExtendExpr(Step, Ty), L,
11770                                 AR->getNoWrapFlags());
11771     }
11772     return SE.getZeroExtendExpr(Operand, Expr->getType());
11773   }
11774 
11775   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11776     const SCEV *Operand = visit(Expr->getOperand());
11777     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11778     if (AR && AR->getLoop() == L && AR->isAffine()) {
11779       // This couldn't be folded because the operand didn't have the nsw
11780       // flag. Add the nssw flag as an assumption that we could make.
11781       const SCEV *Step = AR->getStepRecurrence(SE);
11782       Type *Ty = Expr->getType();
11783       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11784         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11785                                 SE.getSignExtendExpr(Step, Ty), L,
11786                                 AR->getNoWrapFlags());
11787     }
11788     return SE.getSignExtendExpr(Operand, Expr->getType());
11789   }
11790 
11791 private:
11792   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11793                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11794                         SCEVUnionPredicate *Pred)
11795       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11796 
11797   bool addOverflowAssumption(const SCEVPredicate *P) {
11798     if (!NewPreds) {
11799       // Check if we've already made this assumption.
11800       return Pred && Pred->implies(P);
11801     }
11802     NewPreds->insert(P);
11803     return true;
11804   }
11805 
11806   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11807                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11808     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11809     return addOverflowAssumption(A);
11810   }
11811 
11812   // If \p Expr represents a PHINode, we try to see if it can be represented
11813   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11814   // to add this predicate as a runtime overflow check, we return the AddRec.
11815   // If \p Expr does not meet these conditions (is not a PHI node, or we
11816   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11817   // return \p Expr.
11818   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11819     if (!isa<PHINode>(Expr->getValue()))
11820       return Expr;
11821     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11822     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11823     if (!PredicatedRewrite)
11824       return Expr;
11825     for (auto *P : PredicatedRewrite->second){
11826       // Wrap predicates from outer loops are not supported.
11827       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
11828         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
11829         if (L != AR->getLoop())
11830           return Expr;
11831       }
11832       if (!addOverflowAssumption(P))
11833         return Expr;
11834     }
11835     return PredicatedRewrite->first;
11836   }
11837 
11838   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11839   SCEVUnionPredicate *Pred;
11840   const Loop *L;
11841 };
11842 
11843 } // end anonymous namespace
11844 
11845 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11846                                                    SCEVUnionPredicate &Preds) {
11847   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11848 }
11849 
11850 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11851     const SCEV *S, const Loop *L,
11852     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11853   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11854   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11855   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11856 
11857   if (!AddRec)
11858     return nullptr;
11859 
11860   // Since the transformation was successful, we can now transfer the SCEV
11861   // predicates.
11862   for (auto *P : TransformPreds)
11863     Preds.insert(P);
11864 
11865   return AddRec;
11866 }
11867 
11868 /// SCEV predicates
11869 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11870                              SCEVPredicateKind Kind)
11871     : FastID(ID), Kind(Kind) {}
11872 
11873 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11874                                        const SCEV *LHS, const SCEV *RHS)
11875     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11876   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11877   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11878 }
11879 
11880 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11881   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11882 
11883   if (!Op)
11884     return false;
11885 
11886   return Op->LHS == LHS && Op->RHS == RHS;
11887 }
11888 
11889 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11890 
11891 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11892 
11893 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11894   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11895 }
11896 
11897 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11898                                      const SCEVAddRecExpr *AR,
11899                                      IncrementWrapFlags Flags)
11900     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11901 
11902 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11903 
11904 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11905   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11906 
11907   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11908 }
11909 
11910 bool SCEVWrapPredicate::isAlwaysTrue() const {
11911   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11912   IncrementWrapFlags IFlags = Flags;
11913 
11914   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11915     IFlags = clearFlags(IFlags, IncrementNSSW);
11916 
11917   return IFlags == IncrementAnyWrap;
11918 }
11919 
11920 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11921   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11922   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11923     OS << "<nusw>";
11924   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11925     OS << "<nssw>";
11926   OS << "\n";
11927 }
11928 
11929 SCEVWrapPredicate::IncrementWrapFlags
11930 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11931                                    ScalarEvolution &SE) {
11932   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11933   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11934 
11935   // We can safely transfer the NSW flag as NSSW.
11936   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11937     ImpliedFlags = IncrementNSSW;
11938 
11939   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11940     // If the increment is positive, the SCEV NUW flag will also imply the
11941     // WrapPredicate NUSW flag.
11942     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11943       if (Step->getValue()->getValue().isNonNegative())
11944         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11945   }
11946 
11947   return ImpliedFlags;
11948 }
11949 
11950 /// Union predicates don't get cached so create a dummy set ID for it.
11951 SCEVUnionPredicate::SCEVUnionPredicate()
11952     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11953 
11954 bool SCEVUnionPredicate::isAlwaysTrue() const {
11955   return all_of(Preds,
11956                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11957 }
11958 
11959 ArrayRef<const SCEVPredicate *>
11960 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11961   auto I = SCEVToPreds.find(Expr);
11962   if (I == SCEVToPreds.end())
11963     return ArrayRef<const SCEVPredicate *>();
11964   return I->second;
11965 }
11966 
11967 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11968   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11969     return all_of(Set->Preds,
11970                   [this](const SCEVPredicate *I) { return this->implies(I); });
11971 
11972   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11973   if (ScevPredsIt == SCEVToPreds.end())
11974     return false;
11975   auto &SCEVPreds = ScevPredsIt->second;
11976 
11977   return any_of(SCEVPreds,
11978                 [N](const SCEVPredicate *I) { return I->implies(N); });
11979 }
11980 
11981 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11982 
11983 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11984   for (auto Pred : Preds)
11985     Pred->print(OS, Depth);
11986 }
11987 
11988 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11989   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11990     for (auto Pred : Set->Preds)
11991       add(Pred);
11992     return;
11993   }
11994 
11995   if (implies(N))
11996     return;
11997 
11998   const SCEV *Key = N->getExpr();
11999   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12000                 " associated expression!");
12001 
12002   SCEVToPreds[Key].push_back(N);
12003   Preds.push_back(N);
12004 }
12005 
12006 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12007                                                      Loop &L)
12008     : SE(SE), L(L) {}
12009 
12010 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12011   const SCEV *Expr = SE.getSCEV(V);
12012   RewriteEntry &Entry = RewriteMap[Expr];
12013 
12014   // If we already have an entry and the version matches, return it.
12015   if (Entry.second && Generation == Entry.first)
12016     return Entry.second;
12017 
12018   // We found an entry but it's stale. Rewrite the stale entry
12019   // according to the current predicate.
12020   if (Entry.second)
12021     Expr = Entry.second;
12022 
12023   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12024   Entry = {Generation, NewSCEV};
12025 
12026   return NewSCEV;
12027 }
12028 
12029 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12030   if (!BackedgeCount) {
12031     SCEVUnionPredicate BackedgePred;
12032     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12033     addPredicate(BackedgePred);
12034   }
12035   return BackedgeCount;
12036 }
12037 
12038 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12039   if (Preds.implies(&Pred))
12040     return;
12041   Preds.add(&Pred);
12042   updateGeneration();
12043 }
12044 
12045 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12046   return Preds;
12047 }
12048 
12049 void PredicatedScalarEvolution::updateGeneration() {
12050   // If the generation number wrapped recompute everything.
12051   if (++Generation == 0) {
12052     for (auto &II : RewriteMap) {
12053       const SCEV *Rewritten = II.second.second;
12054       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12055     }
12056   }
12057 }
12058 
12059 void PredicatedScalarEvolution::setNoOverflow(
12060     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12061   const SCEV *Expr = getSCEV(V);
12062   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12063 
12064   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12065 
12066   // Clear the statically implied flags.
12067   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12068   addPredicate(*SE.getWrapPredicate(AR, Flags));
12069 
12070   auto II = FlagsMap.insert({V, Flags});
12071   if (!II.second)
12072     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12073 }
12074 
12075 bool PredicatedScalarEvolution::hasNoOverflow(
12076     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12077   const SCEV *Expr = getSCEV(V);
12078   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12079 
12080   Flags = SCEVWrapPredicate::clearFlags(
12081       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12082 
12083   auto II = FlagsMap.find(V);
12084 
12085   if (II != FlagsMap.end())
12086     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12087 
12088   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12089 }
12090 
12091 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12092   const SCEV *Expr = this->getSCEV(V);
12093   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12094   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12095 
12096   if (!New)
12097     return nullptr;
12098 
12099   for (auto *P : NewPreds)
12100     Preds.add(P);
12101 
12102   updateGeneration();
12103   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12104   return New;
12105 }
12106 
12107 PredicatedScalarEvolution::PredicatedScalarEvolution(
12108     const PredicatedScalarEvolution &Init)
12109     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12110       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12111   for (const auto &I : Init.FlagsMap)
12112     FlagsMap.insert(I);
12113 }
12114 
12115 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12116   // For each block.
12117   for (auto *BB : L.getBlocks())
12118     for (auto &I : *BB) {
12119       if (!SE.isSCEVable(I.getType()))
12120         continue;
12121 
12122       auto *Expr = SE.getSCEV(&I);
12123       auto II = RewriteMap.find(Expr);
12124 
12125       if (II == RewriteMap.end())
12126         continue;
12127 
12128       // Don't print things that are not interesting.
12129       if (II->second.second == Expr)
12130         continue;
12131 
12132       OS.indent(Depth) << "[PSE]" << I << ":\n";
12133       OS.indent(Depth + 2) << *Expr << "\n";
12134       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12135     }
12136 }
12137