xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 6cb702d00dbec2bc2f58870d3ee40c8564d89832)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/EquivalenceClasses.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/ConstantFolding.h"
81 #include "llvm/Analysis/InstructionSimplify.h"
82 #include "llvm/Analysis/LoopInfo.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/CallSite.h"
91 #include "llvm/IR/Constant.h"
92 #include "llvm/IR/ConstantRange.h"
93 #include "llvm/IR/Constants.h"
94 #include "llvm/IR/DataLayout.h"
95 #include "llvm/IR/DerivedTypes.h"
96 #include "llvm/IR/Dominators.h"
97 #include "llvm/IR/Function.h"
98 #include "llvm/IR/GlobalAlias.h"
99 #include "llvm/IR/GlobalValue.h"
100 #include "llvm/IR/GlobalVariable.h"
101 #include "llvm/IR/InstIterator.h"
102 #include "llvm/IR/InstrTypes.h"
103 #include "llvm/IR/Instruction.h"
104 #include "llvm/IR/Instructions.h"
105 #include "llvm/IR/IntrinsicInst.h"
106 #include "llvm/IR/Intrinsics.h"
107 #include "llvm/IR/LLVMContext.h"
108 #include "llvm/IR/Metadata.h"
109 #include "llvm/IR/Operator.h"
110 #include "llvm/IR/PatternMatch.h"
111 #include "llvm/IR/Type.h"
112 #include "llvm/IR/Use.h"
113 #include "llvm/IR/User.h"
114 #include "llvm/IR/Value.h"
115 #include "llvm/Pass.h"
116 #include "llvm/Support/Casting.h"
117 #include "llvm/Support/CommandLine.h"
118 #include "llvm/Support/Compiler.h"
119 #include "llvm/Support/Debug.h"
120 #include "llvm/Support/ErrorHandling.h"
121 #include "llvm/Support/KnownBits.h"
122 #include "llvm/Support/SaveAndRestore.h"
123 #include "llvm/Support/raw_ostream.h"
124 #include <algorithm>
125 #include <cassert>
126 #include <climits>
127 #include <cstddef>
128 #include <cstdint>
129 #include <cstdlib>
130 #include <map>
131 #include <memory>
132 #include <tuple>
133 #include <utility>
134 #include <vector>
135 
136 using namespace llvm;
137 
138 #define DEBUG_TYPE "scalar-evolution"
139 
140 STATISTIC(NumArrayLenItCounts,
141           "Number of trip counts computed with array length");
142 STATISTIC(NumTripCountsComputed,
143           "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed,
145           "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147           "Number of loops with trip counts computed by force");
148 
149 static cl::opt<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151                         cl::desc("Maximum number of iterations SCEV will "
152                                  "symbolically execute a constant "
153                                  "derived loop"),
154                         cl::init(100));
155 
156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157 static cl::opt<bool> VerifySCEV(
158     "verify-scev", cl::Hidden,
159     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160 static cl::opt<bool>
161     VerifySCEVMap("verify-scev-maps", cl::Hidden,
162                   cl::desc("Verify no dangling value in ScalarEvolution's "
163                            "ExprValueMap (slow)"));
164 
165 static cl::opt<unsigned> MulOpsInlineThreshold(
166     "scev-mulops-inline-threshold", cl::Hidden,
167     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
168     cl::init(32));
169 
170 static cl::opt<unsigned> AddOpsInlineThreshold(
171     "scev-addops-inline-threshold", cl::Hidden,
172     cl::desc("Threshold for inlining addition operands into a SCEV"),
173     cl::init(500));
174 
175 static cl::opt<unsigned> MaxSCEVCompareDepth(
176     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
177     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
181     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
182     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
183     cl::init(2));
184 
185 static cl::opt<unsigned> MaxValueCompareDepth(
186     "scalar-evolution-max-value-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive value complexity comparisons"),
188     cl::init(2));
189 
190 static cl::opt<unsigned>
191     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
192                   cl::desc("Maximum depth of recursive arithmetics"),
193                   cl::init(32));
194 
195 static cl::opt<unsigned> MaxConstantEvolvingDepth(
196     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
198 
199 static cl::opt<unsigned>
200     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
201                 cl::desc("Maximum depth of recursive SExt/ZExt"),
202                 cl::init(8));
203 
204 static cl::opt<unsigned>
205     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
206                   cl::desc("Max coefficients in AddRec during evolving"),
207                   cl::init(16));
208 
209 //===----------------------------------------------------------------------===//
210 //                           SCEV class definitions
211 //===----------------------------------------------------------------------===//
212 
213 //===----------------------------------------------------------------------===//
214 // Implementation of the SCEV class.
215 //
216 
217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
218 LLVM_DUMP_METHOD void SCEV::dump() const {
219   print(dbgs());
220   dbgs() << '\n';
221 }
222 #endif
223 
224 void SCEV::print(raw_ostream &OS) const {
225   switch (static_cast<SCEVTypes>(getSCEVType())) {
226   case scConstant:
227     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
228     return;
229   case scTruncate: {
230     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
231     const SCEV *Op = Trunc->getOperand();
232     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
233        << *Trunc->getType() << ")";
234     return;
235   }
236   case scZeroExtend: {
237     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
238     const SCEV *Op = ZExt->getOperand();
239     OS << "(zext " << *Op->getType() << " " << *Op << " to "
240        << *ZExt->getType() << ")";
241     return;
242   }
243   case scSignExtend: {
244     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
245     const SCEV *Op = SExt->getOperand();
246     OS << "(sext " << *Op->getType() << " " << *Op << " to "
247        << *SExt->getType() << ")";
248     return;
249   }
250   case scAddRecExpr: {
251     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
252     OS << "{" << *AR->getOperand(0);
253     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
254       OS << ",+," << *AR->getOperand(i);
255     OS << "}<";
256     if (AR->hasNoUnsignedWrap())
257       OS << "nuw><";
258     if (AR->hasNoSignedWrap())
259       OS << "nsw><";
260     if (AR->hasNoSelfWrap() &&
261         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
262       OS << "nw><";
263     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
264     OS << ">";
265     return;
266   }
267   case scAddExpr:
268   case scMulExpr:
269   case scUMaxExpr:
270   case scSMaxExpr: {
271     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
272     const char *OpStr = nullptr;
273     switch (NAry->getSCEVType()) {
274     case scAddExpr: OpStr = " + "; break;
275     case scMulExpr: OpStr = " * "; break;
276     case scUMaxExpr: OpStr = " umax "; break;
277     case scSMaxExpr: OpStr = " smax "; break;
278     }
279     OS << "(";
280     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
281          I != E; ++I) {
282       OS << **I;
283       if (std::next(I) != E)
284         OS << OpStr;
285     }
286     OS << ")";
287     switch (NAry->getSCEVType()) {
288     case scAddExpr:
289     case scMulExpr:
290       if (NAry->hasNoUnsignedWrap())
291         OS << "<nuw>";
292       if (NAry->hasNoSignedWrap())
293         OS << "<nsw>";
294     }
295     return;
296   }
297   case scUDivExpr: {
298     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
299     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
300     return;
301   }
302   case scUnknown: {
303     const SCEVUnknown *U = cast<SCEVUnknown>(this);
304     Type *AllocTy;
305     if (U->isSizeOf(AllocTy)) {
306       OS << "sizeof(" << *AllocTy << ")";
307       return;
308     }
309     if (U->isAlignOf(AllocTy)) {
310       OS << "alignof(" << *AllocTy << ")";
311       return;
312     }
313 
314     Type *CTy;
315     Constant *FieldNo;
316     if (U->isOffsetOf(CTy, FieldNo)) {
317       OS << "offsetof(" << *CTy << ", ";
318       FieldNo->printAsOperand(OS, false);
319       OS << ")";
320       return;
321     }
322 
323     // Otherwise just print it normally.
324     U->getValue()->printAsOperand(OS, false);
325     return;
326   }
327   case scCouldNotCompute:
328     OS << "***COULDNOTCOMPUTE***";
329     return;
330   }
331   llvm_unreachable("Unknown SCEV kind!");
332 }
333 
334 Type *SCEV::getType() const {
335   switch (static_cast<SCEVTypes>(getSCEVType())) {
336   case scConstant:
337     return cast<SCEVConstant>(this)->getType();
338   case scTruncate:
339   case scZeroExtend:
340   case scSignExtend:
341     return cast<SCEVCastExpr>(this)->getType();
342   case scAddRecExpr:
343   case scMulExpr:
344   case scUMaxExpr:
345   case scSMaxExpr:
346     return cast<SCEVNAryExpr>(this)->getType();
347   case scAddExpr:
348     return cast<SCEVAddExpr>(this)->getType();
349   case scUDivExpr:
350     return cast<SCEVUDivExpr>(this)->getType();
351   case scUnknown:
352     return cast<SCEVUnknown>(this)->getType();
353   case scCouldNotCompute:
354     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
355   }
356   llvm_unreachable("Unknown SCEV kind!");
357 }
358 
359 bool SCEV::isZero() const {
360   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
361     return SC->getValue()->isZero();
362   return false;
363 }
364 
365 bool SCEV::isOne() const {
366   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
367     return SC->getValue()->isOne();
368   return false;
369 }
370 
371 bool SCEV::isAllOnesValue() const {
372   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
373     return SC->getValue()->isMinusOne();
374   return false;
375 }
376 
377 bool SCEV::isNonConstantNegative() const {
378   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
379   if (!Mul) return false;
380 
381   // If there is a constant factor, it will be first.
382   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
383   if (!SC) return false;
384 
385   // Return true if the value is negative, this matches things like (-42 * V).
386   return SC->getAPInt().isNegative();
387 }
388 
389 SCEVCouldNotCompute::SCEVCouldNotCompute() :
390   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
391 
392 bool SCEVCouldNotCompute::classof(const SCEV *S) {
393   return S->getSCEVType() == scCouldNotCompute;
394 }
395 
396 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
397   FoldingSetNodeID ID;
398   ID.AddInteger(scConstant);
399   ID.AddPointer(V);
400   void *IP = nullptr;
401   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
402   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
403   UniqueSCEVs.InsertNode(S, IP);
404   return S;
405 }
406 
407 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
408   return getConstant(ConstantInt::get(getContext(), Val));
409 }
410 
411 const SCEV *
412 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
413   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
414   return getConstant(ConstantInt::get(ITy, V, isSigned));
415 }
416 
417 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
418                            unsigned SCEVTy, const SCEV *op, Type *ty)
419   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
420 
421 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
422                                    const SCEV *op, Type *ty)
423   : SCEVCastExpr(ID, scTruncate, op, ty) {
424   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
425          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
426          "Cannot truncate non-integer value!");
427 }
428 
429 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
430                                        const SCEV *op, Type *ty)
431   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
432   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
433          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
434          "Cannot zero extend non-integer value!");
435 }
436 
437 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
438                                        const SCEV *op, Type *ty)
439   : SCEVCastExpr(ID, scSignExtend, op, ty) {
440   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
441          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
442          "Cannot sign extend non-integer value!");
443 }
444 
445 void SCEVUnknown::deleted() {
446   // Clear this SCEVUnknown from various maps.
447   SE->forgetMemoizedResults(this);
448 
449   // Remove this SCEVUnknown from the uniquing map.
450   SE->UniqueSCEVs.RemoveNode(this);
451 
452   // Release the value.
453   setValPtr(nullptr);
454 }
455 
456 void SCEVUnknown::allUsesReplacedWith(Value *New) {
457   // Remove this SCEVUnknown from the uniquing map.
458   SE->UniqueSCEVs.RemoveNode(this);
459 
460   // Update this SCEVUnknown to point to the new value. This is needed
461   // because there may still be outstanding SCEVs which still point to
462   // this SCEVUnknown.
463   setValPtr(New);
464 }
465 
466 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
467   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
468     if (VCE->getOpcode() == Instruction::PtrToInt)
469       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
470         if (CE->getOpcode() == Instruction::GetElementPtr &&
471             CE->getOperand(0)->isNullValue() &&
472             CE->getNumOperands() == 2)
473           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
474             if (CI->isOne()) {
475               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
476                                  ->getElementType();
477               return true;
478             }
479 
480   return false;
481 }
482 
483 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
484   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
485     if (VCE->getOpcode() == Instruction::PtrToInt)
486       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
487         if (CE->getOpcode() == Instruction::GetElementPtr &&
488             CE->getOperand(0)->isNullValue()) {
489           Type *Ty =
490             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
491           if (StructType *STy = dyn_cast<StructType>(Ty))
492             if (!STy->isPacked() &&
493                 CE->getNumOperands() == 3 &&
494                 CE->getOperand(1)->isNullValue()) {
495               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
496                 if (CI->isOne() &&
497                     STy->getNumElements() == 2 &&
498                     STy->getElementType(0)->isIntegerTy(1)) {
499                   AllocTy = STy->getElementType(1);
500                   return true;
501                 }
502             }
503         }
504 
505   return false;
506 }
507 
508 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
509   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
510     if (VCE->getOpcode() == Instruction::PtrToInt)
511       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
512         if (CE->getOpcode() == Instruction::GetElementPtr &&
513             CE->getNumOperands() == 3 &&
514             CE->getOperand(0)->isNullValue() &&
515             CE->getOperand(1)->isNullValue()) {
516           Type *Ty =
517             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
518           // Ignore vector types here so that ScalarEvolutionExpander doesn't
519           // emit getelementptrs that index into vectors.
520           if (Ty->isStructTy() || Ty->isArrayTy()) {
521             CTy = Ty;
522             FieldNo = CE->getOperand(2);
523             return true;
524           }
525         }
526 
527   return false;
528 }
529 
530 //===----------------------------------------------------------------------===//
531 //                               SCEV Utilities
532 //===----------------------------------------------------------------------===//
533 
534 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
535 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
536 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
537 /// have been previously deemed to be "equally complex" by this routine.  It is
538 /// intended to avoid exponential time complexity in cases like:
539 ///
540 ///   %a = f(%x, %y)
541 ///   %b = f(%a, %a)
542 ///   %c = f(%b, %b)
543 ///
544 ///   %d = f(%x, %y)
545 ///   %e = f(%d, %d)
546 ///   %f = f(%e, %e)
547 ///
548 ///   CompareValueComplexity(%f, %c)
549 ///
550 /// Since we do not continue running this routine on expression trees once we
551 /// have seen unequal values, there is no need to track them in the cache.
552 static int
553 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
554                        const LoopInfo *const LI, Value *LV, Value *RV,
555                        unsigned Depth) {
556   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
557     return 0;
558 
559   // Order pointer values after integer values. This helps SCEVExpander form
560   // GEPs.
561   bool LIsPointer = LV->getType()->isPointerTy(),
562        RIsPointer = RV->getType()->isPointerTy();
563   if (LIsPointer != RIsPointer)
564     return (int)LIsPointer - (int)RIsPointer;
565 
566   // Compare getValueID values.
567   unsigned LID = LV->getValueID(), RID = RV->getValueID();
568   if (LID != RID)
569     return (int)LID - (int)RID;
570 
571   // Sort arguments by their position.
572   if (const auto *LA = dyn_cast<Argument>(LV)) {
573     const auto *RA = cast<Argument>(RV);
574     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
575     return (int)LArgNo - (int)RArgNo;
576   }
577 
578   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
579     const auto *RGV = cast<GlobalValue>(RV);
580 
581     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
582       auto LT = GV->getLinkage();
583       return !(GlobalValue::isPrivateLinkage(LT) ||
584                GlobalValue::isInternalLinkage(LT));
585     };
586 
587     // Use the names to distinguish the two values, but only if the
588     // names are semantically important.
589     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
590       return LGV->getName().compare(RGV->getName());
591   }
592 
593   // For instructions, compare their loop depth, and their operand count.  This
594   // is pretty loose.
595   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
596     const auto *RInst = cast<Instruction>(RV);
597 
598     // Compare loop depths.
599     const BasicBlock *LParent = LInst->getParent(),
600                      *RParent = RInst->getParent();
601     if (LParent != RParent) {
602       unsigned LDepth = LI->getLoopDepth(LParent),
603                RDepth = LI->getLoopDepth(RParent);
604       if (LDepth != RDepth)
605         return (int)LDepth - (int)RDepth;
606     }
607 
608     // Compare the number of operands.
609     unsigned LNumOps = LInst->getNumOperands(),
610              RNumOps = RInst->getNumOperands();
611     if (LNumOps != RNumOps)
612       return (int)LNumOps - (int)RNumOps;
613 
614     for (unsigned Idx : seq(0u, LNumOps)) {
615       int Result =
616           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
617                                  RInst->getOperand(Idx), Depth + 1);
618       if (Result != 0)
619         return Result;
620     }
621   }
622 
623   EqCacheValue.unionSets(LV, RV);
624   return 0;
625 }
626 
627 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
628 // than RHS, respectively. A three-way result allows recursive comparisons to be
629 // more efficient.
630 static int CompareSCEVComplexity(
631     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
632     EquivalenceClasses<const Value *> &EqCacheValue,
633     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
634     DominatorTree &DT, unsigned Depth = 0) {
635   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
636   if (LHS == RHS)
637     return 0;
638 
639   // Primarily, sort the SCEVs by their getSCEVType().
640   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
641   if (LType != RType)
642     return (int)LType - (int)RType;
643 
644   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
645     return 0;
646   // Aside from the getSCEVType() ordering, the particular ordering
647   // isn't very important except that it's beneficial to be consistent,
648   // so that (a + b) and (b + a) don't end up as different expressions.
649   switch (static_cast<SCEVTypes>(LType)) {
650   case scUnknown: {
651     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
652     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
653 
654     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
655                                    RU->getValue(), Depth + 1);
656     if (X == 0)
657       EqCacheSCEV.unionSets(LHS, RHS);
658     return X;
659   }
660 
661   case scConstant: {
662     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
663     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
664 
665     // Compare constant values.
666     const APInt &LA = LC->getAPInt();
667     const APInt &RA = RC->getAPInt();
668     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
669     if (LBitWidth != RBitWidth)
670       return (int)LBitWidth - (int)RBitWidth;
671     return LA.ult(RA) ? -1 : 1;
672   }
673 
674   case scAddRecExpr: {
675     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
676     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
677 
678     // There is always a dominance between two recs that are used by one SCEV,
679     // so we can safely sort recs by loop header dominance. We require such
680     // order in getAddExpr.
681     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
682     if (LLoop != RLoop) {
683       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
684       assert(LHead != RHead && "Two loops share the same header?");
685       if (DT.dominates(LHead, RHead))
686         return 1;
687       else
688         assert(DT.dominates(RHead, LHead) &&
689                "No dominance between recurrences used by one SCEV?");
690       return -1;
691     }
692 
693     // Addrec complexity grows with operand count.
694     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
695     if (LNumOps != RNumOps)
696       return (int)LNumOps - (int)RNumOps;
697 
698     // Compare NoWrap flags.
699     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
700       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
701 
702     // Lexicographically compare.
703     for (unsigned i = 0; i != LNumOps; ++i) {
704       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
705                                     LA->getOperand(i), RA->getOperand(i), DT,
706                                     Depth + 1);
707       if (X != 0)
708         return X;
709     }
710     EqCacheSCEV.unionSets(LHS, RHS);
711     return 0;
712   }
713 
714   case scAddExpr:
715   case scMulExpr:
716   case scSMaxExpr:
717   case scUMaxExpr: {
718     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
719     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
720 
721     // Lexicographically compare n-ary expressions.
722     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
723     if (LNumOps != RNumOps)
724       return (int)LNumOps - (int)RNumOps;
725 
726     // Compare NoWrap flags.
727     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
728       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
729 
730     for (unsigned i = 0; i != LNumOps; ++i) {
731       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
732                                     LC->getOperand(i), RC->getOperand(i), DT,
733                                     Depth + 1);
734       if (X != 0)
735         return X;
736     }
737     EqCacheSCEV.unionSets(LHS, RHS);
738     return 0;
739   }
740 
741   case scUDivExpr: {
742     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
743     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
744 
745     // Lexicographically compare udiv expressions.
746     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
747                                   RC->getLHS(), DT, Depth + 1);
748     if (X != 0)
749       return X;
750     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
751                               RC->getRHS(), DT, Depth + 1);
752     if (X == 0)
753       EqCacheSCEV.unionSets(LHS, RHS);
754     return X;
755   }
756 
757   case scTruncate:
758   case scZeroExtend:
759   case scSignExtend: {
760     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
761     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
762 
763     // Compare cast expressions by operand.
764     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
765                                   LC->getOperand(), RC->getOperand(), DT,
766                                   Depth + 1);
767     if (X == 0)
768       EqCacheSCEV.unionSets(LHS, RHS);
769     return X;
770   }
771 
772   case scCouldNotCompute:
773     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
774   }
775   llvm_unreachable("Unknown SCEV kind!");
776 }
777 
778 /// Given a list of SCEV objects, order them by their complexity, and group
779 /// objects of the same complexity together by value.  When this routine is
780 /// finished, we know that any duplicates in the vector are consecutive and that
781 /// complexity is monotonically increasing.
782 ///
783 /// Note that we go take special precautions to ensure that we get deterministic
784 /// results from this routine.  In other words, we don't want the results of
785 /// this to depend on where the addresses of various SCEV objects happened to
786 /// land in memory.
787 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
788                               LoopInfo *LI, DominatorTree &DT) {
789   if (Ops.size() < 2) return;  // Noop
790 
791   EquivalenceClasses<const SCEV *> EqCacheSCEV;
792   EquivalenceClasses<const Value *> EqCacheValue;
793   if (Ops.size() == 2) {
794     // This is the common case, which also happens to be trivially simple.
795     // Special case it.
796     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
797     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
798       std::swap(LHS, RHS);
799     return;
800   }
801 
802   // Do the rough sort by complexity.
803   std::stable_sort(Ops.begin(), Ops.end(),
804                    [&](const SCEV *LHS, const SCEV *RHS) {
805                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
806                                                   LHS, RHS, DT) < 0;
807                    });
808 
809   // Now that we are sorted by complexity, group elements of the same
810   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
811   // be extremely short in practice.  Note that we take this approach because we
812   // do not want to depend on the addresses of the objects we are grouping.
813   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
814     const SCEV *S = Ops[i];
815     unsigned Complexity = S->getSCEVType();
816 
817     // If there are any objects of the same complexity and same value as this
818     // one, group them.
819     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
820       if (Ops[j] == S) { // Found a duplicate.
821         // Move it to immediately after i'th element.
822         std::swap(Ops[i+1], Ops[j]);
823         ++i;   // no need to rescan it.
824         if (i == e-2) return;  // Done!
825       }
826     }
827   }
828 }
829 
830 // Returns the size of the SCEV S.
831 static inline int sizeOfSCEV(const SCEV *S) {
832   struct FindSCEVSize {
833     int Size = 0;
834 
835     FindSCEVSize() = default;
836 
837     bool follow(const SCEV *S) {
838       ++Size;
839       // Keep looking at all operands of S.
840       return true;
841     }
842 
843     bool isDone() const {
844       return false;
845     }
846   };
847 
848   FindSCEVSize F;
849   SCEVTraversal<FindSCEVSize> ST(F);
850   ST.visitAll(S);
851   return F.Size;
852 }
853 
854 namespace {
855 
856 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
857 public:
858   // Computes the Quotient and Remainder of the division of Numerator by
859   // Denominator.
860   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
861                      const SCEV *Denominator, const SCEV **Quotient,
862                      const SCEV **Remainder) {
863     assert(Numerator && Denominator && "Uninitialized SCEV");
864 
865     SCEVDivision D(SE, Numerator, Denominator);
866 
867     // Check for the trivial case here to avoid having to check for it in the
868     // rest of the code.
869     if (Numerator == Denominator) {
870       *Quotient = D.One;
871       *Remainder = D.Zero;
872       return;
873     }
874 
875     if (Numerator->isZero()) {
876       *Quotient = D.Zero;
877       *Remainder = D.Zero;
878       return;
879     }
880 
881     // A simple case when N/1. The quotient is N.
882     if (Denominator->isOne()) {
883       *Quotient = Numerator;
884       *Remainder = D.Zero;
885       return;
886     }
887 
888     // Split the Denominator when it is a product.
889     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
890       const SCEV *Q, *R;
891       *Quotient = Numerator;
892       for (const SCEV *Op : T->operands()) {
893         divide(SE, *Quotient, Op, &Q, &R);
894         *Quotient = Q;
895 
896         // Bail out when the Numerator is not divisible by one of the terms of
897         // the Denominator.
898         if (!R->isZero()) {
899           *Quotient = D.Zero;
900           *Remainder = Numerator;
901           return;
902         }
903       }
904       *Remainder = D.Zero;
905       return;
906     }
907 
908     D.visit(Numerator);
909     *Quotient = D.Quotient;
910     *Remainder = D.Remainder;
911   }
912 
913   // Except in the trivial case described above, we do not know how to divide
914   // Expr by Denominator for the following functions with empty implementation.
915   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
916   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
917   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
918   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
919   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
920   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
921   void visitUnknown(const SCEVUnknown *Numerator) {}
922   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
923 
924   void visitConstant(const SCEVConstant *Numerator) {
925     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
926       APInt NumeratorVal = Numerator->getAPInt();
927       APInt DenominatorVal = D->getAPInt();
928       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
929       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
930 
931       if (NumeratorBW > DenominatorBW)
932         DenominatorVal = DenominatorVal.sext(NumeratorBW);
933       else if (NumeratorBW < DenominatorBW)
934         NumeratorVal = NumeratorVal.sext(DenominatorBW);
935 
936       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
937       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
938       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
939       Quotient = SE.getConstant(QuotientVal);
940       Remainder = SE.getConstant(RemainderVal);
941       return;
942     }
943   }
944 
945   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
946     const SCEV *StartQ, *StartR, *StepQ, *StepR;
947     if (!Numerator->isAffine())
948       return cannotDivide(Numerator);
949     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
950     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
951     // Bail out if the types do not match.
952     Type *Ty = Denominator->getType();
953     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
954         Ty != StepQ->getType() || Ty != StepR->getType())
955       return cannotDivide(Numerator);
956     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
957                                 Numerator->getNoWrapFlags());
958     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
959                                  Numerator->getNoWrapFlags());
960   }
961 
962   void visitAddExpr(const SCEVAddExpr *Numerator) {
963     SmallVector<const SCEV *, 2> Qs, Rs;
964     Type *Ty = Denominator->getType();
965 
966     for (const SCEV *Op : Numerator->operands()) {
967       const SCEV *Q, *R;
968       divide(SE, Op, Denominator, &Q, &R);
969 
970       // Bail out if types do not match.
971       if (Ty != Q->getType() || Ty != R->getType())
972         return cannotDivide(Numerator);
973 
974       Qs.push_back(Q);
975       Rs.push_back(R);
976     }
977 
978     if (Qs.size() == 1) {
979       Quotient = Qs[0];
980       Remainder = Rs[0];
981       return;
982     }
983 
984     Quotient = SE.getAddExpr(Qs);
985     Remainder = SE.getAddExpr(Rs);
986   }
987 
988   void visitMulExpr(const SCEVMulExpr *Numerator) {
989     SmallVector<const SCEV *, 2> Qs;
990     Type *Ty = Denominator->getType();
991 
992     bool FoundDenominatorTerm = false;
993     for (const SCEV *Op : Numerator->operands()) {
994       // Bail out if types do not match.
995       if (Ty != Op->getType())
996         return cannotDivide(Numerator);
997 
998       if (FoundDenominatorTerm) {
999         Qs.push_back(Op);
1000         continue;
1001       }
1002 
1003       // Check whether Denominator divides one of the product operands.
1004       const SCEV *Q, *R;
1005       divide(SE, Op, Denominator, &Q, &R);
1006       if (!R->isZero()) {
1007         Qs.push_back(Op);
1008         continue;
1009       }
1010 
1011       // Bail out if types do not match.
1012       if (Ty != Q->getType())
1013         return cannotDivide(Numerator);
1014 
1015       FoundDenominatorTerm = true;
1016       Qs.push_back(Q);
1017     }
1018 
1019     if (FoundDenominatorTerm) {
1020       Remainder = Zero;
1021       if (Qs.size() == 1)
1022         Quotient = Qs[0];
1023       else
1024         Quotient = SE.getMulExpr(Qs);
1025       return;
1026     }
1027 
1028     if (!isa<SCEVUnknown>(Denominator))
1029       return cannotDivide(Numerator);
1030 
1031     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1032     ValueToValueMap RewriteMap;
1033     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1034         cast<SCEVConstant>(Zero)->getValue();
1035     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1036 
1037     if (Remainder->isZero()) {
1038       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1039       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1040           cast<SCEVConstant>(One)->getValue();
1041       Quotient =
1042           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1043       return;
1044     }
1045 
1046     // Quotient is (Numerator - Remainder) divided by Denominator.
1047     const SCEV *Q, *R;
1048     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1049     // This SCEV does not seem to simplify: fail the division here.
1050     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1051       return cannotDivide(Numerator);
1052     divide(SE, Diff, Denominator, &Q, &R);
1053     if (R != Zero)
1054       return cannotDivide(Numerator);
1055     Quotient = Q;
1056   }
1057 
1058 private:
1059   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1060                const SCEV *Denominator)
1061       : SE(S), Denominator(Denominator) {
1062     Zero = SE.getZero(Denominator->getType());
1063     One = SE.getOne(Denominator->getType());
1064 
1065     // We generally do not know how to divide Expr by Denominator. We
1066     // initialize the division to a "cannot divide" state to simplify the rest
1067     // of the code.
1068     cannotDivide(Numerator);
1069   }
1070 
1071   // Convenience function for giving up on the division. We set the quotient to
1072   // be equal to zero and the remainder to be equal to the numerator.
1073   void cannotDivide(const SCEV *Numerator) {
1074     Quotient = Zero;
1075     Remainder = Numerator;
1076   }
1077 
1078   ScalarEvolution &SE;
1079   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1080 };
1081 
1082 } // end anonymous namespace
1083 
1084 //===----------------------------------------------------------------------===//
1085 //                      Simple SCEV method implementations
1086 //===----------------------------------------------------------------------===//
1087 
1088 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1089 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1090                                        ScalarEvolution &SE,
1091                                        Type *ResultTy) {
1092   // Handle the simplest case efficiently.
1093   if (K == 1)
1094     return SE.getTruncateOrZeroExtend(It, ResultTy);
1095 
1096   // We are using the following formula for BC(It, K):
1097   //
1098   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1099   //
1100   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1101   // overflow.  Hence, we must assure that the result of our computation is
1102   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1103   // safe in modular arithmetic.
1104   //
1105   // However, this code doesn't use exactly that formula; the formula it uses
1106   // is something like the following, where T is the number of factors of 2 in
1107   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1108   // exponentiation:
1109   //
1110   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1111   //
1112   // This formula is trivially equivalent to the previous formula.  However,
1113   // this formula can be implemented much more efficiently.  The trick is that
1114   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1115   // arithmetic.  To do exact division in modular arithmetic, all we have
1116   // to do is multiply by the inverse.  Therefore, this step can be done at
1117   // width W.
1118   //
1119   // The next issue is how to safely do the division by 2^T.  The way this
1120   // is done is by doing the multiplication step at a width of at least W + T
1121   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1122   // when we perform the division by 2^T (which is equivalent to a right shift
1123   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1124   // truncated out after the division by 2^T.
1125   //
1126   // In comparison to just directly using the first formula, this technique
1127   // is much more efficient; using the first formula requires W * K bits,
1128   // but this formula less than W + K bits. Also, the first formula requires
1129   // a division step, whereas this formula only requires multiplies and shifts.
1130   //
1131   // It doesn't matter whether the subtraction step is done in the calculation
1132   // width or the input iteration count's width; if the subtraction overflows,
1133   // the result must be zero anyway.  We prefer here to do it in the width of
1134   // the induction variable because it helps a lot for certain cases; CodeGen
1135   // isn't smart enough to ignore the overflow, which leads to much less
1136   // efficient code if the width of the subtraction is wider than the native
1137   // register width.
1138   //
1139   // (It's possible to not widen at all by pulling out factors of 2 before
1140   // the multiplication; for example, K=2 can be calculated as
1141   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1142   // extra arithmetic, so it's not an obvious win, and it gets
1143   // much more complicated for K > 3.)
1144 
1145   // Protection from insane SCEVs; this bound is conservative,
1146   // but it probably doesn't matter.
1147   if (K > 1000)
1148     return SE.getCouldNotCompute();
1149 
1150   unsigned W = SE.getTypeSizeInBits(ResultTy);
1151 
1152   // Calculate K! / 2^T and T; we divide out the factors of two before
1153   // multiplying for calculating K! / 2^T to avoid overflow.
1154   // Other overflow doesn't matter because we only care about the bottom
1155   // W bits of the result.
1156   APInt OddFactorial(W, 1);
1157   unsigned T = 1;
1158   for (unsigned i = 3; i <= K; ++i) {
1159     APInt Mult(W, i);
1160     unsigned TwoFactors = Mult.countTrailingZeros();
1161     T += TwoFactors;
1162     Mult.lshrInPlace(TwoFactors);
1163     OddFactorial *= Mult;
1164   }
1165 
1166   // We need at least W + T bits for the multiplication step
1167   unsigned CalculationBits = W + T;
1168 
1169   // Calculate 2^T, at width T+W.
1170   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1171 
1172   // Calculate the multiplicative inverse of K! / 2^T;
1173   // this multiplication factor will perform the exact division by
1174   // K! / 2^T.
1175   APInt Mod = APInt::getSignedMinValue(W+1);
1176   APInt MultiplyFactor = OddFactorial.zext(W+1);
1177   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1178   MultiplyFactor = MultiplyFactor.trunc(W);
1179 
1180   // Calculate the product, at width T+W
1181   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1182                                                       CalculationBits);
1183   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1184   for (unsigned i = 1; i != K; ++i) {
1185     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1186     Dividend = SE.getMulExpr(Dividend,
1187                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1188   }
1189 
1190   // Divide by 2^T
1191   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1192 
1193   // Truncate the result, and divide by K! / 2^T.
1194 
1195   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1196                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1197 }
1198 
1199 /// Return the value of this chain of recurrences at the specified iteration
1200 /// number.  We can evaluate this recurrence by multiplying each element in the
1201 /// chain by the binomial coefficient corresponding to it.  In other words, we
1202 /// can evaluate {A,+,B,+,C,+,D} as:
1203 ///
1204 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1205 ///
1206 /// where BC(It, k) stands for binomial coefficient.
1207 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1208                                                 ScalarEvolution &SE) const {
1209   const SCEV *Result = getStart();
1210   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1211     // The computation is correct in the face of overflow provided that the
1212     // multiplication is performed _after_ the evaluation of the binomial
1213     // coefficient.
1214     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1215     if (isa<SCEVCouldNotCompute>(Coeff))
1216       return Coeff;
1217 
1218     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1219   }
1220   return Result;
1221 }
1222 
1223 //===----------------------------------------------------------------------===//
1224 //                    SCEV Expression folder implementations
1225 //===----------------------------------------------------------------------===//
1226 
1227 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1228                                              Type *Ty) {
1229   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1230          "This is not a truncating conversion!");
1231   assert(isSCEVable(Ty) &&
1232          "This is not a conversion to a SCEVable type!");
1233   Ty = getEffectiveSCEVType(Ty);
1234 
1235   FoldingSetNodeID ID;
1236   ID.AddInteger(scTruncate);
1237   ID.AddPointer(Op);
1238   ID.AddPointer(Ty);
1239   void *IP = nullptr;
1240   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1241 
1242   // Fold if the operand is constant.
1243   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1244     return getConstant(
1245       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1246 
1247   // trunc(trunc(x)) --> trunc(x)
1248   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1249     return getTruncateExpr(ST->getOperand(), Ty);
1250 
1251   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1252   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1253     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1254 
1255   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1256   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1257     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1258 
1259   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1260   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1261   // if after transforming we have at most one truncate, not counting truncates
1262   // that replace other casts.
1263   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1264     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1265     SmallVector<const SCEV *, 4> Operands;
1266     unsigned numTruncs = 0;
1267     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1268          ++i) {
1269       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty);
1270       if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1271         numTruncs++;
1272       Operands.push_back(S);
1273     }
1274     if (numTruncs < 2) {
1275       if (isa<SCEVAddExpr>(Op))
1276         return getAddExpr(Operands);
1277       else if (isa<SCEVMulExpr>(Op))
1278         return getMulExpr(Operands);
1279       else
1280         llvm_unreachable("Unexpected SCEV type for Op.");
1281     }
1282     // Although we checked in the beginning that ID is not in the cache, it is
1283     // possible that during recursion and different modification ID was inserted
1284     // into the cache. So if we find it, just return it.
1285     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1286       return S;
1287   }
1288 
1289   // If the input value is a chrec scev, truncate the chrec's operands.
1290   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1291     SmallVector<const SCEV *, 4> Operands;
1292     for (const SCEV *Op : AddRec->operands())
1293       Operands.push_back(getTruncateExpr(Op, Ty));
1294     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1295   }
1296 
1297   // The cast wasn't folded; create an explicit cast node. We can reuse
1298   // the existing insert position since if we get here, we won't have
1299   // made any changes which would invalidate it.
1300   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1301                                                  Op, Ty);
1302   UniqueSCEVs.InsertNode(S, IP);
1303   addToLoopUseLists(S);
1304   return S;
1305 }
1306 
1307 // Get the limit of a recurrence such that incrementing by Step cannot cause
1308 // signed overflow as long as the value of the recurrence within the
1309 // loop does not exceed this limit before incrementing.
1310 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1311                                                  ICmpInst::Predicate *Pred,
1312                                                  ScalarEvolution *SE) {
1313   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1314   if (SE->isKnownPositive(Step)) {
1315     *Pred = ICmpInst::ICMP_SLT;
1316     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1317                            SE->getSignedRangeMax(Step));
1318   }
1319   if (SE->isKnownNegative(Step)) {
1320     *Pred = ICmpInst::ICMP_SGT;
1321     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1322                            SE->getSignedRangeMin(Step));
1323   }
1324   return nullptr;
1325 }
1326 
1327 // Get the limit of a recurrence such that incrementing by Step cannot cause
1328 // unsigned overflow as long as the value of the recurrence within the loop does
1329 // not exceed this limit before incrementing.
1330 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1331                                                    ICmpInst::Predicate *Pred,
1332                                                    ScalarEvolution *SE) {
1333   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1334   *Pred = ICmpInst::ICMP_ULT;
1335 
1336   return SE->getConstant(APInt::getMinValue(BitWidth) -
1337                          SE->getUnsignedRangeMax(Step));
1338 }
1339 
1340 namespace {
1341 
1342 struct ExtendOpTraitsBase {
1343   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1344                                                           unsigned);
1345 };
1346 
1347 // Used to make code generic over signed and unsigned overflow.
1348 template <typename ExtendOp> struct ExtendOpTraits {
1349   // Members present:
1350   //
1351   // static const SCEV::NoWrapFlags WrapType;
1352   //
1353   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1354   //
1355   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1356   //                                           ICmpInst::Predicate *Pred,
1357   //                                           ScalarEvolution *SE);
1358 };
1359 
1360 template <>
1361 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1362   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1363 
1364   static const GetExtendExprTy GetExtendExpr;
1365 
1366   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1367                                              ICmpInst::Predicate *Pred,
1368                                              ScalarEvolution *SE) {
1369     return getSignedOverflowLimitForStep(Step, Pred, SE);
1370   }
1371 };
1372 
1373 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1374     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1375 
1376 template <>
1377 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1378   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1379 
1380   static const GetExtendExprTy GetExtendExpr;
1381 
1382   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1383                                              ICmpInst::Predicate *Pred,
1384                                              ScalarEvolution *SE) {
1385     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1386   }
1387 };
1388 
1389 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1390     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1391 
1392 } // end anonymous namespace
1393 
1394 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1395 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1396 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1397 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1398 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1399 // expression "Step + sext/zext(PreIncAR)" is congruent with
1400 // "sext/zext(PostIncAR)"
1401 template <typename ExtendOpTy>
1402 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1403                                         ScalarEvolution *SE, unsigned Depth) {
1404   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1405   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1406 
1407   const Loop *L = AR->getLoop();
1408   const SCEV *Start = AR->getStart();
1409   const SCEV *Step = AR->getStepRecurrence(*SE);
1410 
1411   // Check for a simple looking step prior to loop entry.
1412   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1413   if (!SA)
1414     return nullptr;
1415 
1416   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1417   // subtraction is expensive. For this purpose, perform a quick and dirty
1418   // difference, by checking for Step in the operand list.
1419   SmallVector<const SCEV *, 4> DiffOps;
1420   for (const SCEV *Op : SA->operands())
1421     if (Op != Step)
1422       DiffOps.push_back(Op);
1423 
1424   if (DiffOps.size() == SA->getNumOperands())
1425     return nullptr;
1426 
1427   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1428   // `Step`:
1429 
1430   // 1. NSW/NUW flags on the step increment.
1431   auto PreStartFlags = SA->getNoWrapFlags() & SCEV::FlagNUW;
1432   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1433   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1434       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1435 
1436   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1437   // "S+X does not sign/unsign-overflow".
1438   //
1439 
1440   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1441   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1442       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1443     return PreStart;
1444 
1445   // 2. Direct overflow check on the step operation's expression.
1446   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1447   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1448   const SCEV *OperandExtendedStart =
1449       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1450                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1451   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1452     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1453       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1454       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1455       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1456       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1457     }
1458     return PreStart;
1459   }
1460 
1461   // 3. Loop precondition.
1462   ICmpInst::Predicate Pred;
1463   const SCEV *OverflowLimit =
1464       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1465 
1466   if (OverflowLimit &&
1467       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1468     return PreStart;
1469 
1470   return nullptr;
1471 }
1472 
1473 // Get the normalized zero or sign extended expression for this AddRec's Start.
1474 template <typename ExtendOpTy>
1475 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1476                                         ScalarEvolution *SE,
1477                                         unsigned Depth) {
1478   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1479 
1480   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1481   if (!PreStart)
1482     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1483 
1484   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1485                                              Depth),
1486                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1487 }
1488 
1489 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1490 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1491 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1492 //
1493 // Formally:
1494 //
1495 //     {S,+,X} == {S-T,+,X} + T
1496 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1497 //
1498 // If ({S-T,+,X} + T) does not overflow  ... (1)
1499 //
1500 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1501 //
1502 // If {S-T,+,X} does not overflow  ... (2)
1503 //
1504 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1505 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1506 //
1507 // If (S-T)+T does not overflow  ... (3)
1508 //
1509 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1510 //      == {Ext(S),+,Ext(X)} == LHS
1511 //
1512 // Thus, if (1), (2) and (3) are true for some T, then
1513 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1514 //
1515 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1516 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1517 // to check for (1) and (2).
1518 //
1519 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1520 // is `Delta` (defined below).
1521 template <typename ExtendOpTy>
1522 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1523                                                 const SCEV *Step,
1524                                                 const Loop *L) {
1525   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1526 
1527   // We restrict `Start` to a constant to prevent SCEV from spending too much
1528   // time here.  It is correct (but more expensive) to continue with a
1529   // non-constant `Start` and do a general SCEV subtraction to compute
1530   // `PreStart` below.
1531   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1532   if (!StartC)
1533     return false;
1534 
1535   APInt StartAI = StartC->getAPInt();
1536 
1537   for (unsigned Delta : {-2, -1, 1, 2}) {
1538     const SCEV *PreStart = getConstant(StartAI - Delta);
1539 
1540     FoldingSetNodeID ID;
1541     ID.AddInteger(scAddRecExpr);
1542     ID.AddPointer(PreStart);
1543     ID.AddPointer(Step);
1544     ID.AddPointer(L);
1545     void *IP = nullptr;
1546     const auto *PreAR =
1547       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1548 
1549     // Give up if we don't already have the add recurrence we need because
1550     // actually constructing an add recurrence is relatively expensive.
1551     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1552       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1553       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1554       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1555           DeltaS, &Pred, this);
1556       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1557         return true;
1558     }
1559   }
1560 
1561   return false;
1562 }
1563 
1564 const SCEV *
1565 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1566   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1567          "This is not an extending conversion!");
1568   assert(isSCEVable(Ty) &&
1569          "This is not a conversion to a SCEVable type!");
1570   Ty = getEffectiveSCEVType(Ty);
1571 
1572   // Fold if the operand is constant.
1573   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1574     return getConstant(
1575       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1576 
1577   // zext(zext(x)) --> zext(x)
1578   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1579     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1580 
1581   // Before doing any expensive analysis, check to see if we've already
1582   // computed a SCEV for this Op and Ty.
1583   FoldingSetNodeID ID;
1584   ID.AddInteger(scZeroExtend);
1585   ID.AddPointer(Op);
1586   ID.AddPointer(Ty);
1587   void *IP = nullptr;
1588   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1589   if (Depth > MaxExtDepth) {
1590     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1591                                                      Op, Ty);
1592     UniqueSCEVs.InsertNode(S, IP);
1593     addToLoopUseLists(S);
1594     return S;
1595   }
1596 
1597   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1598   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1599     // It's possible the bits taken off by the truncate were all zero bits. If
1600     // so, we should be able to simplify this further.
1601     const SCEV *X = ST->getOperand();
1602     ConstantRange CR = getUnsignedRange(X);
1603     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1604     unsigned NewBits = getTypeSizeInBits(Ty);
1605     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1606             CR.zextOrTrunc(NewBits)))
1607       return getTruncateOrZeroExtend(X, Ty);
1608   }
1609 
1610   // If the input value is a chrec scev, and we can prove that the value
1611   // did not overflow the old, smaller, value, we can zero extend all of the
1612   // operands (often constants).  This allows analysis of something like
1613   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1614   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1615     if (AR->isAffine()) {
1616       const SCEV *Start = AR->getStart();
1617       const SCEV *Step = AR->getStepRecurrence(*this);
1618       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1619       const Loop *L = AR->getLoop();
1620 
1621       if (!AR->hasNoUnsignedWrap()) {
1622         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1623         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1624       }
1625 
1626       // If we have special knowledge that this addrec won't overflow,
1627       // we don't need to do any further analysis.
1628       if (AR->hasNoUnsignedWrap())
1629         return getAddRecExpr(
1630             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1631             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1632 
1633       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1634       // Note that this serves two purposes: It filters out loops that are
1635       // simply not analyzable, and it covers the case where this code is
1636       // being called from within backedge-taken count analysis, such that
1637       // attempting to ask for the backedge-taken count would likely result
1638       // in infinite recursion. In the later case, the analysis code will
1639       // cope with a conservative value, and it will take care to purge
1640       // that value once it has finished.
1641       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1642       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1643         // Manually compute the final value for AR, checking for
1644         // overflow.
1645 
1646         // Check whether the backedge-taken count can be losslessly casted to
1647         // the addrec's type. The count is always unsigned.
1648         const SCEV *CastedMaxBECount =
1649           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1650         const SCEV *RecastedMaxBECount =
1651           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1652         if (MaxBECount == RecastedMaxBECount) {
1653           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1654           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1655           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1656                                         SCEV::FlagAnyWrap, Depth + 1);
1657           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1658                                                           SCEV::FlagAnyWrap,
1659                                                           Depth + 1),
1660                                                WideTy, Depth + 1);
1661           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1662           const SCEV *WideMaxBECount =
1663             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1664           const SCEV *OperandExtendedAdd =
1665             getAddExpr(WideStart,
1666                        getMulExpr(WideMaxBECount,
1667                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1668                                   SCEV::FlagAnyWrap, Depth + 1),
1669                        SCEV::FlagAnyWrap, Depth + 1);
1670           if (ZAdd == OperandExtendedAdd) {
1671             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1672             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1673             // Return the expression with the addrec on the outside.
1674             return getAddRecExpr(
1675                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1676                                                          Depth + 1),
1677                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1678                 AR->getNoWrapFlags());
1679           }
1680           // Similar to above, only this time treat the step value as signed.
1681           // This covers loops that count down.
1682           OperandExtendedAdd =
1683             getAddExpr(WideStart,
1684                        getMulExpr(WideMaxBECount,
1685                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1686                                   SCEV::FlagAnyWrap, Depth + 1),
1687                        SCEV::FlagAnyWrap, Depth + 1);
1688           if (ZAdd == OperandExtendedAdd) {
1689             // Cache knowledge of AR NW, which is propagated to this AddRec.
1690             // Negative step causes unsigned wrap, but it still can't self-wrap.
1691             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1692             // Return the expression with the addrec on the outside.
1693             return getAddRecExpr(
1694                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1695                                                          Depth + 1),
1696                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1697                 AR->getNoWrapFlags());
1698           }
1699         }
1700       }
1701 
1702       // Normally, in the cases we can prove no-overflow via a
1703       // backedge guarding condition, we can also compute a backedge
1704       // taken count for the loop.  The exceptions are assumptions and
1705       // guards present in the loop -- SCEV is not great at exploiting
1706       // these to compute max backedge taken counts, but can still use
1707       // these to prove lack of overflow.  Use this fact to avoid
1708       // doing extra work that may not pay off.
1709       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1710           !AC.assumptions().empty()) {
1711         // If the backedge is guarded by a comparison with the pre-inc
1712         // value the addrec is safe. Also, if the entry is guarded by
1713         // a comparison with the start value and the backedge is
1714         // guarded by a comparison with the post-inc value, the addrec
1715         // is safe.
1716         if (isKnownPositive(Step)) {
1717           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1718                                       getUnsignedRangeMax(Step));
1719           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1720               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1721             // Cache knowledge of AR NUW, which is propagated to this
1722             // AddRec.
1723             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1724             // Return the expression with the addrec on the outside.
1725             return getAddRecExpr(
1726                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1727                                                          Depth + 1),
1728                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1729                 AR->getNoWrapFlags());
1730           }
1731         } else if (isKnownNegative(Step)) {
1732           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1733                                       getSignedRangeMin(Step));
1734           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1735               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1736             // Cache knowledge of AR NW, which is propagated to this
1737             // AddRec.  Negative step causes unsigned wrap, but it
1738             // still can't self-wrap.
1739             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1740             // Return the expression with the addrec on the outside.
1741             return getAddRecExpr(
1742                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1743                                                          Depth + 1),
1744                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1745                 AR->getNoWrapFlags());
1746           }
1747         }
1748       }
1749 
1750       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1751         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1752         return getAddRecExpr(
1753             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1754             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1755       }
1756     }
1757 
1758   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1759     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1760     if (SA->hasNoUnsignedWrap()) {
1761       // If the addition does not unsign overflow then we can, by definition,
1762       // commute the zero extension with the addition operation.
1763       SmallVector<const SCEV *, 4> Ops;
1764       for (const auto *Op : SA->operands())
1765         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1766       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1767     }
1768   }
1769 
1770   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1771     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1772     if (SM->hasNoUnsignedWrap()) {
1773       // If the multiply does not unsign overflow then we can, by definition,
1774       // commute the zero extension with the multiply operation.
1775       SmallVector<const SCEV *, 4> Ops;
1776       for (const auto *Op : SM->operands())
1777         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1778       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1779     }
1780 
1781     // zext(2^K * (trunc X to iN)) to iM ->
1782     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1783     //
1784     // Proof:
1785     //
1786     //     zext(2^K * (trunc X to iN)) to iM
1787     //   = zext((trunc X to iN) << K) to iM
1788     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1789     //     (because shl removes the top K bits)
1790     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1791     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1792     //
1793     if (SM->getNumOperands() == 2)
1794       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1795         if (MulLHS->getAPInt().isPowerOf2())
1796           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1797             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1798                                MulLHS->getAPInt().logBase2();
1799             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1800             return getMulExpr(
1801                 getZeroExtendExpr(MulLHS, Ty),
1802                 getZeroExtendExpr(
1803                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1804                 SCEV::FlagNUW, Depth + 1);
1805           }
1806   }
1807 
1808   // The cast wasn't folded; create an explicit cast node.
1809   // Recompute the insert position, as it may have been invalidated.
1810   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1811   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1812                                                    Op, Ty);
1813   UniqueSCEVs.InsertNode(S, IP);
1814   addToLoopUseLists(S);
1815   return S;
1816 }
1817 
1818 const SCEV *
1819 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1820   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1821          "This is not an extending conversion!");
1822   assert(isSCEVable(Ty) &&
1823          "This is not a conversion to a SCEVable type!");
1824   Ty = getEffectiveSCEVType(Ty);
1825 
1826   // Fold if the operand is constant.
1827   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1828     return getConstant(
1829       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1830 
1831   // sext(sext(x)) --> sext(x)
1832   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1833     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1834 
1835   // sext(zext(x)) --> zext(x)
1836   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1837     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1838 
1839   // Before doing any expensive analysis, check to see if we've already
1840   // computed a SCEV for this Op and Ty.
1841   FoldingSetNodeID ID;
1842   ID.AddInteger(scSignExtend);
1843   ID.AddPointer(Op);
1844   ID.AddPointer(Ty);
1845   void *IP = nullptr;
1846   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1847   // Limit recursion depth.
1848   if (Depth > MaxExtDepth) {
1849     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1850                                                      Op, Ty);
1851     UniqueSCEVs.InsertNode(S, IP);
1852     addToLoopUseLists(S);
1853     return S;
1854   }
1855 
1856   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1857   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1858     // It's possible the bits taken off by the truncate were all sign bits. If
1859     // so, we should be able to simplify this further.
1860     const SCEV *X = ST->getOperand();
1861     ConstantRange CR = getSignedRange(X);
1862     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1863     unsigned NewBits = getTypeSizeInBits(Ty);
1864     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1865             CR.sextOrTrunc(NewBits)))
1866       return getTruncateOrSignExtend(X, Ty);
1867   }
1868 
1869   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1870   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1871     if (SA->getNumOperands() == 2) {
1872       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1873       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1874       if (SMul && SC1) {
1875         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1876           const APInt &C1 = SC1->getAPInt();
1877           const APInt &C2 = SC2->getAPInt();
1878           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1879               C2.ugt(C1) && C2.isPowerOf2())
1880             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1881                               getSignExtendExpr(SMul, Ty, Depth + 1),
1882                               SCEV::FlagAnyWrap, Depth + 1);
1883         }
1884       }
1885     }
1886 
1887     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1888     if (SA->hasNoSignedWrap()) {
1889       // If the addition does not sign overflow then we can, by definition,
1890       // commute the sign extension with the addition operation.
1891       SmallVector<const SCEV *, 4> Ops;
1892       for (const auto *Op : SA->operands())
1893         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1894       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1895     }
1896   }
1897   // If the input value is a chrec scev, and we can prove that the value
1898   // did not overflow the old, smaller, value, we can sign extend all of the
1899   // operands (often constants).  This allows analysis of something like
1900   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1901   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1902     if (AR->isAffine()) {
1903       const SCEV *Start = AR->getStart();
1904       const SCEV *Step = AR->getStepRecurrence(*this);
1905       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1906       const Loop *L = AR->getLoop();
1907 
1908       if (!AR->hasNoSignedWrap()) {
1909         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1910         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1911       }
1912 
1913       // If we have special knowledge that this addrec won't overflow,
1914       // we don't need to do any further analysis.
1915       if (AR->hasNoSignedWrap())
1916         return getAddRecExpr(
1917             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1918             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1919 
1920       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1921       // Note that this serves two purposes: It filters out loops that are
1922       // simply not analyzable, and it covers the case where this code is
1923       // being called from within backedge-taken count analysis, such that
1924       // attempting to ask for the backedge-taken count would likely result
1925       // in infinite recursion. In the later case, the analysis code will
1926       // cope with a conservative value, and it will take care to purge
1927       // that value once it has finished.
1928       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1929       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1930         // Manually compute the final value for AR, checking for
1931         // overflow.
1932 
1933         // Check whether the backedge-taken count can be losslessly casted to
1934         // the addrec's type. The count is always unsigned.
1935         const SCEV *CastedMaxBECount =
1936           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1937         const SCEV *RecastedMaxBECount =
1938           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1939         if (MaxBECount == RecastedMaxBECount) {
1940           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1941           // Check whether Start+Step*MaxBECount has no signed overflow.
1942           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1943                                         SCEV::FlagAnyWrap, Depth + 1);
1944           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1945                                                           SCEV::FlagAnyWrap,
1946                                                           Depth + 1),
1947                                                WideTy, Depth + 1);
1948           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1949           const SCEV *WideMaxBECount =
1950             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1951           const SCEV *OperandExtendedAdd =
1952             getAddExpr(WideStart,
1953                        getMulExpr(WideMaxBECount,
1954                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1955                                   SCEV::FlagAnyWrap, Depth + 1),
1956                        SCEV::FlagAnyWrap, Depth + 1);
1957           if (SAdd == OperandExtendedAdd) {
1958             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1959             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1960             // Return the expression with the addrec on the outside.
1961             return getAddRecExpr(
1962                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1963                                                          Depth + 1),
1964                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1965                 AR->getNoWrapFlags());
1966           }
1967           // Similar to above, only this time treat the step value as unsigned.
1968           // This covers loops that count up with an unsigned step.
1969           OperandExtendedAdd =
1970             getAddExpr(WideStart,
1971                        getMulExpr(WideMaxBECount,
1972                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1973                                   SCEV::FlagAnyWrap, Depth + 1),
1974                        SCEV::FlagAnyWrap, Depth + 1);
1975           if (SAdd == OperandExtendedAdd) {
1976             // If AR wraps around then
1977             //
1978             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1979             // => SAdd != OperandExtendedAdd
1980             //
1981             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1982             // (SAdd == OperandExtendedAdd => AR is NW)
1983 
1984             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1985 
1986             // Return the expression with the addrec on the outside.
1987             return getAddRecExpr(
1988                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1989                                                          Depth + 1),
1990                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1991                 AR->getNoWrapFlags());
1992           }
1993         }
1994       }
1995 
1996       // Normally, in the cases we can prove no-overflow via a
1997       // backedge guarding condition, we can also compute a backedge
1998       // taken count for the loop.  The exceptions are assumptions and
1999       // guards present in the loop -- SCEV is not great at exploiting
2000       // these to compute max backedge taken counts, but can still use
2001       // these to prove lack of overflow.  Use this fact to avoid
2002       // doing extra work that may not pay off.
2003 
2004       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2005           !AC.assumptions().empty()) {
2006         // If the backedge is guarded by a comparison with the pre-inc
2007         // value the addrec is safe. Also, if the entry is guarded by
2008         // a comparison with the start value and the backedge is
2009         // guarded by a comparison with the post-inc value, the addrec
2010         // is safe.
2011         ICmpInst::Predicate Pred;
2012         const SCEV *OverflowLimit =
2013             getSignedOverflowLimitForStep(Step, &Pred, this);
2014         if (OverflowLimit &&
2015             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2016              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2017           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2018           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2019           return getAddRecExpr(
2020               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2021               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2022         }
2023       }
2024 
2025       // If Start and Step are constants, check if we can apply this
2026       // transformation:
2027       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2028       auto *SC1 = dyn_cast<SCEVConstant>(Start);
2029       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2030       if (SC1 && SC2) {
2031         const APInt &C1 = SC1->getAPInt();
2032         const APInt &C2 = SC2->getAPInt();
2033         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2034             C2.isPowerOf2()) {
2035           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2036           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2037                                             AR->getNoWrapFlags());
2038           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2039                             SCEV::FlagAnyWrap, Depth + 1);
2040         }
2041       }
2042 
2043       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2044         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2045         return getAddRecExpr(
2046             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2047             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2048       }
2049     }
2050 
2051   // If the input value is provably positive and we could not simplify
2052   // away the sext build a zext instead.
2053   if (isKnownNonNegative(Op))
2054     return getZeroExtendExpr(Op, Ty, Depth + 1);
2055 
2056   // The cast wasn't folded; create an explicit cast node.
2057   // Recompute the insert position, as it may have been invalidated.
2058   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2059   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2060                                                    Op, Ty);
2061   UniqueSCEVs.InsertNode(S, IP);
2062   addToLoopUseLists(S);
2063   return S;
2064 }
2065 
2066 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2067 /// unspecified bits out to the given type.
2068 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2069                                               Type *Ty) {
2070   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2071          "This is not an extending conversion!");
2072   assert(isSCEVable(Ty) &&
2073          "This is not a conversion to a SCEVable type!");
2074   Ty = getEffectiveSCEVType(Ty);
2075 
2076   // Sign-extend negative constants.
2077   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2078     if (SC->getAPInt().isNegative())
2079       return getSignExtendExpr(Op, Ty);
2080 
2081   // Peel off a truncate cast.
2082   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2083     const SCEV *NewOp = T->getOperand();
2084     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2085       return getAnyExtendExpr(NewOp, Ty);
2086     return getTruncateOrNoop(NewOp, Ty);
2087   }
2088 
2089   // Next try a zext cast. If the cast is folded, use it.
2090   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2091   if (!isa<SCEVZeroExtendExpr>(ZExt))
2092     return ZExt;
2093 
2094   // Next try a sext cast. If the cast is folded, use it.
2095   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2096   if (!isa<SCEVSignExtendExpr>(SExt))
2097     return SExt;
2098 
2099   // Force the cast to be folded into the operands of an addrec.
2100   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2101     SmallVector<const SCEV *, 4> Ops;
2102     for (const SCEV *Op : AR->operands())
2103       Ops.push_back(getAnyExtendExpr(Op, Ty));
2104     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2105   }
2106 
2107   // If the expression is obviously signed, use the sext cast value.
2108   if (isa<SCEVSMaxExpr>(Op))
2109     return SExt;
2110 
2111   // Absent any other information, use the zext cast value.
2112   return ZExt;
2113 }
2114 
2115 /// Process the given Ops list, which is a list of operands to be added under
2116 /// the given scale, update the given map. This is a helper function for
2117 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2118 /// that would form an add expression like this:
2119 ///
2120 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2121 ///
2122 /// where A and B are constants, update the map with these values:
2123 ///
2124 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2125 ///
2126 /// and add 13 + A*B*29 to AccumulatedConstant.
2127 /// This will allow getAddRecExpr to produce this:
2128 ///
2129 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2130 ///
2131 /// This form often exposes folding opportunities that are hidden in
2132 /// the original operand list.
2133 ///
2134 /// Return true iff it appears that any interesting folding opportunities
2135 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2136 /// the common case where no interesting opportunities are present, and
2137 /// is also used as a check to avoid infinite recursion.
2138 static bool
2139 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2140                              SmallVectorImpl<const SCEV *> &NewOps,
2141                              APInt &AccumulatedConstant,
2142                              const SCEV *const *Ops, size_t NumOperands,
2143                              const APInt &Scale,
2144                              ScalarEvolution &SE) {
2145   bool Interesting = false;
2146 
2147   // Iterate over the add operands. They are sorted, with constants first.
2148   unsigned i = 0;
2149   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2150     ++i;
2151     // Pull a buried constant out to the outside.
2152     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2153       Interesting = true;
2154     AccumulatedConstant += Scale * C->getAPInt();
2155   }
2156 
2157   // Next comes everything else. We're especially interested in multiplies
2158   // here, but they're in the middle, so just visit the rest with one loop.
2159   for (; i != NumOperands; ++i) {
2160     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2161     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2162       APInt NewScale =
2163           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2164       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2165         // A multiplication of a constant with another add; recurse.
2166         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2167         Interesting |=
2168           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2169                                        Add->op_begin(), Add->getNumOperands(),
2170                                        NewScale, SE);
2171       } else {
2172         // A multiplication of a constant with some other value. Update
2173         // the map.
2174         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2175         const SCEV *Key = SE.getMulExpr(MulOps);
2176         auto Pair = M.insert({Key, NewScale});
2177         if (Pair.second) {
2178           NewOps.push_back(Pair.first->first);
2179         } else {
2180           Pair.first->second += NewScale;
2181           // The map already had an entry for this value, which may indicate
2182           // a folding opportunity.
2183           Interesting = true;
2184         }
2185       }
2186     } else {
2187       // An ordinary operand. Update the map.
2188       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2189           M.insert({Ops[i], Scale});
2190       if (Pair.second) {
2191         NewOps.push_back(Pair.first->first);
2192       } else {
2193         Pair.first->second += Scale;
2194         // The map already had an entry for this value, which may indicate
2195         // a folding opportunity.
2196         Interesting = true;
2197       }
2198     }
2199   }
2200 
2201   return Interesting;
2202 }
2203 
2204 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2205 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2206 // can't-overflow flags for the operation if possible.
2207 static SCEV::NoWrapFlags
2208 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2209                       const SmallVectorImpl<const SCEV *> &Ops,
2210                       SCEV::NoWrapFlags Flags) {
2211   using namespace std::placeholders;
2212 
2213   using OBO = OverflowingBinaryOperator;
2214 
2215   bool CanAnalyze =
2216       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2217   (void)CanAnalyze;
2218   assert(CanAnalyze && "don't call from other places!");
2219 
2220   SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2221   SCEV::NoWrapFlags SignOrUnsignWrap = Flags & SignOrUnsignMask;
2222 
2223   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2224   auto IsKnownNonNegative = [&](const SCEV *S) {
2225     return SE->isKnownNonNegative(S);
2226   };
2227 
2228   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2229     Flags |= SignOrUnsignMask;
2230 
2231   SignOrUnsignWrap = Flags & SignOrUnsignMask;
2232 
2233   if (SignOrUnsignWrap != SignOrUnsignMask &&
2234       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2235       isa<SCEVConstant>(Ops[0])) {
2236 
2237     auto Opcode = [&] {
2238       switch (Type) {
2239       case scAddExpr:
2240         return Instruction::Add;
2241       case scMulExpr:
2242         return Instruction::Mul;
2243       default:
2244         llvm_unreachable("Unexpected SCEV op.");
2245       }
2246     }();
2247 
2248     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2249 
2250     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2251     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2252       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2253           Opcode, C, OBO::NoSignedWrap);
2254       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2255         Flags |= SCEV::FlagNSW;
2256     }
2257 
2258     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2259     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2260       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2261           Instruction::Add, C, OBO::NoUnsignedWrap);
2262       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2263         Flags |= SCEV::FlagNUW;
2264     }
2265   }
2266 
2267   return Flags;
2268 }
2269 
2270 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2271   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2272 }
2273 
2274 /// Get a canonical add expression, or something simpler if possible.
2275 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2276                                         SCEV::NoWrapFlags Flags,
2277                                         unsigned Depth) {
2278   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2279          "only nuw or nsw allowed");
2280   assert(!Ops.empty() && "Cannot get empty add!");
2281   if (Ops.size() == 1) return Ops[0];
2282 #ifndef NDEBUG
2283   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2284   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2285     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2286            "SCEVAddExpr operand types don't match!");
2287 #endif
2288 
2289   // Sort by complexity, this groups all similar expression types together.
2290   GroupByComplexity(Ops, &LI, DT);
2291 
2292   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2293 
2294   // If there are any constants, fold them together.
2295   unsigned Idx = 0;
2296   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2297     ++Idx;
2298     assert(Idx < Ops.size());
2299     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2300       // We found two constants, fold them together!
2301       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2302       if (Ops.size() == 2) return Ops[0];
2303       Ops.erase(Ops.begin()+1);  // Erase the folded element
2304       LHSC = cast<SCEVConstant>(Ops[0]);
2305     }
2306 
2307     // If we are left with a constant zero being added, strip it off.
2308     if (LHSC->getValue()->isZero()) {
2309       Ops.erase(Ops.begin());
2310       --Idx;
2311     }
2312 
2313     if (Ops.size() == 1) return Ops[0];
2314   }
2315 
2316   // Limit recursion calls depth.
2317   if (Depth > MaxArithDepth)
2318     return getOrCreateAddExpr(Ops, Flags);
2319 
2320   // Okay, check to see if the same value occurs in the operand list more than
2321   // once.  If so, merge them together into an multiply expression.  Since we
2322   // sorted the list, these values are required to be adjacent.
2323   Type *Ty = Ops[0]->getType();
2324   bool FoundMatch = false;
2325   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2326     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2327       // Scan ahead to count how many equal operands there are.
2328       unsigned Count = 2;
2329       while (i+Count != e && Ops[i+Count] == Ops[i])
2330         ++Count;
2331       // Merge the values into a multiply.
2332       const SCEV *Scale = getConstant(Ty, Count);
2333       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2334       if (Ops.size() == Count)
2335         return Mul;
2336       Ops[i] = Mul;
2337       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2338       --i; e -= Count - 1;
2339       FoundMatch = true;
2340     }
2341   if (FoundMatch)
2342     return getAddExpr(Ops, Flags, Depth + 1);
2343 
2344   // Check for truncates. If all the operands are truncated from the same
2345   // type, see if factoring out the truncate would permit the result to be
2346   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2347   // if the contents of the resulting outer trunc fold to something simple.
2348   auto FindTruncSrcType = [&]() -> Type * {
2349     // We're ultimately looking to fold an addrec of truncs and muls of only
2350     // constants and truncs, so if we find any other types of SCEV
2351     // as operands of the addrec then we bail and return nullptr here.
2352     // Otherwise, we return the type of the operand of a trunc that we find.
2353     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2354       return T->getOperand()->getType();
2355     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2356       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2357       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2358         return T->getOperand()->getType();
2359     }
2360     return nullptr;
2361   };
2362   if (auto *SrcType = FindTruncSrcType()) {
2363     SmallVector<const SCEV *, 8> LargeOps;
2364     bool Ok = true;
2365     // Check all the operands to see if they can be represented in the
2366     // source type of the truncate.
2367     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2368       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2369         if (T->getOperand()->getType() != SrcType) {
2370           Ok = false;
2371           break;
2372         }
2373         LargeOps.push_back(T->getOperand());
2374       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2375         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2376       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2377         SmallVector<const SCEV *, 8> LargeMulOps;
2378         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2379           if (const SCEVTruncateExpr *T =
2380                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2381             if (T->getOperand()->getType() != SrcType) {
2382               Ok = false;
2383               break;
2384             }
2385             LargeMulOps.push_back(T->getOperand());
2386           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2387             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2388           } else {
2389             Ok = false;
2390             break;
2391           }
2392         }
2393         if (Ok)
2394           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2395       } else {
2396         Ok = false;
2397         break;
2398       }
2399     }
2400     if (Ok) {
2401       // Evaluate the expression in the larger type.
2402       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2403       // If it folds to something simple, use it. Otherwise, don't.
2404       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2405         return getTruncateExpr(Fold, Ty);
2406     }
2407   }
2408 
2409   // Skip past any other cast SCEVs.
2410   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2411     ++Idx;
2412 
2413   // If there are add operands they would be next.
2414   if (Idx < Ops.size()) {
2415     bool DeletedAdd = false;
2416     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2417       if (Ops.size() > AddOpsInlineThreshold ||
2418           Add->getNumOperands() > AddOpsInlineThreshold)
2419         break;
2420       // If we have an add, expand the add operands onto the end of the operands
2421       // list.
2422       Ops.erase(Ops.begin()+Idx);
2423       Ops.append(Add->op_begin(), Add->op_end());
2424       DeletedAdd = true;
2425     }
2426 
2427     // If we deleted at least one add, we added operands to the end of the list,
2428     // and they are not necessarily sorted.  Recurse to resort and resimplify
2429     // any operands we just acquired.
2430     if (DeletedAdd)
2431       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2432   }
2433 
2434   // Skip over the add expression until we get to a multiply.
2435   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2436     ++Idx;
2437 
2438   // Check to see if there are any folding opportunities present with
2439   // operands multiplied by constant values.
2440   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2441     uint64_t BitWidth = getTypeSizeInBits(Ty);
2442     DenseMap<const SCEV *, APInt> M;
2443     SmallVector<const SCEV *, 8> NewOps;
2444     APInt AccumulatedConstant(BitWidth, 0);
2445     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2446                                      Ops.data(), Ops.size(),
2447                                      APInt(BitWidth, 1), *this)) {
2448       struct APIntCompare {
2449         bool operator()(const APInt &LHS, const APInt &RHS) const {
2450           return LHS.ult(RHS);
2451         }
2452       };
2453 
2454       // Some interesting folding opportunity is present, so its worthwhile to
2455       // re-generate the operands list. Group the operands by constant scale,
2456       // to avoid multiplying by the same constant scale multiple times.
2457       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2458       for (const SCEV *NewOp : NewOps)
2459         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2460       // Re-generate the operands list.
2461       Ops.clear();
2462       if (AccumulatedConstant != 0)
2463         Ops.push_back(getConstant(AccumulatedConstant));
2464       for (auto &MulOp : MulOpLists)
2465         if (MulOp.first != 0)
2466           Ops.push_back(getMulExpr(
2467               getConstant(MulOp.first),
2468               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2469               SCEV::FlagAnyWrap, Depth + 1));
2470       if (Ops.empty())
2471         return getZero(Ty);
2472       if (Ops.size() == 1)
2473         return Ops[0];
2474       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2475     }
2476   }
2477 
2478   // If we are adding something to a multiply expression, make sure the
2479   // something is not already an operand of the multiply.  If so, merge it into
2480   // the multiply.
2481   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2482     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2483     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2484       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2485       if (isa<SCEVConstant>(MulOpSCEV))
2486         continue;
2487       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2488         if (MulOpSCEV == Ops[AddOp]) {
2489           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2490           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2491           if (Mul->getNumOperands() != 2) {
2492             // If the multiply has more than two operands, we must get the
2493             // Y*Z term.
2494             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2495                                                 Mul->op_begin()+MulOp);
2496             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2497             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2498           }
2499           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2500           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2501           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2502                                             SCEV::FlagAnyWrap, Depth + 1);
2503           if (Ops.size() == 2) return OuterMul;
2504           if (AddOp < Idx) {
2505             Ops.erase(Ops.begin()+AddOp);
2506             Ops.erase(Ops.begin()+Idx-1);
2507           } else {
2508             Ops.erase(Ops.begin()+Idx);
2509             Ops.erase(Ops.begin()+AddOp-1);
2510           }
2511           Ops.push_back(OuterMul);
2512           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2513         }
2514 
2515       // Check this multiply against other multiplies being added together.
2516       for (unsigned OtherMulIdx = Idx+1;
2517            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2518            ++OtherMulIdx) {
2519         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2520         // If MulOp occurs in OtherMul, we can fold the two multiplies
2521         // together.
2522         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2523              OMulOp != e; ++OMulOp)
2524           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2525             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2526             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2527             if (Mul->getNumOperands() != 2) {
2528               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2529                                                   Mul->op_begin()+MulOp);
2530               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2531               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2532             }
2533             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2534             if (OtherMul->getNumOperands() != 2) {
2535               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2536                                                   OtherMul->op_begin()+OMulOp);
2537               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2538               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2539             }
2540             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2541             const SCEV *InnerMulSum =
2542                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2543             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2544                                               SCEV::FlagAnyWrap, Depth + 1);
2545             if (Ops.size() == 2) return OuterMul;
2546             Ops.erase(Ops.begin()+Idx);
2547             Ops.erase(Ops.begin()+OtherMulIdx-1);
2548             Ops.push_back(OuterMul);
2549             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2550           }
2551       }
2552     }
2553   }
2554 
2555   // If there are any add recurrences in the operands list, see if any other
2556   // added values are loop invariant.  If so, we can fold them into the
2557   // recurrence.
2558   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2559     ++Idx;
2560 
2561   // Scan over all recurrences, trying to fold loop invariants into them.
2562   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2563     // Scan all of the other operands to this add and add them to the vector if
2564     // they are loop invariant w.r.t. the recurrence.
2565     SmallVector<const SCEV *, 8> LIOps;
2566     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2567     const Loop *AddRecLoop = AddRec->getLoop();
2568     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2569       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2570         LIOps.push_back(Ops[i]);
2571         Ops.erase(Ops.begin()+i);
2572         --i; --e;
2573       }
2574 
2575     // If we found some loop invariants, fold them into the recurrence.
2576     if (!LIOps.empty()) {
2577       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2578       LIOps.push_back(AddRec->getStart());
2579 
2580       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2581                                              AddRec->op_end());
2582       // This follows from the fact that the no-wrap flags on the outer add
2583       // expression are applicable on the 0th iteration, when the add recurrence
2584       // will be equal to its start value.
2585       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2586 
2587       // Build the new addrec. Propagate the NUW and NSW flags if both the
2588       // outer add and the inner addrec are guaranteed to have no overflow.
2589       // Always propagate NW.
2590       Flags = AddRec->getNoWrapFlags(Flags | SCEV::FlagNW);
2591       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2592 
2593       // If all of the other operands were loop invariant, we are done.
2594       if (Ops.size() == 1) return NewRec;
2595 
2596       // Otherwise, add the folded AddRec by the non-invariant parts.
2597       for (unsigned i = 0;; ++i)
2598         if (Ops[i] == AddRec) {
2599           Ops[i] = NewRec;
2600           break;
2601         }
2602       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2603     }
2604 
2605     // Okay, if there weren't any loop invariants to be folded, check to see if
2606     // there are multiple AddRec's with the same loop induction variable being
2607     // added together.  If so, we can fold them.
2608     for (unsigned OtherIdx = Idx+1;
2609          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2610          ++OtherIdx) {
2611       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2612       // so that the 1st found AddRecExpr is dominated by all others.
2613       assert(DT.dominates(
2614            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2615            AddRec->getLoop()->getHeader()) &&
2616         "AddRecExprs are not sorted in reverse dominance order?");
2617       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2618         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2619         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2620                                                AddRec->op_end());
2621         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2622              ++OtherIdx) {
2623           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2624           if (OtherAddRec->getLoop() == AddRecLoop) {
2625             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2626                  i != e; ++i) {
2627               if (i >= AddRecOps.size()) {
2628                 AddRecOps.append(OtherAddRec->op_begin()+i,
2629                                  OtherAddRec->op_end());
2630                 break;
2631               }
2632               SmallVector<const SCEV *, 2> TwoOps = {
2633                   AddRecOps[i], OtherAddRec->getOperand(i)};
2634               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2635             }
2636             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2637           }
2638         }
2639         // Step size has changed, so we cannot guarantee no self-wraparound.
2640         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2641         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2642       }
2643     }
2644 
2645     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2646     // next one.
2647   }
2648 
2649   // Okay, it looks like we really DO need an add expr.  Check to see if we
2650   // already have one, otherwise create a new one.
2651   return getOrCreateAddExpr(Ops, Flags);
2652 }
2653 
2654 const SCEV *
2655 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2656                                     SCEV::NoWrapFlags Flags) {
2657   FoldingSetNodeID ID;
2658   ID.AddInteger(scAddExpr);
2659   for (const SCEV *Op : Ops)
2660     ID.AddPointer(Op);
2661   void *IP = nullptr;
2662   SCEVAddExpr *S =
2663       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2664   if (!S) {
2665     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2666     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2667     S = new (SCEVAllocator)
2668         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2669     UniqueSCEVs.InsertNode(S, IP);
2670     addToLoopUseLists(S);
2671   }
2672   S->setNoWrapFlags(Flags);
2673   return S;
2674 }
2675 
2676 const SCEV *
2677 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2678                                     SCEV::NoWrapFlags Flags) {
2679   FoldingSetNodeID ID;
2680   ID.AddInteger(scMulExpr);
2681   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2682     ID.AddPointer(Ops[i]);
2683   void *IP = nullptr;
2684   SCEVMulExpr *S =
2685     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2686   if (!S) {
2687     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2688     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2689     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2690                                         O, Ops.size());
2691     UniqueSCEVs.InsertNode(S, IP);
2692     addToLoopUseLists(S);
2693   }
2694   S->setNoWrapFlags(Flags);
2695   return S;
2696 }
2697 
2698 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2699   uint64_t k = i*j;
2700   if (j > 1 && k / j != i) Overflow = true;
2701   return k;
2702 }
2703 
2704 /// Compute the result of "n choose k", the binomial coefficient.  If an
2705 /// intermediate computation overflows, Overflow will be set and the return will
2706 /// be garbage. Overflow is not cleared on absence of overflow.
2707 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2708   // We use the multiplicative formula:
2709   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2710   // At each iteration, we take the n-th term of the numeral and divide by the
2711   // (k-n)th term of the denominator.  This division will always produce an
2712   // integral result, and helps reduce the chance of overflow in the
2713   // intermediate computations. However, we can still overflow even when the
2714   // final result would fit.
2715 
2716   if (n == 0 || n == k) return 1;
2717   if (k > n) return 0;
2718 
2719   if (k > n/2)
2720     k = n-k;
2721 
2722   uint64_t r = 1;
2723   for (uint64_t i = 1; i <= k; ++i) {
2724     r = umul_ov(r, n-(i-1), Overflow);
2725     r /= i;
2726   }
2727   return r;
2728 }
2729 
2730 /// Determine if any of the operands in this SCEV are a constant or if
2731 /// any of the add or multiply expressions in this SCEV contain a constant.
2732 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2733   struct FindConstantInAddMulChain {
2734     bool FoundConstant = false;
2735 
2736     bool follow(const SCEV *S) {
2737       FoundConstant |= isa<SCEVConstant>(S);
2738       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2739     }
2740 
2741     bool isDone() const {
2742       return FoundConstant;
2743     }
2744   };
2745 
2746   FindConstantInAddMulChain F;
2747   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2748   ST.visitAll(StartExpr);
2749   return F.FoundConstant;
2750 }
2751 
2752 /// Get a canonical multiply expression, or something simpler if possible.
2753 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2754                                         SCEV::NoWrapFlags Flags,
2755                                         unsigned Depth) {
2756   assert(Flags == (Flags & (SCEV::FlagNUW | SCEV::FlagNSW)) &&
2757          "only nuw or nsw allowed");
2758   assert(!Ops.empty() && "Cannot get empty mul!");
2759   if (Ops.size() == 1) return Ops[0];
2760 #ifndef NDEBUG
2761   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2762   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2763     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2764            "SCEVMulExpr operand types don't match!");
2765 #endif
2766 
2767   // Sort by complexity, this groups all similar expression types together.
2768   GroupByComplexity(Ops, &LI, DT);
2769 
2770   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2771 
2772   // Limit recursion calls depth.
2773   if (Depth > MaxArithDepth)
2774     return getOrCreateMulExpr(Ops, Flags);
2775 
2776   // If there are any constants, fold them together.
2777   unsigned Idx = 0;
2778   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2779 
2780     if (Ops.size() == 2)
2781       // C1*(C2+V) -> C1*C2 + C1*V
2782       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2783         // If any of Add's ops are Adds or Muls with a constant, apply this
2784         // transformation as well.
2785         //
2786         // TODO: There are some cases where this transformation is not
2787         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2788         // this transformation should be narrowed down.
2789         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2790           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2791                                        SCEV::FlagAnyWrap, Depth + 1),
2792                             getMulExpr(LHSC, Add->getOperand(1),
2793                                        SCEV::FlagAnyWrap, Depth + 1),
2794                             SCEV::FlagAnyWrap, Depth + 1);
2795 
2796     ++Idx;
2797     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2798       // We found two constants, fold them together!
2799       ConstantInt *Fold =
2800           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2801       Ops[0] = getConstant(Fold);
2802       Ops.erase(Ops.begin()+1);  // Erase the folded element
2803       if (Ops.size() == 1) return Ops[0];
2804       LHSC = cast<SCEVConstant>(Ops[0]);
2805     }
2806 
2807     // If we are left with a constant one being multiplied, strip it off.
2808     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2809       Ops.erase(Ops.begin());
2810       --Idx;
2811     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2812       // If we have a multiply of zero, it will always be zero.
2813       return Ops[0];
2814     } else if (Ops[0]->isAllOnesValue()) {
2815       // If we have a mul by -1 of an add, try distributing the -1 among the
2816       // add operands.
2817       if (Ops.size() == 2) {
2818         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2819           SmallVector<const SCEV *, 4> NewOps;
2820           bool AnyFolded = false;
2821           for (const SCEV *AddOp : Add->operands()) {
2822             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2823                                          Depth + 1);
2824             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2825             NewOps.push_back(Mul);
2826           }
2827           if (AnyFolded)
2828             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2829         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2830           // Negation preserves a recurrence's no self-wrap property.
2831           SmallVector<const SCEV *, 4> Operands;
2832           for (const SCEV *AddRecOp : AddRec->operands())
2833             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2834                                           Depth + 1));
2835 
2836           return getAddRecExpr(Operands, AddRec->getLoop(),
2837                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2838         }
2839       }
2840     }
2841 
2842     if (Ops.size() == 1)
2843       return Ops[0];
2844   }
2845 
2846   // Skip over the add expression until we get to a multiply.
2847   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2848     ++Idx;
2849 
2850   // If there are mul operands inline them all into this expression.
2851   if (Idx < Ops.size()) {
2852     bool DeletedMul = false;
2853     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2854       if (Ops.size() > MulOpsInlineThreshold)
2855         break;
2856       // If we have an mul, expand the mul operands onto the end of the
2857       // operands list.
2858       Ops.erase(Ops.begin()+Idx);
2859       Ops.append(Mul->op_begin(), Mul->op_end());
2860       DeletedMul = true;
2861     }
2862 
2863     // If we deleted at least one mul, we added operands to the end of the
2864     // list, and they are not necessarily sorted.  Recurse to resort and
2865     // resimplify any operands we just acquired.
2866     if (DeletedMul)
2867       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2868   }
2869 
2870   // If there are any add recurrences in the operands list, see if any other
2871   // added values are loop invariant.  If so, we can fold them into the
2872   // recurrence.
2873   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2874     ++Idx;
2875 
2876   // Scan over all recurrences, trying to fold loop invariants into them.
2877   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2878     // Scan all of the other operands to this mul and add them to the vector
2879     // if they are loop invariant w.r.t. the recurrence.
2880     SmallVector<const SCEV *, 8> LIOps;
2881     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2882     const Loop *AddRecLoop = AddRec->getLoop();
2883     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2884       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2885         LIOps.push_back(Ops[i]);
2886         Ops.erase(Ops.begin()+i);
2887         --i; --e;
2888       }
2889 
2890     // If we found some loop invariants, fold them into the recurrence.
2891     if (!LIOps.empty()) {
2892       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2893       SmallVector<const SCEV *, 4> NewOps;
2894       NewOps.reserve(AddRec->getNumOperands());
2895       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2896       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2897         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2898                                     SCEV::FlagAnyWrap, Depth + 1));
2899 
2900       // Build the new addrec. Propagate the NUW and NSW flags if both the
2901       // outer mul and the inner addrec are guaranteed to have no overflow.
2902       //
2903       // No self-wrap cannot be guaranteed after changing the step size, but
2904       // will be inferred if either NUW or NSW is true.
2905       Flags = AddRec->getNoWrapFlags(Flags & ~SCEV::FlagNW);
2906       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2907 
2908       // If all of the other operands were loop invariant, we are done.
2909       if (Ops.size() == 1) return NewRec;
2910 
2911       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2912       for (unsigned i = 0;; ++i)
2913         if (Ops[i] == AddRec) {
2914           Ops[i] = NewRec;
2915           break;
2916         }
2917       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2918     }
2919 
2920     // Okay, if there weren't any loop invariants to be folded, check to see
2921     // if there are multiple AddRec's with the same loop induction variable
2922     // being multiplied together.  If so, we can fold them.
2923 
2924     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2925     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2926     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2927     //   ]]],+,...up to x=2n}.
2928     // Note that the arguments to choose() are always integers with values
2929     // known at compile time, never SCEV objects.
2930     //
2931     // The implementation avoids pointless extra computations when the two
2932     // addrec's are of different length (mathematically, it's equivalent to
2933     // an infinite stream of zeros on the right).
2934     bool OpsModified = false;
2935     for (unsigned OtherIdx = Idx+1;
2936          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2937          ++OtherIdx) {
2938       const SCEVAddRecExpr *OtherAddRec =
2939         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2940       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2941         continue;
2942 
2943       // Limit max number of arguments to avoid creation of unreasonably big
2944       // SCEVAddRecs with very complex operands.
2945       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2946           MaxAddRecSize)
2947         continue;
2948 
2949       bool Overflow = false;
2950       Type *Ty = AddRec->getType();
2951       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2952       SmallVector<const SCEV*, 7> AddRecOps;
2953       for (int x = 0, xe = AddRec->getNumOperands() +
2954              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2955         const SCEV *Term = getZero(Ty);
2956         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2957           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2958           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2959                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2960                z < ze && !Overflow; ++z) {
2961             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2962             uint64_t Coeff;
2963             if (LargerThan64Bits)
2964               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2965             else
2966               Coeff = Coeff1*Coeff2;
2967             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2968             const SCEV *Term1 = AddRec->getOperand(y-z);
2969             const SCEV *Term2 = OtherAddRec->getOperand(z);
2970             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2971                                                SCEV::FlagAnyWrap, Depth + 1),
2972                               SCEV::FlagAnyWrap, Depth + 1);
2973           }
2974         }
2975         AddRecOps.push_back(Term);
2976       }
2977       if (!Overflow) {
2978         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2979                                               SCEV::FlagAnyWrap);
2980         if (Ops.size() == 2) return NewAddRec;
2981         Ops[Idx] = NewAddRec;
2982         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2983         OpsModified = true;
2984         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2985         if (!AddRec)
2986           break;
2987       }
2988     }
2989     if (OpsModified)
2990       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2991 
2992     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2993     // next one.
2994   }
2995 
2996   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2997   // already have one, otherwise create a new one.
2998   return getOrCreateMulExpr(Ops, Flags);
2999 }
3000 
3001 /// Represents an unsigned remainder expression based on unsigned division.
3002 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3003                                          const SCEV *RHS) {
3004   assert(getEffectiveSCEVType(LHS->getType()) ==
3005          getEffectiveSCEVType(RHS->getType()) &&
3006          "SCEVURemExpr operand types don't match!");
3007 
3008   // Short-circuit easy cases
3009   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3010     // If constant is one, the result is trivial
3011     if (RHSC->getValue()->isOne())
3012       return getZero(LHS->getType()); // X urem 1 --> 0
3013 
3014     // If constant is a power of two, fold into a zext(trunc(LHS)).
3015     if (RHSC->getAPInt().isPowerOf2()) {
3016       Type *FullTy = LHS->getType();
3017       Type *TruncTy =
3018           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3019       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3020     }
3021   }
3022 
3023   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3024   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3025   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3026   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3027 }
3028 
3029 /// Get a canonical unsigned division expression, or something simpler if
3030 /// possible.
3031 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3032                                          const SCEV *RHS) {
3033   assert(getEffectiveSCEVType(LHS->getType()) ==
3034          getEffectiveSCEVType(RHS->getType()) &&
3035          "SCEVUDivExpr operand types don't match!");
3036 
3037   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3038     if (RHSC->getValue()->isOne())
3039       return LHS;                               // X udiv 1 --> x
3040     // If the denominator is zero, the result of the udiv is undefined. Don't
3041     // try to analyze it, because the resolution chosen here may differ from
3042     // the resolution chosen in other parts of the compiler.
3043     if (!RHSC->getValue()->isZero()) {
3044       // Determine if the division can be folded into the operands of
3045       // its operands.
3046       // TODO: Generalize this to non-constants by using known-bits information.
3047       Type *Ty = LHS->getType();
3048       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3049       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3050       // For non-power-of-two values, effectively round the value up to the
3051       // nearest power of two.
3052       if (!RHSC->getAPInt().isPowerOf2())
3053         ++MaxShiftAmt;
3054       IntegerType *ExtTy =
3055         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3056       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3057         if (const SCEVConstant *Step =
3058             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3059           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3060           const APInt &StepInt = Step->getAPInt();
3061           const APInt &DivInt = RHSC->getAPInt();
3062           if (!StepInt.urem(DivInt) &&
3063               getZeroExtendExpr(AR, ExtTy) ==
3064               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3065                             getZeroExtendExpr(Step, ExtTy),
3066                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3067             SmallVector<const SCEV *, 4> Operands;
3068             for (const SCEV *Op : AR->operands())
3069               Operands.push_back(getUDivExpr(Op, RHS));
3070             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3071           }
3072           /// Get a canonical UDivExpr for a recurrence.
3073           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3074           // We can currently only fold X%N if X is constant.
3075           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3076           if (StartC && !DivInt.urem(StepInt) &&
3077               getZeroExtendExpr(AR, ExtTy) ==
3078               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3079                             getZeroExtendExpr(Step, ExtTy),
3080                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3081             const APInt &StartInt = StartC->getAPInt();
3082             const APInt &StartRem = StartInt.urem(StepInt);
3083             if (StartRem != 0)
3084               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3085                                   AR->getLoop(), SCEV::FlagNW);
3086           }
3087         }
3088       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3089       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3090         SmallVector<const SCEV *, 4> Operands;
3091         for (const SCEV *Op : M->operands())
3092           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3093         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3094           // Find an operand that's safely divisible.
3095           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3096             const SCEV *Op = M->getOperand(i);
3097             const SCEV *Div = getUDivExpr(Op, RHSC);
3098             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3099               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3100                                                       M->op_end());
3101               Operands[i] = Div;
3102               return getMulExpr(Operands);
3103             }
3104           }
3105       }
3106 
3107       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3108       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3109         if (auto *DivisorConstant =
3110                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3111           bool Overflow = false;
3112           APInt NewRHS =
3113               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3114           if (Overflow) {
3115             return getConstant(RHSC->getType(), 0, false);
3116           }
3117           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3118         }
3119       }
3120 
3121       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3122       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3123         SmallVector<const SCEV *, 4> Operands;
3124         for (const SCEV *Op : A->operands())
3125           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3126         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3127           Operands.clear();
3128           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3129             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3130             if (isa<SCEVUDivExpr>(Op) ||
3131                 getMulExpr(Op, RHS) != A->getOperand(i))
3132               break;
3133             Operands.push_back(Op);
3134           }
3135           if (Operands.size() == A->getNumOperands())
3136             return getAddExpr(Operands);
3137         }
3138       }
3139 
3140       // Fold if both operands are constant.
3141       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3142         Constant *LHSCV = LHSC->getValue();
3143         Constant *RHSCV = RHSC->getValue();
3144         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3145                                                                    RHSCV)));
3146       }
3147     }
3148   }
3149 
3150   FoldingSetNodeID ID;
3151   ID.AddInteger(scUDivExpr);
3152   ID.AddPointer(LHS);
3153   ID.AddPointer(RHS);
3154   void *IP = nullptr;
3155   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3156   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3157                                              LHS, RHS);
3158   UniqueSCEVs.InsertNode(S, IP);
3159   addToLoopUseLists(S);
3160   return S;
3161 }
3162 
3163 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3164   APInt A = C1->getAPInt().abs();
3165   APInt B = C2->getAPInt().abs();
3166   uint32_t ABW = A.getBitWidth();
3167   uint32_t BBW = B.getBitWidth();
3168 
3169   if (ABW > BBW)
3170     B = B.zext(ABW);
3171   else if (ABW < BBW)
3172     A = A.zext(BBW);
3173 
3174   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3175 }
3176 
3177 /// Get a canonical unsigned division expression, or something simpler if
3178 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3179 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3180 /// it's not exact because the udiv may be clearing bits.
3181 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3182                                               const SCEV *RHS) {
3183   // TODO: we could try to find factors in all sorts of things, but for now we
3184   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3185   // end of this file for inspiration.
3186 
3187   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3188   if (!Mul || !Mul->hasNoUnsignedWrap())
3189     return getUDivExpr(LHS, RHS);
3190 
3191   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3192     // If the mulexpr multiplies by a constant, then that constant must be the
3193     // first element of the mulexpr.
3194     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3195       if (LHSCst == RHSCst) {
3196         SmallVector<const SCEV *, 2> Operands;
3197         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3198         return getMulExpr(Operands);
3199       }
3200 
3201       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3202       // that there's a factor provided by one of the other terms. We need to
3203       // check.
3204       APInt Factor = gcd(LHSCst, RHSCst);
3205       if (!Factor.isIntN(1)) {
3206         LHSCst =
3207             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3208         RHSCst =
3209             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3210         SmallVector<const SCEV *, 2> Operands;
3211         Operands.push_back(LHSCst);
3212         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3213         LHS = getMulExpr(Operands);
3214         RHS = RHSCst;
3215         Mul = dyn_cast<SCEVMulExpr>(LHS);
3216         if (!Mul)
3217           return getUDivExactExpr(LHS, RHS);
3218       }
3219     }
3220   }
3221 
3222   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3223     if (Mul->getOperand(i) == RHS) {
3224       SmallVector<const SCEV *, 2> Operands;
3225       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3226       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3227       return getMulExpr(Operands);
3228     }
3229   }
3230 
3231   return getUDivExpr(LHS, RHS);
3232 }
3233 
3234 /// Get an add recurrence expression for the specified loop.  Simplify the
3235 /// expression as much as possible.
3236 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3237                                            const Loop *L,
3238                                            SCEV::NoWrapFlags Flags) {
3239   SmallVector<const SCEV *, 4> Operands;
3240   Operands.push_back(Start);
3241   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3242     if (StepChrec->getLoop() == L) {
3243       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3244       return getAddRecExpr(Operands, L, Flags & SCEV::FlagNW);
3245     }
3246 
3247   Operands.push_back(Step);
3248   return getAddRecExpr(Operands, L, Flags);
3249 }
3250 
3251 /// Get an add recurrence expression for the specified loop.  Simplify the
3252 /// expression as much as possible.
3253 const SCEV *
3254 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3255                                const Loop *L, SCEV::NoWrapFlags Flags) {
3256   if (Operands.size() == 1) return Operands[0];
3257 #ifndef NDEBUG
3258   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3259   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3260     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3261            "SCEVAddRecExpr operand types don't match!");
3262   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3263     assert(isLoopInvariant(Operands[i], L) &&
3264            "SCEVAddRecExpr operand is not loop-invariant!");
3265 #endif
3266 
3267   if (Operands.back()->isZero()) {
3268     Operands.pop_back();
3269     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3270   }
3271 
3272   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3273   // use that information to infer NUW and NSW flags. However, computing a
3274   // BE count requires calling getAddRecExpr, so we may not yet have a
3275   // meaningful BE count at this point (and if we don't, we'd be stuck
3276   // with a SCEVCouldNotCompute as the cached BE count).
3277 
3278   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3279 
3280   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3281   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3282     const Loop *NestedLoop = NestedAR->getLoop();
3283     if (L->contains(NestedLoop)
3284             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3285             : (!NestedLoop->contains(L) &&
3286                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3287       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3288                                                   NestedAR->op_end());
3289       Operands[0] = NestedAR->getStart();
3290       // AddRecs require their operands be loop-invariant with respect to their
3291       // loops. Don't perform this transformation if it would break this
3292       // requirement.
3293       bool AllInvariant = all_of(
3294           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3295 
3296       if (AllInvariant) {
3297         // Create a recurrence for the outer loop with the same step size.
3298         //
3299         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3300         // inner recurrence has the same property.
3301         SCEV::NoWrapFlags OuterFlags =
3302             Flags & (SCEV::FlagNW | NestedAR->getNoWrapFlags());
3303 
3304         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3305         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3306           return isLoopInvariant(Op, NestedLoop);
3307         });
3308 
3309         if (AllInvariant) {
3310           // Ok, both add recurrences are valid after the transformation.
3311           //
3312           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3313           // the outer recurrence has the same property.
3314           SCEV::NoWrapFlags InnerFlags =
3315               NestedAR->getNoWrapFlags() & (SCEV::FlagNW | Flags);
3316           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3317         }
3318       }
3319       // Reset Operands to its original state.
3320       Operands[0] = NestedAR;
3321     }
3322   }
3323 
3324   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3325   // already have one, otherwise create a new one.
3326   FoldingSetNodeID ID;
3327   ID.AddInteger(scAddRecExpr);
3328   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3329     ID.AddPointer(Operands[i]);
3330   ID.AddPointer(L);
3331   void *IP = nullptr;
3332   SCEVAddRecExpr *S =
3333     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3334   if (!S) {
3335     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3336     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3337     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3338                                            O, Operands.size(), L);
3339     UniqueSCEVs.InsertNode(S, IP);
3340     addToLoopUseLists(S);
3341   }
3342   S->setNoWrapFlags(Flags);
3343   return S;
3344 }
3345 
3346 const SCEV *
3347 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3348                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3349   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3350   // getSCEV(Base)->getType() has the same address space as Base->getType()
3351   // because SCEV::getType() preserves the address space.
3352   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3353   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3354   // instruction to its SCEV, because the Instruction may be guarded by control
3355   // flow and the no-overflow bits may not be valid for the expression in any
3356   // context. This can be fixed similarly to how these flags are handled for
3357   // adds.
3358   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3359                                              : SCEV::FlagAnyWrap;
3360 
3361   const SCEV *TotalOffset = getZero(IntPtrTy);
3362   // The array size is unimportant. The first thing we do on CurTy is getting
3363   // its element type.
3364   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3365   for (const SCEV *IndexExpr : IndexExprs) {
3366     // Compute the (potentially symbolic) offset in bytes for this index.
3367     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3368       // For a struct, add the member offset.
3369       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3370       unsigned FieldNo = Index->getZExtValue();
3371       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3372 
3373       // Add the field offset to the running total offset.
3374       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3375 
3376       // Update CurTy to the type of the field at Index.
3377       CurTy = STy->getTypeAtIndex(Index);
3378     } else {
3379       // Update CurTy to its element type.
3380       CurTy = cast<SequentialType>(CurTy)->getElementType();
3381       // For an array, add the element offset, explicitly scaled.
3382       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3383       // Getelementptr indices are signed.
3384       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3385 
3386       // Multiply the index by the element size to compute the element offset.
3387       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3388 
3389       // Add the element offset to the running total offset.
3390       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3391     }
3392   }
3393 
3394   // Add the total offset from all the GEP indices to the base.
3395   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3396 }
3397 
3398 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3399                                          const SCEV *RHS) {
3400   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3401   return getSMaxExpr(Ops);
3402 }
3403 
3404 const SCEV *
3405 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3406   assert(!Ops.empty() && "Cannot get empty smax!");
3407   if (Ops.size() == 1) return Ops[0];
3408 #ifndef NDEBUG
3409   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3410   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3411     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3412            "SCEVSMaxExpr operand types don't match!");
3413 #endif
3414 
3415   // Sort by complexity, this groups all similar expression types together.
3416   GroupByComplexity(Ops, &LI, DT);
3417 
3418   // If there are any constants, fold them together.
3419   unsigned Idx = 0;
3420   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3421     ++Idx;
3422     assert(Idx < Ops.size());
3423     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3424       // We found two constants, fold them together!
3425       ConstantInt *Fold = ConstantInt::get(
3426           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3427       Ops[0] = getConstant(Fold);
3428       Ops.erase(Ops.begin()+1);  // Erase the folded element
3429       if (Ops.size() == 1) return Ops[0];
3430       LHSC = cast<SCEVConstant>(Ops[0]);
3431     }
3432 
3433     // If we are left with a constant minimum-int, strip it off.
3434     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3435       Ops.erase(Ops.begin());
3436       --Idx;
3437     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3438       // If we have an smax with a constant maximum-int, it will always be
3439       // maximum-int.
3440       return Ops[0];
3441     }
3442 
3443     if (Ops.size() == 1) return Ops[0];
3444   }
3445 
3446   // Find the first SMax
3447   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3448     ++Idx;
3449 
3450   // Check to see if one of the operands is an SMax. If so, expand its operands
3451   // onto our operand list, and recurse to simplify.
3452   if (Idx < Ops.size()) {
3453     bool DeletedSMax = false;
3454     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3455       Ops.erase(Ops.begin()+Idx);
3456       Ops.append(SMax->op_begin(), SMax->op_end());
3457       DeletedSMax = true;
3458     }
3459 
3460     if (DeletedSMax)
3461       return getSMaxExpr(Ops);
3462   }
3463 
3464   // Okay, check to see if the same value occurs in the operand list twice.  If
3465   // so, delete one.  Since we sorted the list, these values are required to
3466   // be adjacent.
3467   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3468     //  X smax Y smax Y  -->  X smax Y
3469     //  X smax Y         -->  X, if X is always greater than Y
3470     if (Ops[i] == Ops[i+1] ||
3471         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3472       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3473       --i; --e;
3474     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3475       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3476       --i; --e;
3477     }
3478 
3479   if (Ops.size() == 1) return Ops[0];
3480 
3481   assert(!Ops.empty() && "Reduced smax down to nothing!");
3482 
3483   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3484   // already have one, otherwise create a new one.
3485   FoldingSetNodeID ID;
3486   ID.AddInteger(scSMaxExpr);
3487   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3488     ID.AddPointer(Ops[i]);
3489   void *IP = nullptr;
3490   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3491   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3492   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3493   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3494                                              O, Ops.size());
3495   UniqueSCEVs.InsertNode(S, IP);
3496   addToLoopUseLists(S);
3497   return S;
3498 }
3499 
3500 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3501                                          const SCEV *RHS) {
3502   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3503   return getUMaxExpr(Ops);
3504 }
3505 
3506 const SCEV *
3507 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3508   assert(!Ops.empty() && "Cannot get empty umax!");
3509   if (Ops.size() == 1) return Ops[0];
3510 #ifndef NDEBUG
3511   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3512   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3513     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3514            "SCEVUMaxExpr operand types don't match!");
3515 #endif
3516 
3517   // Sort by complexity, this groups all similar expression types together.
3518   GroupByComplexity(Ops, &LI, DT);
3519 
3520   // If there are any constants, fold them together.
3521   unsigned Idx = 0;
3522   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3523     ++Idx;
3524     assert(Idx < Ops.size());
3525     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3526       // We found two constants, fold them together!
3527       ConstantInt *Fold = ConstantInt::get(
3528           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3529       Ops[0] = getConstant(Fold);
3530       Ops.erase(Ops.begin()+1);  // Erase the folded element
3531       if (Ops.size() == 1) return Ops[0];
3532       LHSC = cast<SCEVConstant>(Ops[0]);
3533     }
3534 
3535     // If we are left with a constant minimum-int, strip it off.
3536     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3537       Ops.erase(Ops.begin());
3538       --Idx;
3539     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3540       // If we have an umax with a constant maximum-int, it will always be
3541       // maximum-int.
3542       return Ops[0];
3543     }
3544 
3545     if (Ops.size() == 1) return Ops[0];
3546   }
3547 
3548   // Find the first UMax
3549   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3550     ++Idx;
3551 
3552   // Check to see if one of the operands is a UMax. If so, expand its operands
3553   // onto our operand list, and recurse to simplify.
3554   if (Idx < Ops.size()) {
3555     bool DeletedUMax = false;
3556     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3557       Ops.erase(Ops.begin()+Idx);
3558       Ops.append(UMax->op_begin(), UMax->op_end());
3559       DeletedUMax = true;
3560     }
3561 
3562     if (DeletedUMax)
3563       return getUMaxExpr(Ops);
3564   }
3565 
3566   // Okay, check to see if the same value occurs in the operand list twice.  If
3567   // so, delete one.  Since we sorted the list, these values are required to
3568   // be adjacent.
3569   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3570     //  X umax Y umax Y  -->  X umax Y
3571     //  X umax Y         -->  X, if X is always greater than Y
3572     if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
3573                                     ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) {
3574       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3575       --i; --e;
3576     } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i],
3577                                                Ops[i + 1])) {
3578       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3579       --i; --e;
3580     }
3581 
3582   if (Ops.size() == 1) return Ops[0];
3583 
3584   assert(!Ops.empty() && "Reduced umax down to nothing!");
3585 
3586   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3587   // already have one, otherwise create a new one.
3588   FoldingSetNodeID ID;
3589   ID.AddInteger(scUMaxExpr);
3590   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3591     ID.AddPointer(Ops[i]);
3592   void *IP = nullptr;
3593   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3594   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3595   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3596   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3597                                              O, Ops.size());
3598   UniqueSCEVs.InsertNode(S, IP);
3599   addToLoopUseLists(S);
3600   return S;
3601 }
3602 
3603 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3604                                          const SCEV *RHS) {
3605   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3606   return getSMinExpr(Ops);
3607 }
3608 
3609 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3610   // ~smax(~x, ~y, ~z) == smin(x, y, z).
3611   SmallVector<const SCEV *, 2> NotOps;
3612   for (auto *S : Ops)
3613     NotOps.push_back(getNotSCEV(S));
3614   return getNotSCEV(getSMaxExpr(NotOps));
3615 }
3616 
3617 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3618                                          const SCEV *RHS) {
3619   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3620   return getUMinExpr(Ops);
3621 }
3622 
3623 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3624   assert(!Ops.empty() && "At least one operand must be!");
3625   // Trivial case.
3626   if (Ops.size() == 1)
3627     return Ops[0];
3628 
3629   // ~umax(~x, ~y, ~z) == umin(x, y, z).
3630   SmallVector<const SCEV *, 2> NotOps;
3631   for (auto *S : Ops)
3632     NotOps.push_back(getNotSCEV(S));
3633   return getNotSCEV(getUMaxExpr(NotOps));
3634 }
3635 
3636 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3637   // We can bypass creating a target-independent
3638   // constant expression and then folding it back into a ConstantInt.
3639   // This is just a compile-time optimization.
3640   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3641 }
3642 
3643 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3644                                              StructType *STy,
3645                                              unsigned FieldNo) {
3646   // We can bypass creating a target-independent
3647   // constant expression and then folding it back into a ConstantInt.
3648   // This is just a compile-time optimization.
3649   return getConstant(
3650       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3651 }
3652 
3653 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3654   // Don't attempt to do anything other than create a SCEVUnknown object
3655   // here.  createSCEV only calls getUnknown after checking for all other
3656   // interesting possibilities, and any other code that calls getUnknown
3657   // is doing so in order to hide a value from SCEV canonicalization.
3658 
3659   FoldingSetNodeID ID;
3660   ID.AddInteger(scUnknown);
3661   ID.AddPointer(V);
3662   void *IP = nullptr;
3663   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3664     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3665            "Stale SCEVUnknown in uniquing map!");
3666     return S;
3667   }
3668   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3669                                             FirstUnknown);
3670   FirstUnknown = cast<SCEVUnknown>(S);
3671   UniqueSCEVs.InsertNode(S, IP);
3672   return S;
3673 }
3674 
3675 //===----------------------------------------------------------------------===//
3676 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3677 //
3678 
3679 /// Test if values of the given type are analyzable within the SCEV
3680 /// framework. This primarily includes integer types, and it can optionally
3681 /// include pointer types if the ScalarEvolution class has access to
3682 /// target-specific information.
3683 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3684   // Integers and pointers are always SCEVable.
3685   return Ty->isIntegerTy() || Ty->isPointerTy();
3686 }
3687 
3688 /// Return the size in bits of the specified type, for which isSCEVable must
3689 /// return true.
3690 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3691   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3692   if (Ty->isPointerTy())
3693     return getDataLayout().getIndexTypeSizeInBits(Ty);
3694   return getDataLayout().getTypeSizeInBits(Ty);
3695 }
3696 
3697 /// Return a type with the same bitwidth as the given type and which represents
3698 /// how SCEV will treat the given type, for which isSCEVable must return
3699 /// true. For pointer types, this is the pointer-sized integer type.
3700 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3701   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3702 
3703   if (Ty->isIntegerTy())
3704     return Ty;
3705 
3706   // The only other support type is pointer.
3707   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3708   return getDataLayout().getIntPtrType(Ty);
3709 }
3710 
3711 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3712   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3713 }
3714 
3715 const SCEV *ScalarEvolution::getCouldNotCompute() {
3716   return CouldNotCompute.get();
3717 }
3718 
3719 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3720   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3721     auto *SU = dyn_cast<SCEVUnknown>(S);
3722     return SU && SU->getValue() == nullptr;
3723   });
3724 
3725   return !ContainsNulls;
3726 }
3727 
3728 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3729   HasRecMapType::iterator I = HasRecMap.find(S);
3730   if (I != HasRecMap.end())
3731     return I->second;
3732 
3733   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3734   HasRecMap.insert({S, FoundAddRec});
3735   return FoundAddRec;
3736 }
3737 
3738 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3739 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3740 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3741 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3742   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3743   if (!Add)
3744     return {S, nullptr};
3745 
3746   if (Add->getNumOperands() != 2)
3747     return {S, nullptr};
3748 
3749   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3750   if (!ConstOp)
3751     return {S, nullptr};
3752 
3753   return {Add->getOperand(1), ConstOp->getValue()};
3754 }
3755 
3756 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3757 /// by the value and offset from any ValueOffsetPair in the set.
3758 SetVector<ScalarEvolution::ValueOffsetPair> *
3759 ScalarEvolution::getSCEVValues(const SCEV *S) {
3760   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3761   if (SI == ExprValueMap.end())
3762     return nullptr;
3763 #ifndef NDEBUG
3764   if (VerifySCEVMap) {
3765     // Check there is no dangling Value in the set returned.
3766     for (const auto &VE : SI->second)
3767       assert(ValueExprMap.count(VE.first));
3768   }
3769 #endif
3770   return &SI->second;
3771 }
3772 
3773 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3774 /// cannot be used separately. eraseValueFromMap should be used to remove
3775 /// V from ValueExprMap and ExprValueMap at the same time.
3776 void ScalarEvolution::eraseValueFromMap(Value *V) {
3777   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3778   if (I != ValueExprMap.end()) {
3779     const SCEV *S = I->second;
3780     // Remove {V, 0} from the set of ExprValueMap[S]
3781     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3782       SV->remove({V, nullptr});
3783 
3784     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3785     const SCEV *Stripped;
3786     ConstantInt *Offset;
3787     std::tie(Stripped, Offset) = splitAddExpr(S);
3788     if (Offset != nullptr) {
3789       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3790         SV->remove({V, Offset});
3791     }
3792     ValueExprMap.erase(V);
3793   }
3794 }
3795 
3796 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3797 /// TODO: In reality it is better to check the poison recursevely
3798 /// but this is better than nothing.
3799 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3800   if (auto *I = dyn_cast<Instruction>(V)) {
3801     if (isa<OverflowingBinaryOperator>(I)) {
3802       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3803         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3804           return true;
3805         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3806           return true;
3807       }
3808     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3809       return true;
3810   }
3811   return false;
3812 }
3813 
3814 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3815 /// create a new one.
3816 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3817   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3818 
3819   const SCEV *S = getExistingSCEV(V);
3820   if (S == nullptr) {
3821     S = createSCEV(V);
3822     // During PHI resolution, it is possible to create two SCEVs for the same
3823     // V, so it is needed to double check whether V->S is inserted into
3824     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3825     std::pair<ValueExprMapType::iterator, bool> Pair =
3826         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3827     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3828       ExprValueMap[S].insert({V, nullptr});
3829 
3830       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3831       // ExprValueMap.
3832       const SCEV *Stripped = S;
3833       ConstantInt *Offset = nullptr;
3834       std::tie(Stripped, Offset) = splitAddExpr(S);
3835       // If stripped is SCEVUnknown, don't bother to save
3836       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3837       // increase the complexity of the expansion code.
3838       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3839       // because it may generate add/sub instead of GEP in SCEV expansion.
3840       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3841           !isa<GetElementPtrInst>(V))
3842         ExprValueMap[Stripped].insert({V, Offset});
3843     }
3844   }
3845   return S;
3846 }
3847 
3848 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3849   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3850 
3851   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3852   if (I != ValueExprMap.end()) {
3853     const SCEV *S = I->second;
3854     if (checkValidity(S))
3855       return S;
3856     eraseValueFromMap(V);
3857     forgetMemoizedResults(S);
3858   }
3859   return nullptr;
3860 }
3861 
3862 /// Return a SCEV corresponding to -V = -1*V
3863 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3864                                              SCEV::NoWrapFlags Flags) {
3865   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3866     return getConstant(
3867                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3868 
3869   Type *Ty = V->getType();
3870   Ty = getEffectiveSCEVType(Ty);
3871   return getMulExpr(
3872       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3873 }
3874 
3875 /// Return a SCEV corresponding to ~V = -1-V
3876 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3877   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3878     return getConstant(
3879                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3880 
3881   Type *Ty = V->getType();
3882   Ty = getEffectiveSCEVType(Ty);
3883   const SCEV *AllOnes =
3884                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3885   return getMinusSCEV(AllOnes, V);
3886 }
3887 
3888 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3889                                           SCEV::NoWrapFlags Flags,
3890                                           unsigned Depth) {
3891   // Fast path: X - X --> 0.
3892   if (LHS == RHS)
3893     return getZero(LHS->getType());
3894 
3895   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3896   // makes it so that we cannot make much use of NUW.
3897   auto AddFlags = SCEV::FlagAnyWrap;
3898   const bool RHSIsNotMinSigned =
3899       !getSignedRangeMin(RHS).isMinSignedValue();
3900   if ((Flags & SCEV::FlagNSW) == SCEV::FlagNSW) {
3901     // Let M be the minimum representable signed value. Then (-1)*RHS
3902     // signed-wraps if and only if RHS is M. That can happen even for
3903     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3904     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3905     // (-1)*RHS, we need to prove that RHS != M.
3906     //
3907     // If LHS is non-negative and we know that LHS - RHS does not
3908     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3909     // either by proving that RHS > M or that LHS >= 0.
3910     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3911       AddFlags = SCEV::FlagNSW;
3912     }
3913   }
3914 
3915   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3916   // RHS is NSW and LHS >= 0.
3917   //
3918   // The difficulty here is that the NSW flag may have been proven
3919   // relative to a loop that is to be found in a recurrence in LHS and
3920   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3921   // larger scope than intended.
3922   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3923 
3924   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3925 }
3926 
3927 const SCEV *
3928 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3929   Type *SrcTy = V->getType();
3930   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3931          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3932          "Cannot truncate or zero extend with non-integer arguments!");
3933   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3934     return V;  // No conversion
3935   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3936     return getTruncateExpr(V, Ty);
3937   return getZeroExtendExpr(V, Ty);
3938 }
3939 
3940 const SCEV *
3941 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3942                                          Type *Ty) {
3943   Type *SrcTy = V->getType();
3944   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3945          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3946          "Cannot truncate or zero extend with non-integer arguments!");
3947   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3948     return V;  // No conversion
3949   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3950     return getTruncateExpr(V, Ty);
3951   return getSignExtendExpr(V, Ty);
3952 }
3953 
3954 const SCEV *
3955 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3956   Type *SrcTy = V->getType();
3957   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3958          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3959          "Cannot noop or zero extend with non-integer arguments!");
3960   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3961          "getNoopOrZeroExtend cannot truncate!");
3962   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3963     return V;  // No conversion
3964   return getZeroExtendExpr(V, Ty);
3965 }
3966 
3967 const SCEV *
3968 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3969   Type *SrcTy = V->getType();
3970   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3971          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3972          "Cannot noop or sign extend with non-integer arguments!");
3973   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3974          "getNoopOrSignExtend cannot truncate!");
3975   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3976     return V;  // No conversion
3977   return getSignExtendExpr(V, Ty);
3978 }
3979 
3980 const SCEV *
3981 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3982   Type *SrcTy = V->getType();
3983   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3984          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3985          "Cannot noop or any extend with non-integer arguments!");
3986   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3987          "getNoopOrAnyExtend cannot truncate!");
3988   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3989     return V;  // No conversion
3990   return getAnyExtendExpr(V, Ty);
3991 }
3992 
3993 const SCEV *
3994 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3995   Type *SrcTy = V->getType();
3996   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3997          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3998          "Cannot truncate or noop with non-integer arguments!");
3999   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4000          "getTruncateOrNoop cannot extend!");
4001   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4002     return V;  // No conversion
4003   return getTruncateExpr(V, Ty);
4004 }
4005 
4006 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4007                                                         const SCEV *RHS) {
4008   const SCEV *PromotedLHS = LHS;
4009   const SCEV *PromotedRHS = RHS;
4010 
4011   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4012     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4013   else
4014     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4015 
4016   return getUMaxExpr(PromotedLHS, PromotedRHS);
4017 }
4018 
4019 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4020                                                         const SCEV *RHS) {
4021   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4022   return getUMinFromMismatchedTypes(Ops);
4023 }
4024 
4025 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4026     SmallVectorImpl<const SCEV *> &Ops) {
4027   assert(!Ops.empty() && "At least one operand must be!");
4028   // Trivial case.
4029   if (Ops.size() == 1)
4030     return Ops[0];
4031 
4032   // Find the max type first.
4033   Type *MaxType = nullptr;
4034   for (auto *S : Ops)
4035     if (MaxType)
4036       MaxType = getWiderType(MaxType, S->getType());
4037     else
4038       MaxType = S->getType();
4039 
4040   // Extend all ops to max type.
4041   SmallVector<const SCEV *, 2> PromotedOps;
4042   for (auto *S : Ops)
4043     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4044 
4045   // Generate umin.
4046   return getUMinExpr(PromotedOps);
4047 }
4048 
4049 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4050   // A pointer operand may evaluate to a nonpointer expression, such as null.
4051   if (!V->getType()->isPointerTy())
4052     return V;
4053 
4054   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4055     return getPointerBase(Cast->getOperand());
4056   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4057     const SCEV *PtrOp = nullptr;
4058     for (const SCEV *NAryOp : NAry->operands()) {
4059       if (NAryOp->getType()->isPointerTy()) {
4060         // Cannot find the base of an expression with multiple pointer operands.
4061         if (PtrOp)
4062           return V;
4063         PtrOp = NAryOp;
4064       }
4065     }
4066     if (!PtrOp)
4067       return V;
4068     return getPointerBase(PtrOp);
4069   }
4070   return V;
4071 }
4072 
4073 /// Push users of the given Instruction onto the given Worklist.
4074 static void
4075 PushDefUseChildren(Instruction *I,
4076                    SmallVectorImpl<Instruction *> &Worklist) {
4077   // Push the def-use children onto the Worklist stack.
4078   for (User *U : I->users())
4079     Worklist.push_back(cast<Instruction>(U));
4080 }
4081 
4082 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4083   SmallVector<Instruction *, 16> Worklist;
4084   PushDefUseChildren(PN, Worklist);
4085 
4086   SmallPtrSet<Instruction *, 8> Visited;
4087   Visited.insert(PN);
4088   while (!Worklist.empty()) {
4089     Instruction *I = Worklist.pop_back_val();
4090     if (!Visited.insert(I).second)
4091       continue;
4092 
4093     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4094     if (It != ValueExprMap.end()) {
4095       const SCEV *Old = It->second;
4096 
4097       // Short-circuit the def-use traversal if the symbolic name
4098       // ceases to appear in expressions.
4099       if (Old != SymName && !hasOperand(Old, SymName))
4100         continue;
4101 
4102       // SCEVUnknown for a PHI either means that it has an unrecognized
4103       // structure, it's a PHI that's in the progress of being computed
4104       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4105       // additional loop trip count information isn't going to change anything.
4106       // In the second case, createNodeForPHI will perform the necessary
4107       // updates on its own when it gets to that point. In the third, we do
4108       // want to forget the SCEVUnknown.
4109       if (!isa<PHINode>(I) ||
4110           !isa<SCEVUnknown>(Old) ||
4111           (I != PN && Old == SymName)) {
4112         eraseValueFromMap(It->first);
4113         forgetMemoizedResults(Old);
4114       }
4115     }
4116 
4117     PushDefUseChildren(I, Worklist);
4118   }
4119 }
4120 
4121 namespace {
4122 
4123 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4124 /// expression in case its Loop is L. If it is not L then
4125 /// if IgnoreOtherLoops is true then use AddRec itself
4126 /// otherwise rewrite cannot be done.
4127 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4128 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4129 public:
4130   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4131                              bool IgnoreOtherLoops = true) {
4132     SCEVInitRewriter Rewriter(L, SE);
4133     const SCEV *Result = Rewriter.visit(S);
4134     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4135       return SE.getCouldNotCompute();
4136     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4137                ? SE.getCouldNotCompute()
4138                : Result;
4139   }
4140 
4141   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4142     if (!SE.isLoopInvariant(Expr, L))
4143       SeenLoopVariantSCEVUnknown = true;
4144     return Expr;
4145   }
4146 
4147   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4148     // Only re-write AddRecExprs for this loop.
4149     if (Expr->getLoop() == L)
4150       return Expr->getStart();
4151     SeenOtherLoops = true;
4152     return Expr;
4153   }
4154 
4155   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4156 
4157   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4158 
4159 private:
4160   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4161       : SCEVRewriteVisitor(SE), L(L) {}
4162 
4163   const Loop *L;
4164   bool SeenLoopVariantSCEVUnknown = false;
4165   bool SeenOtherLoops = false;
4166 };
4167 
4168 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4169 /// increment expression in case its Loop is L. If it is not L then
4170 /// use AddRec itself.
4171 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4172 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4173 public:
4174   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4175     SCEVPostIncRewriter Rewriter(L, SE);
4176     const SCEV *Result = Rewriter.visit(S);
4177     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4178         ? SE.getCouldNotCompute()
4179         : Result;
4180   }
4181 
4182   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4183     if (!SE.isLoopInvariant(Expr, L))
4184       SeenLoopVariantSCEVUnknown = true;
4185     return Expr;
4186   }
4187 
4188   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4189     // Only re-write AddRecExprs for this loop.
4190     if (Expr->getLoop() == L)
4191       return Expr->getPostIncExpr(SE);
4192     SeenOtherLoops = true;
4193     return Expr;
4194   }
4195 
4196   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4197 
4198   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4199 
4200 private:
4201   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4202       : SCEVRewriteVisitor(SE), L(L) {}
4203 
4204   const Loop *L;
4205   bool SeenLoopVariantSCEVUnknown = false;
4206   bool SeenOtherLoops = false;
4207 };
4208 
4209 /// This class evaluates the compare condition by matching it against the
4210 /// condition of loop latch. If there is a match we assume a true value
4211 /// for the condition while building SCEV nodes.
4212 class SCEVBackedgeConditionFolder
4213     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4214 public:
4215   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4216                              ScalarEvolution &SE) {
4217     bool IsPosBECond = false;
4218     Value *BECond = nullptr;
4219     if (BasicBlock *Latch = L->getLoopLatch()) {
4220       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4221       if (BI && BI->isConditional()) {
4222         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4223                "Both outgoing branches should not target same header!");
4224         BECond = BI->getCondition();
4225         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4226       } else {
4227         return S;
4228       }
4229     }
4230     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4231     return Rewriter.visit(S);
4232   }
4233 
4234   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4235     const SCEV *Result = Expr;
4236     bool InvariantF = SE.isLoopInvariant(Expr, L);
4237 
4238     if (!InvariantF) {
4239       Instruction *I = cast<Instruction>(Expr->getValue());
4240       switch (I->getOpcode()) {
4241       case Instruction::Select: {
4242         SelectInst *SI = cast<SelectInst>(I);
4243         Optional<const SCEV *> Res =
4244             compareWithBackedgeCondition(SI->getCondition());
4245         if (Res.hasValue()) {
4246           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4247           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4248         }
4249         break;
4250       }
4251       default: {
4252         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4253         if (Res.hasValue())
4254           Result = Res.getValue();
4255         break;
4256       }
4257       }
4258     }
4259     return Result;
4260   }
4261 
4262 private:
4263   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4264                                        bool IsPosBECond, ScalarEvolution &SE)
4265       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4266         IsPositiveBECond(IsPosBECond) {}
4267 
4268   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4269 
4270   const Loop *L;
4271   /// Loop back condition.
4272   Value *BackedgeCond = nullptr;
4273   /// Set to true if loop back is on positive branch condition.
4274   bool IsPositiveBECond;
4275 };
4276 
4277 Optional<const SCEV *>
4278 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4279 
4280   // If value matches the backedge condition for loop latch,
4281   // then return a constant evolution node based on loopback
4282   // branch taken.
4283   if (BackedgeCond == IC)
4284     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4285                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4286   return None;
4287 }
4288 
4289 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4290 public:
4291   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4292                              ScalarEvolution &SE) {
4293     SCEVShiftRewriter Rewriter(L, SE);
4294     const SCEV *Result = Rewriter.visit(S);
4295     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4296   }
4297 
4298   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4299     // Only allow AddRecExprs for this loop.
4300     if (!SE.isLoopInvariant(Expr, L))
4301       Valid = false;
4302     return Expr;
4303   }
4304 
4305   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4306     if (Expr->getLoop() == L && Expr->isAffine())
4307       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4308     Valid = false;
4309     return Expr;
4310   }
4311 
4312   bool isValid() { return Valid; }
4313 
4314 private:
4315   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4316       : SCEVRewriteVisitor(SE), L(L) {}
4317 
4318   const Loop *L;
4319   bool Valid = true;
4320 };
4321 
4322 } // end anonymous namespace
4323 
4324 SCEV::NoWrapFlags
4325 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4326   if (!AR->isAffine())
4327     return SCEV::FlagAnyWrap;
4328 
4329   using OBO = OverflowingBinaryOperator;
4330 
4331   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4332 
4333   if (!AR->hasNoSignedWrap()) {
4334     ConstantRange AddRecRange = getSignedRange(AR);
4335     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4336 
4337     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4338         Instruction::Add, IncRange, OBO::NoSignedWrap);
4339     if (NSWRegion.contains(AddRecRange))
4340       Result |= SCEV::FlagNSW;
4341   }
4342 
4343   if (!AR->hasNoUnsignedWrap()) {
4344     ConstantRange AddRecRange = getUnsignedRange(AR);
4345     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4346 
4347     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4348         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4349     if (NUWRegion.contains(AddRecRange))
4350       Result |= SCEV::FlagNUW;
4351   }
4352 
4353   return Result;
4354 }
4355 
4356 namespace {
4357 
4358 /// Represents an abstract binary operation.  This may exist as a
4359 /// normal instruction or constant expression, or may have been
4360 /// derived from an expression tree.
4361 struct BinaryOp {
4362   unsigned Opcode;
4363   Value *LHS;
4364   Value *RHS;
4365   bool IsNSW = false;
4366   bool IsNUW = false;
4367 
4368   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4369   /// constant expression.
4370   Operator *Op = nullptr;
4371 
4372   explicit BinaryOp(Operator *Op)
4373       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4374         Op(Op) {
4375     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4376       IsNSW = OBO->hasNoSignedWrap();
4377       IsNUW = OBO->hasNoUnsignedWrap();
4378     }
4379   }
4380 
4381   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4382                     bool IsNUW = false)
4383       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4384 };
4385 
4386 } // end anonymous namespace
4387 
4388 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4389 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4390   auto *Op = dyn_cast<Operator>(V);
4391   if (!Op)
4392     return None;
4393 
4394   // Implementation detail: all the cleverness here should happen without
4395   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4396   // SCEV expressions when possible, and we should not break that.
4397 
4398   switch (Op->getOpcode()) {
4399   case Instruction::Add:
4400   case Instruction::Sub:
4401   case Instruction::Mul:
4402   case Instruction::UDiv:
4403   case Instruction::URem:
4404   case Instruction::And:
4405   case Instruction::Or:
4406   case Instruction::AShr:
4407   case Instruction::Shl:
4408     return BinaryOp(Op);
4409 
4410   case Instruction::Xor:
4411     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4412       // If the RHS of the xor is a signmask, then this is just an add.
4413       // Instcombine turns add of signmask into xor as a strength reduction step.
4414       if (RHSC->getValue().isSignMask())
4415         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4416     return BinaryOp(Op);
4417 
4418   case Instruction::LShr:
4419     // Turn logical shift right of a constant into a unsigned divide.
4420     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4421       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4422 
4423       // If the shift count is not less than the bitwidth, the result of
4424       // the shift is undefined. Don't try to analyze it, because the
4425       // resolution chosen here may differ from the resolution chosen in
4426       // other parts of the compiler.
4427       if (SA->getValue().ult(BitWidth)) {
4428         Constant *X =
4429             ConstantInt::get(SA->getContext(),
4430                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4431         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4432       }
4433     }
4434     return BinaryOp(Op);
4435 
4436   case Instruction::ExtractValue: {
4437     auto *EVI = cast<ExtractValueInst>(Op);
4438     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4439       break;
4440 
4441     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4442     if (!CI)
4443       break;
4444 
4445     if (auto *F = CI->getCalledFunction())
4446       switch (F->getIntrinsicID()) {
4447       case Intrinsic::sadd_with_overflow:
4448       case Intrinsic::uadd_with_overflow:
4449         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4450           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4451                           CI->getArgOperand(1));
4452 
4453         // Now that we know that all uses of the arithmetic-result component of
4454         // CI are guarded by the overflow check, we can go ahead and pretend
4455         // that the arithmetic is non-overflowing.
4456         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4457           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4458                           CI->getArgOperand(1), /* IsNSW = */ true,
4459                           /* IsNUW = */ false);
4460         else
4461           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4462                           CI->getArgOperand(1), /* IsNSW = */ false,
4463                           /* IsNUW*/ true);
4464       case Intrinsic::ssub_with_overflow:
4465       case Intrinsic::usub_with_overflow:
4466         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4467           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4468                           CI->getArgOperand(1));
4469 
4470         // The same reasoning as sadd/uadd above.
4471         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4472           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4473                           CI->getArgOperand(1), /* IsNSW = */ true,
4474                           /* IsNUW = */ false);
4475         else
4476           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4477                           CI->getArgOperand(1), /* IsNSW = */ false,
4478                           /* IsNUW = */ true);
4479       case Intrinsic::smul_with_overflow:
4480       case Intrinsic::umul_with_overflow:
4481         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4482                         CI->getArgOperand(1));
4483       default:
4484         break;
4485       }
4486     break;
4487   }
4488 
4489   default:
4490     break;
4491   }
4492 
4493   return None;
4494 }
4495 
4496 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4497 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4498 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4499 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4500 /// follows one of the following patterns:
4501 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4502 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4503 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4504 /// we return the type of the truncation operation, and indicate whether the
4505 /// truncated type should be treated as signed/unsigned by setting
4506 /// \p Signed to true/false, respectively.
4507 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4508                                bool &Signed, ScalarEvolution &SE) {
4509   // The case where Op == SymbolicPHI (that is, with no type conversions on
4510   // the way) is handled by the regular add recurrence creating logic and
4511   // would have already been triggered in createAddRecForPHI. Reaching it here
4512   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4513   // because one of the other operands of the SCEVAddExpr updating this PHI is
4514   // not invariant).
4515   //
4516   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4517   // this case predicates that allow us to prove that Op == SymbolicPHI will
4518   // be added.
4519   if (Op == SymbolicPHI)
4520     return nullptr;
4521 
4522   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4523   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4524   if (SourceBits != NewBits)
4525     return nullptr;
4526 
4527   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4528   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4529   if (!SExt && !ZExt)
4530     return nullptr;
4531   const SCEVTruncateExpr *Trunc =
4532       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4533            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4534   if (!Trunc)
4535     return nullptr;
4536   const SCEV *X = Trunc->getOperand();
4537   if (X != SymbolicPHI)
4538     return nullptr;
4539   Signed = SExt != nullptr;
4540   return Trunc->getType();
4541 }
4542 
4543 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4544   if (!PN->getType()->isIntegerTy())
4545     return nullptr;
4546   const Loop *L = LI.getLoopFor(PN->getParent());
4547   if (!L || L->getHeader() != PN->getParent())
4548     return nullptr;
4549   return L;
4550 }
4551 
4552 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4553 // computation that updates the phi follows the following pattern:
4554 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4555 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4556 // If so, try to see if it can be rewritten as an AddRecExpr under some
4557 // Predicates. If successful, return them as a pair. Also cache the results
4558 // of the analysis.
4559 //
4560 // Example usage scenario:
4561 //    Say the Rewriter is called for the following SCEV:
4562 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4563 //    where:
4564 //         %X = phi i64 (%Start, %BEValue)
4565 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4566 //    and call this function with %SymbolicPHI = %X.
4567 //
4568 //    The analysis will find that the value coming around the backedge has
4569 //    the following SCEV:
4570 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4571 //    Upon concluding that this matches the desired pattern, the function
4572 //    will return the pair {NewAddRec, SmallPredsVec} where:
4573 //         NewAddRec = {%Start,+,%Step}
4574 //         SmallPredsVec = {P1, P2, P3} as follows:
4575 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4576 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4577 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4578 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4579 //    under the predicates {P1,P2,P3}.
4580 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4581 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4582 //
4583 // TODO's:
4584 //
4585 // 1) Extend the Induction descriptor to also support inductions that involve
4586 //    casts: When needed (namely, when we are called in the context of the
4587 //    vectorizer induction analysis), a Set of cast instructions will be
4588 //    populated by this method, and provided back to isInductionPHI. This is
4589 //    needed to allow the vectorizer to properly record them to be ignored by
4590 //    the cost model and to avoid vectorizing them (otherwise these casts,
4591 //    which are redundant under the runtime overflow checks, will be
4592 //    vectorized, which can be costly).
4593 //
4594 // 2) Support additional induction/PHISCEV patterns: We also want to support
4595 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4596 //    after the induction update operation (the induction increment):
4597 //
4598 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4599 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4600 //
4601 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4602 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4603 //
4604 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4605 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4606 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4607   SmallVector<const SCEVPredicate *, 3> Predicates;
4608 
4609   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4610   // return an AddRec expression under some predicate.
4611 
4612   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4613   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4614   assert(L && "Expecting an integer loop header phi");
4615 
4616   // The loop may have multiple entrances or multiple exits; we can analyze
4617   // this phi as an addrec if it has a unique entry value and a unique
4618   // backedge value.
4619   Value *BEValueV = nullptr, *StartValueV = nullptr;
4620   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4621     Value *V = PN->getIncomingValue(i);
4622     if (L->contains(PN->getIncomingBlock(i))) {
4623       if (!BEValueV) {
4624         BEValueV = V;
4625       } else if (BEValueV != V) {
4626         BEValueV = nullptr;
4627         break;
4628       }
4629     } else if (!StartValueV) {
4630       StartValueV = V;
4631     } else if (StartValueV != V) {
4632       StartValueV = nullptr;
4633       break;
4634     }
4635   }
4636   if (!BEValueV || !StartValueV)
4637     return None;
4638 
4639   const SCEV *BEValue = getSCEV(BEValueV);
4640 
4641   // If the value coming around the backedge is an add with the symbolic
4642   // value we just inserted, possibly with casts that we can ignore under
4643   // an appropriate runtime guard, then we found a simple induction variable!
4644   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4645   if (!Add)
4646     return None;
4647 
4648   // If there is a single occurrence of the symbolic value, possibly
4649   // casted, replace it with a recurrence.
4650   unsigned FoundIndex = Add->getNumOperands();
4651   Type *TruncTy = nullptr;
4652   bool Signed;
4653   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4654     if ((TruncTy =
4655              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4656       if (FoundIndex == e) {
4657         FoundIndex = i;
4658         break;
4659       }
4660 
4661   if (FoundIndex == Add->getNumOperands())
4662     return None;
4663 
4664   // Create an add with everything but the specified operand.
4665   SmallVector<const SCEV *, 8> Ops;
4666   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4667     if (i != FoundIndex)
4668       Ops.push_back(Add->getOperand(i));
4669   const SCEV *Accum = getAddExpr(Ops);
4670 
4671   // The runtime checks will not be valid if the step amount is
4672   // varying inside the loop.
4673   if (!isLoopInvariant(Accum, L))
4674     return None;
4675 
4676   // *** Part2: Create the predicates
4677 
4678   // Analysis was successful: we have a phi-with-cast pattern for which we
4679   // can return an AddRec expression under the following predicates:
4680   //
4681   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4682   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4683   // P2: An Equal predicate that guarantees that
4684   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4685   // P3: An Equal predicate that guarantees that
4686   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4687   //
4688   // As we next prove, the above predicates guarantee that:
4689   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4690   //
4691   //
4692   // More formally, we want to prove that:
4693   //     Expr(i+1) = Start + (i+1) * Accum
4694   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4695   //
4696   // Given that:
4697   // 1) Expr(0) = Start
4698   // 2) Expr(1) = Start + Accum
4699   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4700   // 3) Induction hypothesis (step i):
4701   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4702   //
4703   // Proof:
4704   //  Expr(i+1) =
4705   //   = Start + (i+1)*Accum
4706   //   = (Start + i*Accum) + Accum
4707   //   = Expr(i) + Accum
4708   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4709   //                                                             :: from step i
4710   //
4711   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4712   //
4713   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4714   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4715   //     + Accum                                                     :: from P3
4716   //
4717   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4718   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4719   //
4720   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4721   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4722   //
4723   // By induction, the same applies to all iterations 1<=i<n:
4724   //
4725 
4726   // Create a truncated addrec for which we will add a no overflow check (P1).
4727   const SCEV *StartVal = getSCEV(StartValueV);
4728   const SCEV *PHISCEV =
4729       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4730                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4731 
4732   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4733   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4734   // will be constant.
4735   //
4736   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4737   // add P1.
4738   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4739     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4740         Signed ? SCEVWrapPredicate::IncrementNSSW
4741                : SCEVWrapPredicate::IncrementNUSW;
4742     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4743     Predicates.push_back(AddRecPred);
4744   }
4745 
4746   // Create the Equal Predicates P2,P3:
4747 
4748   // It is possible that the predicates P2 and/or P3 are computable at
4749   // compile time due to StartVal and/or Accum being constants.
4750   // If either one is, then we can check that now and escape if either P2
4751   // or P3 is false.
4752 
4753   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4754   // for each of StartVal and Accum
4755   auto getExtendedExpr = [&](const SCEV *Expr,
4756                              bool CreateSignExtend) -> const SCEV * {
4757     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4758     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4759     const SCEV *ExtendedExpr =
4760         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4761                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4762     return ExtendedExpr;
4763   };
4764 
4765   // Given:
4766   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4767   //               = getExtendedExpr(Expr)
4768   // Determine whether the predicate P: Expr == ExtendedExpr
4769   // is known to be false at compile time
4770   auto PredIsKnownFalse = [&](const SCEV *Expr,
4771                               const SCEV *ExtendedExpr) -> bool {
4772     return Expr != ExtendedExpr &&
4773            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4774   };
4775 
4776   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4777   if (PredIsKnownFalse(StartVal, StartExtended)) {
4778     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4779     return None;
4780   }
4781 
4782   // The Step is always Signed (because the overflow checks are either
4783   // NSSW or NUSW)
4784   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4785   if (PredIsKnownFalse(Accum, AccumExtended)) {
4786     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4787     return None;
4788   }
4789 
4790   auto AppendPredicate = [&](const SCEV *Expr,
4791                              const SCEV *ExtendedExpr) -> void {
4792     if (Expr != ExtendedExpr &&
4793         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4794       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4795       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4796       Predicates.push_back(Pred);
4797     }
4798   };
4799 
4800   AppendPredicate(StartVal, StartExtended);
4801   AppendPredicate(Accum, AccumExtended);
4802 
4803   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4804   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4805   // into NewAR if it will also add the runtime overflow checks specified in
4806   // Predicates.
4807   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4808 
4809   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4810       std::make_pair(NewAR, Predicates);
4811   // Remember the result of the analysis for this SCEV at this locayyytion.
4812   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4813   return PredRewrite;
4814 }
4815 
4816 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4817 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4818   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4819   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4820   if (!L)
4821     return None;
4822 
4823   // Check to see if we already analyzed this PHI.
4824   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4825   if (I != PredicatedSCEVRewrites.end()) {
4826     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4827         I->second;
4828     // Analysis was done before and failed to create an AddRec:
4829     if (Rewrite.first == SymbolicPHI)
4830       return None;
4831     // Analysis was done before and succeeded to create an AddRec under
4832     // a predicate:
4833     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4834     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4835     return Rewrite;
4836   }
4837 
4838   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4839     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4840 
4841   // Record in the cache that the analysis failed
4842   if (!Rewrite) {
4843     SmallVector<const SCEVPredicate *, 3> Predicates;
4844     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4845     return None;
4846   }
4847 
4848   return Rewrite;
4849 }
4850 
4851 // FIXME: This utility is currently required because the Rewriter currently
4852 // does not rewrite this expression:
4853 // {0, +, (sext ix (trunc iy to ix) to iy)}
4854 // into {0, +, %step},
4855 // even when the following Equal predicate exists:
4856 // "%step == (sext ix (trunc iy to ix) to iy)".
4857 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4858     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4859   if (AR1 == AR2)
4860     return true;
4861 
4862   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4863     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4864         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4865       return false;
4866     return true;
4867   };
4868 
4869   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4870       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4871     return false;
4872   return true;
4873 }
4874 
4875 /// A helper function for createAddRecFromPHI to handle simple cases.
4876 ///
4877 /// This function tries to find an AddRec expression for the simplest (yet most
4878 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4879 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4880 /// technique for finding the AddRec expression.
4881 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4882                                                       Value *BEValueV,
4883                                                       Value *StartValueV) {
4884   const Loop *L = LI.getLoopFor(PN->getParent());
4885   assert(L && L->getHeader() == PN->getParent());
4886   assert(BEValueV && StartValueV);
4887 
4888   auto BO = MatchBinaryOp(BEValueV, DT);
4889   if (!BO)
4890     return nullptr;
4891 
4892   if (BO->Opcode != Instruction::Add)
4893     return nullptr;
4894 
4895   const SCEV *Accum = nullptr;
4896   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4897     Accum = getSCEV(BO->RHS);
4898   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4899     Accum = getSCEV(BO->LHS);
4900 
4901   if (!Accum)
4902     return nullptr;
4903 
4904   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4905   if (BO->IsNUW)
4906     Flags |= SCEV::FlagNUW;
4907   if (BO->IsNSW)
4908     Flags |= SCEV::FlagNSW;
4909 
4910   const SCEV *StartVal = getSCEV(StartValueV);
4911   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4912 
4913   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4914 
4915   // We can add Flags to the post-inc expression only if we
4916   // know that it is *undefined behavior* for BEValueV to
4917   // overflow.
4918   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4919     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4920       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4921 
4922   return PHISCEV;
4923 }
4924 
4925 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4926   const Loop *L = LI.getLoopFor(PN->getParent());
4927   if (!L || L->getHeader() != PN->getParent())
4928     return nullptr;
4929 
4930   // The loop may have multiple entrances or multiple exits; we can analyze
4931   // this phi as an addrec if it has a unique entry value and a unique
4932   // backedge value.
4933   Value *BEValueV = nullptr, *StartValueV = nullptr;
4934   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4935     Value *V = PN->getIncomingValue(i);
4936     if (L->contains(PN->getIncomingBlock(i))) {
4937       if (!BEValueV) {
4938         BEValueV = V;
4939       } else if (BEValueV != V) {
4940         BEValueV = nullptr;
4941         break;
4942       }
4943     } else if (!StartValueV) {
4944       StartValueV = V;
4945     } else if (StartValueV != V) {
4946       StartValueV = nullptr;
4947       break;
4948     }
4949   }
4950   if (!BEValueV || !StartValueV)
4951     return nullptr;
4952 
4953   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4954          "PHI node already processed?");
4955 
4956   // First, try to find AddRec expression without creating a fictituos symbolic
4957   // value for PN.
4958   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4959     return S;
4960 
4961   // Handle PHI node value symbolically.
4962   const SCEV *SymbolicName = getUnknown(PN);
4963   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4964 
4965   // Using this symbolic name for the PHI, analyze the value coming around
4966   // the back-edge.
4967   const SCEV *BEValue = getSCEV(BEValueV);
4968 
4969   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4970   // has a special value for the first iteration of the loop.
4971 
4972   // If the value coming around the backedge is an add with the symbolic
4973   // value we just inserted, then we found a simple induction variable!
4974   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4975     // If there is a single occurrence of the symbolic value, replace it
4976     // with a recurrence.
4977     unsigned FoundIndex = Add->getNumOperands();
4978     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4979       if (Add->getOperand(i) == SymbolicName)
4980         if (FoundIndex == e) {
4981           FoundIndex = i;
4982           break;
4983         }
4984 
4985     if (FoundIndex != Add->getNumOperands()) {
4986       // Create an add with everything but the specified operand.
4987       SmallVector<const SCEV *, 8> Ops;
4988       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4989         if (i != FoundIndex)
4990           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4991                                                              L, *this));
4992       const SCEV *Accum = getAddExpr(Ops);
4993 
4994       // This is not a valid addrec if the step amount is varying each
4995       // loop iteration, but is not itself an addrec in this loop.
4996       if (isLoopInvariant(Accum, L) ||
4997           (isa<SCEVAddRecExpr>(Accum) &&
4998            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4999         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5000 
5001         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5002           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5003             if (BO->IsNUW)
5004               Flags |= SCEV::FlagNUW;
5005             if (BO->IsNSW)
5006               Flags |= SCEV::FlagNSW;
5007           }
5008         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5009           // If the increment is an inbounds GEP, then we know the address
5010           // space cannot be wrapped around. We cannot make any guarantee
5011           // about signed or unsigned overflow because pointers are
5012           // unsigned but we may have a negative index from the base
5013           // pointer. We can guarantee that no unsigned wrap occurs if the
5014           // indices form a positive value.
5015           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5016             Flags |= SCEV::FlagNW;
5017 
5018             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5019             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5020               Flags |= SCEV::FlagNUW;
5021           }
5022 
5023           // We cannot transfer nuw and nsw flags from subtraction
5024           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5025           // for instance.
5026         }
5027 
5028         const SCEV *StartVal = getSCEV(StartValueV);
5029         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5030 
5031         // Okay, for the entire analysis of this edge we assumed the PHI
5032         // to be symbolic.  We now need to go back and purge all of the
5033         // entries for the scalars that use the symbolic expression.
5034         forgetSymbolicName(PN, SymbolicName);
5035         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5036 
5037         // We can add Flags to the post-inc expression only if we
5038         // know that it is *undefined behavior* for BEValueV to
5039         // overflow.
5040         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5041           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5042             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5043 
5044         return PHISCEV;
5045       }
5046     }
5047   } else {
5048     // Otherwise, this could be a loop like this:
5049     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5050     // In this case, j = {1,+,1}  and BEValue is j.
5051     // Because the other in-value of i (0) fits the evolution of BEValue
5052     // i really is an addrec evolution.
5053     //
5054     // We can generalize this saying that i is the shifted value of BEValue
5055     // by one iteration:
5056     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5057     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5058     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5059     if (Shifted != getCouldNotCompute() &&
5060         Start != getCouldNotCompute()) {
5061       const SCEV *StartVal = getSCEV(StartValueV);
5062       if (Start == StartVal) {
5063         // Okay, for the entire analysis of this edge we assumed the PHI
5064         // to be symbolic.  We now need to go back and purge all of the
5065         // entries for the scalars that use the symbolic expression.
5066         forgetSymbolicName(PN, SymbolicName);
5067         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5068         return Shifted;
5069       }
5070     }
5071   }
5072 
5073   // Remove the temporary PHI node SCEV that has been inserted while intending
5074   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5075   // as it will prevent later (possibly simpler) SCEV expressions to be added
5076   // to the ValueExprMap.
5077   eraseValueFromMap(PN);
5078 
5079   return nullptr;
5080 }
5081 
5082 // Checks if the SCEV S is available at BB.  S is considered available at BB
5083 // if S can be materialized at BB without introducing a fault.
5084 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5085                                BasicBlock *BB) {
5086   struct CheckAvailable {
5087     bool TraversalDone = false;
5088     bool Available = true;
5089 
5090     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5091     BasicBlock *BB = nullptr;
5092     DominatorTree &DT;
5093 
5094     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5095       : L(L), BB(BB), DT(DT) {}
5096 
5097     bool setUnavailable() {
5098       TraversalDone = true;
5099       Available = false;
5100       return false;
5101     }
5102 
5103     bool follow(const SCEV *S) {
5104       switch (S->getSCEVType()) {
5105       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5106       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5107         // These expressions are available if their operand(s) is/are.
5108         return true;
5109 
5110       case scAddRecExpr: {
5111         // We allow add recurrences that are on the loop BB is in, or some
5112         // outer loop.  This guarantees availability because the value of the
5113         // add recurrence at BB is simply the "current" value of the induction
5114         // variable.  We can relax this in the future; for instance an add
5115         // recurrence on a sibling dominating loop is also available at BB.
5116         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5117         if (L && (ARLoop == L || ARLoop->contains(L)))
5118           return true;
5119 
5120         return setUnavailable();
5121       }
5122 
5123       case scUnknown: {
5124         // For SCEVUnknown, we check for simple dominance.
5125         const auto *SU = cast<SCEVUnknown>(S);
5126         Value *V = SU->getValue();
5127 
5128         if (isa<Argument>(V))
5129           return false;
5130 
5131         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5132           return false;
5133 
5134         return setUnavailable();
5135       }
5136 
5137       case scUDivExpr:
5138       case scCouldNotCompute:
5139         // We do not try to smart about these at all.
5140         return setUnavailable();
5141       }
5142       llvm_unreachable("switch should be fully covered!");
5143     }
5144 
5145     bool isDone() { return TraversalDone; }
5146   };
5147 
5148   CheckAvailable CA(L, BB, DT);
5149   SCEVTraversal<CheckAvailable> ST(CA);
5150 
5151   ST.visitAll(S);
5152   return CA.Available;
5153 }
5154 
5155 // Try to match a control flow sequence that branches out at BI and merges back
5156 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5157 // match.
5158 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5159                           Value *&C, Value *&LHS, Value *&RHS) {
5160   C = BI->getCondition();
5161 
5162   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5163   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5164 
5165   if (!LeftEdge.isSingleEdge())
5166     return false;
5167 
5168   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5169 
5170   Use &LeftUse = Merge->getOperandUse(0);
5171   Use &RightUse = Merge->getOperandUse(1);
5172 
5173   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5174     LHS = LeftUse;
5175     RHS = RightUse;
5176     return true;
5177   }
5178 
5179   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5180     LHS = RightUse;
5181     RHS = LeftUse;
5182     return true;
5183   }
5184 
5185   return false;
5186 }
5187 
5188 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5189   auto IsReachable =
5190       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5191   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5192     const Loop *L = LI.getLoopFor(PN->getParent());
5193 
5194     // We don't want to break LCSSA, even in a SCEV expression tree.
5195     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5196       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5197         return nullptr;
5198 
5199     // Try to match
5200     //
5201     //  br %cond, label %left, label %right
5202     // left:
5203     //  br label %merge
5204     // right:
5205     //  br label %merge
5206     // merge:
5207     //  V = phi [ %x, %left ], [ %y, %right ]
5208     //
5209     // as "select %cond, %x, %y"
5210 
5211     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5212     assert(IDom && "At least the entry block should dominate PN");
5213 
5214     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5215     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5216 
5217     if (BI && BI->isConditional() &&
5218         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5219         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5220         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5221       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5222   }
5223 
5224   return nullptr;
5225 }
5226 
5227 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5228   if (const SCEV *S = createAddRecFromPHI(PN))
5229     return S;
5230 
5231   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5232     return S;
5233 
5234   // If the PHI has a single incoming value, follow that value, unless the
5235   // PHI's incoming blocks are in a different loop, in which case doing so
5236   // risks breaking LCSSA form. Instcombine would normally zap these, but
5237   // it doesn't have DominatorTree information, so it may miss cases.
5238   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5239     if (LI.replacementPreservesLCSSAForm(PN, V))
5240       return getSCEV(V);
5241 
5242   // If it's not a loop phi, we can't handle it yet.
5243   return getUnknown(PN);
5244 }
5245 
5246 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5247                                                       Value *Cond,
5248                                                       Value *TrueVal,
5249                                                       Value *FalseVal) {
5250   // Handle "constant" branch or select. This can occur for instance when a
5251   // loop pass transforms an inner loop and moves on to process the outer loop.
5252   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5253     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5254 
5255   // Try to match some simple smax or umax patterns.
5256   auto *ICI = dyn_cast<ICmpInst>(Cond);
5257   if (!ICI)
5258     return getUnknown(I);
5259 
5260   Value *LHS = ICI->getOperand(0);
5261   Value *RHS = ICI->getOperand(1);
5262 
5263   switch (ICI->getPredicate()) {
5264   case ICmpInst::ICMP_SLT:
5265   case ICmpInst::ICMP_SLE:
5266     std::swap(LHS, RHS);
5267     LLVM_FALLTHROUGH;
5268   case ICmpInst::ICMP_SGT:
5269   case ICmpInst::ICMP_SGE:
5270     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5271     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5272     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5273       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5274       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5275       const SCEV *LA = getSCEV(TrueVal);
5276       const SCEV *RA = getSCEV(FalseVal);
5277       const SCEV *LDiff = getMinusSCEV(LA, LS);
5278       const SCEV *RDiff = getMinusSCEV(RA, RS);
5279       if (LDiff == RDiff)
5280         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5281       LDiff = getMinusSCEV(LA, RS);
5282       RDiff = getMinusSCEV(RA, LS);
5283       if (LDiff == RDiff)
5284         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5285     }
5286     break;
5287   case ICmpInst::ICMP_ULT:
5288   case ICmpInst::ICMP_ULE:
5289     std::swap(LHS, RHS);
5290     LLVM_FALLTHROUGH;
5291   case ICmpInst::ICMP_UGT:
5292   case ICmpInst::ICMP_UGE:
5293     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5294     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5295     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5296       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5297       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5298       const SCEV *LA = getSCEV(TrueVal);
5299       const SCEV *RA = getSCEV(FalseVal);
5300       const SCEV *LDiff = getMinusSCEV(LA, LS);
5301       const SCEV *RDiff = getMinusSCEV(RA, RS);
5302       if (LDiff == RDiff)
5303         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5304       LDiff = getMinusSCEV(LA, RS);
5305       RDiff = getMinusSCEV(RA, LS);
5306       if (LDiff == RDiff)
5307         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5308     }
5309     break;
5310   case ICmpInst::ICMP_NE:
5311     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5312     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5313         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5314       const SCEV *One = getOne(I->getType());
5315       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5316       const SCEV *LA = getSCEV(TrueVal);
5317       const SCEV *RA = getSCEV(FalseVal);
5318       const SCEV *LDiff = getMinusSCEV(LA, LS);
5319       const SCEV *RDiff = getMinusSCEV(RA, One);
5320       if (LDiff == RDiff)
5321         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5322     }
5323     break;
5324   case ICmpInst::ICMP_EQ:
5325     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5326     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5327         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5328       const SCEV *One = getOne(I->getType());
5329       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5330       const SCEV *LA = getSCEV(TrueVal);
5331       const SCEV *RA = getSCEV(FalseVal);
5332       const SCEV *LDiff = getMinusSCEV(LA, One);
5333       const SCEV *RDiff = getMinusSCEV(RA, LS);
5334       if (LDiff == RDiff)
5335         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5336     }
5337     break;
5338   default:
5339     break;
5340   }
5341 
5342   return getUnknown(I);
5343 }
5344 
5345 /// Expand GEP instructions into add and multiply operations. This allows them
5346 /// to be analyzed by regular SCEV code.
5347 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5348   // Don't attempt to analyze GEPs over unsized objects.
5349   if (!GEP->getSourceElementType()->isSized())
5350     return getUnknown(GEP);
5351 
5352   SmallVector<const SCEV *, 4> IndexExprs;
5353   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5354     IndexExprs.push_back(getSCEV(*Index));
5355   return getGEPExpr(GEP, IndexExprs);
5356 }
5357 
5358 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5359   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5360     return C->getAPInt().countTrailingZeros();
5361 
5362   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5363     return std::min(GetMinTrailingZeros(T->getOperand()),
5364                     (uint32_t)getTypeSizeInBits(T->getType()));
5365 
5366   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5367     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5368     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5369                ? getTypeSizeInBits(E->getType())
5370                : OpRes;
5371   }
5372 
5373   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5374     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5375     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5376                ? getTypeSizeInBits(E->getType())
5377                : OpRes;
5378   }
5379 
5380   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5381     // The result is the min of all operands results.
5382     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5383     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5384       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5385     return MinOpRes;
5386   }
5387 
5388   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5389     // The result is the sum of all operands results.
5390     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5391     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5392     for (unsigned i = 1, e = M->getNumOperands();
5393          SumOpRes != BitWidth && i != e; ++i)
5394       SumOpRes =
5395           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5396     return SumOpRes;
5397   }
5398 
5399   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5400     // The result is the min of all operands results.
5401     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5402     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5403       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5404     return MinOpRes;
5405   }
5406 
5407   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5408     // The result is the min of all operands results.
5409     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5410     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5411       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5412     return MinOpRes;
5413   }
5414 
5415   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5416     // The result is the min of all operands results.
5417     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5418     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5419       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5420     return MinOpRes;
5421   }
5422 
5423   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5424     // For a SCEVUnknown, ask ValueTracking.
5425     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5426     return Known.countMinTrailingZeros();
5427   }
5428 
5429   // SCEVUDivExpr
5430   return 0;
5431 }
5432 
5433 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5434   auto I = MinTrailingZerosCache.find(S);
5435   if (I != MinTrailingZerosCache.end())
5436     return I->second;
5437 
5438   uint32_t Result = GetMinTrailingZerosImpl(S);
5439   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5440   assert(InsertPair.second && "Should insert a new key");
5441   return InsertPair.first->second;
5442 }
5443 
5444 /// Helper method to assign a range to V from metadata present in the IR.
5445 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5446   if (Instruction *I = dyn_cast<Instruction>(V))
5447     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5448       return getConstantRangeFromMetadata(*MD);
5449 
5450   return None;
5451 }
5452 
5453 /// Determine the range for a particular SCEV.  If SignHint is
5454 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5455 /// with a "cleaner" unsigned (resp. signed) representation.
5456 const ConstantRange &
5457 ScalarEvolution::getRangeRef(const SCEV *S,
5458                              ScalarEvolution::RangeSignHint SignHint) {
5459   DenseMap<const SCEV *, ConstantRange> &Cache =
5460       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5461                                                        : SignedRanges;
5462 
5463   // See if we've computed this range already.
5464   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5465   if (I != Cache.end())
5466     return I->second;
5467 
5468   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5469     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5470 
5471   unsigned BitWidth = getTypeSizeInBits(S->getType());
5472   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5473 
5474   // If the value has known zeros, the maximum value will have those known zeros
5475   // as well.
5476   uint32_t TZ = GetMinTrailingZeros(S);
5477   if (TZ != 0) {
5478     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5479       ConservativeResult =
5480           ConstantRange(APInt::getMinValue(BitWidth),
5481                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5482     else
5483       ConservativeResult = ConstantRange(
5484           APInt::getSignedMinValue(BitWidth),
5485           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5486   }
5487 
5488   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5489     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5490     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5491       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5492     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5493   }
5494 
5495   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5496     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5497     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5498       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5499     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5500   }
5501 
5502   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5503     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5504     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5505       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5506     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5507   }
5508 
5509   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5510     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5511     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5512       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5513     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5514   }
5515 
5516   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5517     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5518     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5519     return setRange(UDiv, SignHint,
5520                     ConservativeResult.intersectWith(X.udiv(Y)));
5521   }
5522 
5523   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5524     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5525     return setRange(ZExt, SignHint,
5526                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5527   }
5528 
5529   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5530     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5531     return setRange(SExt, SignHint,
5532                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5533   }
5534 
5535   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5536     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5537     return setRange(Trunc, SignHint,
5538                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5539   }
5540 
5541   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5542     // If there's no unsigned wrap, the value will never be less than its
5543     // initial value.
5544     if (AddRec->hasNoUnsignedWrap())
5545       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5546         if (!C->getValue()->isZero())
5547           ConservativeResult = ConservativeResult.intersectWith(
5548               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5549 
5550     // If there's no signed wrap, and all the operands have the same sign or
5551     // zero, the value won't ever change sign.
5552     if (AddRec->hasNoSignedWrap()) {
5553       bool AllNonNeg = true;
5554       bool AllNonPos = true;
5555       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5556         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5557         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5558       }
5559       if (AllNonNeg)
5560         ConservativeResult = ConservativeResult.intersectWith(
5561           ConstantRange(APInt(BitWidth, 0),
5562                         APInt::getSignedMinValue(BitWidth)));
5563       else if (AllNonPos)
5564         ConservativeResult = ConservativeResult.intersectWith(
5565           ConstantRange(APInt::getSignedMinValue(BitWidth),
5566                         APInt(BitWidth, 1)));
5567     }
5568 
5569     // TODO: non-affine addrec
5570     if (AddRec->isAffine()) {
5571       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5572       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5573           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5574         auto RangeFromAffine = getRangeForAffineAR(
5575             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5576             BitWidth);
5577         if (!RangeFromAffine.isFullSet())
5578           ConservativeResult =
5579               ConservativeResult.intersectWith(RangeFromAffine);
5580 
5581         auto RangeFromFactoring = getRangeViaFactoring(
5582             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5583             BitWidth);
5584         if (!RangeFromFactoring.isFullSet())
5585           ConservativeResult =
5586               ConservativeResult.intersectWith(RangeFromFactoring);
5587       }
5588     }
5589 
5590     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5591   }
5592 
5593   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5594     // Check if the IR explicitly contains !range metadata.
5595     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5596     if (MDRange.hasValue())
5597       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5598 
5599     // Split here to avoid paying the compile-time cost of calling both
5600     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5601     // if needed.
5602     const DataLayout &DL = getDataLayout();
5603     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5604       // For a SCEVUnknown, ask ValueTracking.
5605       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5606       if (Known.One != ~Known.Zero + 1)
5607         ConservativeResult =
5608             ConservativeResult.intersectWith(ConstantRange(Known.One,
5609                                                            ~Known.Zero + 1));
5610     } else {
5611       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5612              "generalize as needed!");
5613       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5614       if (NS > 1)
5615         ConservativeResult = ConservativeResult.intersectWith(
5616             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5617                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5618     }
5619 
5620     // A range of Phi is a subset of union of all ranges of its input.
5621     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5622       // Make sure that we do not run over cycled Phis.
5623       if (PendingPhiRanges.insert(Phi).second) {
5624         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5625         for (auto &Op : Phi->operands()) {
5626           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5627           RangeFromOps = RangeFromOps.unionWith(OpRange);
5628           // No point to continue if we already have a full set.
5629           if (RangeFromOps.isFullSet())
5630             break;
5631         }
5632         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5633         bool Erased = PendingPhiRanges.erase(Phi);
5634         assert(Erased && "Failed to erase Phi properly?");
5635         (void) Erased;
5636       }
5637     }
5638 
5639     return setRange(U, SignHint, std::move(ConservativeResult));
5640   }
5641 
5642   return setRange(S, SignHint, std::move(ConservativeResult));
5643 }
5644 
5645 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5646 // values that the expression can take. Initially, the expression has a value
5647 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5648 // argument defines if we treat Step as signed or unsigned.
5649 static ConstantRange getRangeForAffineARHelper(APInt Step,
5650                                                const ConstantRange &StartRange,
5651                                                const APInt &MaxBECount,
5652                                                unsigned BitWidth, bool Signed) {
5653   // If either Step or MaxBECount is 0, then the expression won't change, and we
5654   // just need to return the initial range.
5655   if (Step == 0 || MaxBECount == 0)
5656     return StartRange;
5657 
5658   // If we don't know anything about the initial value (i.e. StartRange is
5659   // FullRange), then we don't know anything about the final range either.
5660   // Return FullRange.
5661   if (StartRange.isFullSet())
5662     return ConstantRange(BitWidth, /* isFullSet = */ true);
5663 
5664   // If Step is signed and negative, then we use its absolute value, but we also
5665   // note that we're moving in the opposite direction.
5666   bool Descending = Signed && Step.isNegative();
5667 
5668   if (Signed)
5669     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5670     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5671     // This equations hold true due to the well-defined wrap-around behavior of
5672     // APInt.
5673     Step = Step.abs();
5674 
5675   // Check if Offset is more than full span of BitWidth. If it is, the
5676   // expression is guaranteed to overflow.
5677   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5678     return ConstantRange(BitWidth, /* isFullSet = */ true);
5679 
5680   // Offset is by how much the expression can change. Checks above guarantee no
5681   // overflow here.
5682   APInt Offset = Step * MaxBECount;
5683 
5684   // Minimum value of the final range will match the minimal value of StartRange
5685   // if the expression is increasing and will be decreased by Offset otherwise.
5686   // Maximum value of the final range will match the maximal value of StartRange
5687   // if the expression is decreasing and will be increased by Offset otherwise.
5688   APInt StartLower = StartRange.getLower();
5689   APInt StartUpper = StartRange.getUpper() - 1;
5690   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5691                                    : (StartUpper + std::move(Offset));
5692 
5693   // It's possible that the new minimum/maximum value will fall into the initial
5694   // range (due to wrap around). This means that the expression can take any
5695   // value in this bitwidth, and we have to return full range.
5696   if (StartRange.contains(MovedBoundary))
5697     return ConstantRange(BitWidth, /* isFullSet = */ true);
5698 
5699   APInt NewLower =
5700       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5701   APInt NewUpper =
5702       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5703   NewUpper += 1;
5704 
5705   // If we end up with full range, return a proper full range.
5706   if (NewLower == NewUpper)
5707     return ConstantRange(BitWidth, /* isFullSet = */ true);
5708 
5709   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5710   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5711 }
5712 
5713 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5714                                                    const SCEV *Step,
5715                                                    const SCEV *MaxBECount,
5716                                                    unsigned BitWidth) {
5717   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5718          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5719          "Precondition!");
5720 
5721   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5722   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5723 
5724   // First, consider step signed.
5725   ConstantRange StartSRange = getSignedRange(Start);
5726   ConstantRange StepSRange = getSignedRange(Step);
5727 
5728   // If Step can be both positive and negative, we need to find ranges for the
5729   // maximum absolute step values in both directions and union them.
5730   ConstantRange SR =
5731       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5732                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5733   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5734                                               StartSRange, MaxBECountValue,
5735                                               BitWidth, /* Signed = */ true));
5736 
5737   // Next, consider step unsigned.
5738   ConstantRange UR = getRangeForAffineARHelper(
5739       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5740       MaxBECountValue, BitWidth, /* Signed = */ false);
5741 
5742   // Finally, intersect signed and unsigned ranges.
5743   return SR.intersectWith(UR);
5744 }
5745 
5746 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5747                                                     const SCEV *Step,
5748                                                     const SCEV *MaxBECount,
5749                                                     unsigned BitWidth) {
5750   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5751   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5752 
5753   struct SelectPattern {
5754     Value *Condition = nullptr;
5755     APInt TrueValue;
5756     APInt FalseValue;
5757 
5758     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5759                            const SCEV *S) {
5760       Optional<unsigned> CastOp;
5761       APInt Offset(BitWidth, 0);
5762 
5763       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5764              "Should be!");
5765 
5766       // Peel off a constant offset:
5767       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5768         // In the future we could consider being smarter here and handle
5769         // {Start+Step,+,Step} too.
5770         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5771           return;
5772 
5773         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5774         S = SA->getOperand(1);
5775       }
5776 
5777       // Peel off a cast operation
5778       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5779         CastOp = SCast->getSCEVType();
5780         S = SCast->getOperand();
5781       }
5782 
5783       using namespace llvm::PatternMatch;
5784 
5785       auto *SU = dyn_cast<SCEVUnknown>(S);
5786       const APInt *TrueVal, *FalseVal;
5787       if (!SU ||
5788           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5789                                           m_APInt(FalseVal)))) {
5790         Condition = nullptr;
5791         return;
5792       }
5793 
5794       TrueValue = *TrueVal;
5795       FalseValue = *FalseVal;
5796 
5797       // Re-apply the cast we peeled off earlier
5798       if (CastOp.hasValue())
5799         switch (*CastOp) {
5800         default:
5801           llvm_unreachable("Unknown SCEV cast type!");
5802 
5803         case scTruncate:
5804           TrueValue = TrueValue.trunc(BitWidth);
5805           FalseValue = FalseValue.trunc(BitWidth);
5806           break;
5807         case scZeroExtend:
5808           TrueValue = TrueValue.zext(BitWidth);
5809           FalseValue = FalseValue.zext(BitWidth);
5810           break;
5811         case scSignExtend:
5812           TrueValue = TrueValue.sext(BitWidth);
5813           FalseValue = FalseValue.sext(BitWidth);
5814           break;
5815         }
5816 
5817       // Re-apply the constant offset we peeled off earlier
5818       TrueValue += Offset;
5819       FalseValue += Offset;
5820     }
5821 
5822     bool isRecognized() { return Condition != nullptr; }
5823   };
5824 
5825   SelectPattern StartPattern(*this, BitWidth, Start);
5826   if (!StartPattern.isRecognized())
5827     return ConstantRange(BitWidth, /* isFullSet = */ true);
5828 
5829   SelectPattern StepPattern(*this, BitWidth, Step);
5830   if (!StepPattern.isRecognized())
5831     return ConstantRange(BitWidth, /* isFullSet = */ true);
5832 
5833   if (StartPattern.Condition != StepPattern.Condition) {
5834     // We don't handle this case today; but we could, by considering four
5835     // possibilities below instead of two. I'm not sure if there are cases where
5836     // that will help over what getRange already does, though.
5837     return ConstantRange(BitWidth, /* isFullSet = */ true);
5838   }
5839 
5840   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5841   // construct arbitrary general SCEV expressions here.  This function is called
5842   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5843   // say) can end up caching a suboptimal value.
5844 
5845   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5846   // C2352 and C2512 (otherwise it isn't needed).
5847 
5848   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5849   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5850   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5851   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5852 
5853   ConstantRange TrueRange =
5854       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5855   ConstantRange FalseRange =
5856       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5857 
5858   return TrueRange.unionWith(FalseRange);
5859 }
5860 
5861 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5862   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5863   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5864 
5865   // Return early if there are no flags to propagate to the SCEV.
5866   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5867   if (BinOp->hasNoUnsignedWrap())
5868     Flags |= SCEV::FlagNUW;
5869   if (BinOp->hasNoSignedWrap())
5870     Flags |= SCEV::FlagNSW;
5871   if (Flags == SCEV::FlagAnyWrap)
5872     return SCEV::FlagAnyWrap;
5873 
5874   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5875 }
5876 
5877 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5878   // Here we check that I is in the header of the innermost loop containing I,
5879   // since we only deal with instructions in the loop header. The actual loop we
5880   // need to check later will come from an add recurrence, but getting that
5881   // requires computing the SCEV of the operands, which can be expensive. This
5882   // check we can do cheaply to rule out some cases early.
5883   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5884   if (InnermostContainingLoop == nullptr ||
5885       InnermostContainingLoop->getHeader() != I->getParent())
5886     return false;
5887 
5888   // Only proceed if we can prove that I does not yield poison.
5889   if (!programUndefinedIfFullPoison(I))
5890     return false;
5891 
5892   // At this point we know that if I is executed, then it does not wrap
5893   // according to at least one of NSW or NUW. If I is not executed, then we do
5894   // not know if the calculation that I represents would wrap. Multiple
5895   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5896   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5897   // derived from other instructions that map to the same SCEV. We cannot make
5898   // that guarantee for cases where I is not executed. So we need to find the
5899   // loop that I is considered in relation to and prove that I is executed for
5900   // every iteration of that loop. That implies that the value that I
5901   // calculates does not wrap anywhere in the loop, so then we can apply the
5902   // flags to the SCEV.
5903   //
5904   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5905   // from different loops, so that we know which loop to prove that I is
5906   // executed in.
5907   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5908     // I could be an extractvalue from a call to an overflow intrinsic.
5909     // TODO: We can do better here in some cases.
5910     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5911       return false;
5912     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5913     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5914       bool AllOtherOpsLoopInvariant = true;
5915       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5916            ++OtherOpIndex) {
5917         if (OtherOpIndex != OpIndex) {
5918           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5919           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5920             AllOtherOpsLoopInvariant = false;
5921             break;
5922           }
5923         }
5924       }
5925       if (AllOtherOpsLoopInvariant &&
5926           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5927         return true;
5928     }
5929   }
5930   return false;
5931 }
5932 
5933 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5934   // If we know that \c I can never be poison period, then that's enough.
5935   if (isSCEVExprNeverPoison(I))
5936     return true;
5937 
5938   // For an add recurrence specifically, we assume that infinite loops without
5939   // side effects are undefined behavior, and then reason as follows:
5940   //
5941   // If the add recurrence is poison in any iteration, it is poison on all
5942   // future iterations (since incrementing poison yields poison). If the result
5943   // of the add recurrence is fed into the loop latch condition and the loop
5944   // does not contain any throws or exiting blocks other than the latch, we now
5945   // have the ability to "choose" whether the backedge is taken or not (by
5946   // choosing a sufficiently evil value for the poison feeding into the branch)
5947   // for every iteration including and after the one in which \p I first became
5948   // poison.  There are two possibilities (let's call the iteration in which \p
5949   // I first became poison as K):
5950   //
5951   //  1. In the set of iterations including and after K, the loop body executes
5952   //     no side effects.  In this case executing the backege an infinte number
5953   //     of times will yield undefined behavior.
5954   //
5955   //  2. In the set of iterations including and after K, the loop body executes
5956   //     at least one side effect.  In this case, that specific instance of side
5957   //     effect is control dependent on poison, which also yields undefined
5958   //     behavior.
5959 
5960   auto *ExitingBB = L->getExitingBlock();
5961   auto *LatchBB = L->getLoopLatch();
5962   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5963     return false;
5964 
5965   SmallPtrSet<const Instruction *, 16> Pushed;
5966   SmallVector<const Instruction *, 8> PoisonStack;
5967 
5968   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5969   // things that are known to be fully poison under that assumption go on the
5970   // PoisonStack.
5971   Pushed.insert(I);
5972   PoisonStack.push_back(I);
5973 
5974   bool LatchControlDependentOnPoison = false;
5975   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5976     const Instruction *Poison = PoisonStack.pop_back_val();
5977 
5978     for (auto *PoisonUser : Poison->users()) {
5979       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5980         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5981           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5982       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5983         assert(BI->isConditional() && "Only possibility!");
5984         if (BI->getParent() == LatchBB) {
5985           LatchControlDependentOnPoison = true;
5986           break;
5987         }
5988       }
5989     }
5990   }
5991 
5992   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5993 }
5994 
5995 ScalarEvolution::LoopProperties
5996 ScalarEvolution::getLoopProperties(const Loop *L) {
5997   using LoopProperties = ScalarEvolution::LoopProperties;
5998 
5999   auto Itr = LoopPropertiesCache.find(L);
6000   if (Itr == LoopPropertiesCache.end()) {
6001     auto HasSideEffects = [](Instruction *I) {
6002       if (auto *SI = dyn_cast<StoreInst>(I))
6003         return !SI->isSimple();
6004 
6005       return I->mayHaveSideEffects();
6006     };
6007 
6008     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6009                          /*HasNoSideEffects*/ true};
6010 
6011     for (auto *BB : L->getBlocks())
6012       for (auto &I : *BB) {
6013         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6014           LP.HasNoAbnormalExits = false;
6015         if (HasSideEffects(&I))
6016           LP.HasNoSideEffects = false;
6017         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6018           break; // We're already as pessimistic as we can get.
6019       }
6020 
6021     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6022     assert(InsertPair.second && "We just checked!");
6023     Itr = InsertPair.first;
6024   }
6025 
6026   return Itr->second;
6027 }
6028 
6029 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6030   if (!isSCEVable(V->getType()))
6031     return getUnknown(V);
6032 
6033   if (Instruction *I = dyn_cast<Instruction>(V)) {
6034     // Don't attempt to analyze instructions in blocks that aren't
6035     // reachable. Such instructions don't matter, and they aren't required
6036     // to obey basic rules for definitions dominating uses which this
6037     // analysis depends on.
6038     if (!DT.isReachableFromEntry(I->getParent()))
6039       return getUnknown(V);
6040   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6041     return getConstant(CI);
6042   else if (isa<ConstantPointerNull>(V))
6043     return getZero(V->getType());
6044   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6045     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6046   else if (!isa<ConstantExpr>(V))
6047     return getUnknown(V);
6048 
6049   Operator *U = cast<Operator>(V);
6050   if (auto BO = MatchBinaryOp(U, DT)) {
6051     switch (BO->Opcode) {
6052     case Instruction::Add: {
6053       // The simple thing to do would be to just call getSCEV on both operands
6054       // and call getAddExpr with the result. However if we're looking at a
6055       // bunch of things all added together, this can be quite inefficient,
6056       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6057       // Instead, gather up all the operands and make a single getAddExpr call.
6058       // LLVM IR canonical form means we need only traverse the left operands.
6059       SmallVector<const SCEV *, 4> AddOps;
6060       do {
6061         if (BO->Op) {
6062           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6063             AddOps.push_back(OpSCEV);
6064             break;
6065           }
6066 
6067           // If a NUW or NSW flag can be applied to the SCEV for this
6068           // addition, then compute the SCEV for this addition by itself
6069           // with a separate call to getAddExpr. We need to do that
6070           // instead of pushing the operands of the addition onto AddOps,
6071           // since the flags are only known to apply to this particular
6072           // addition - they may not apply to other additions that can be
6073           // formed with operands from AddOps.
6074           const SCEV *RHS = getSCEV(BO->RHS);
6075           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6076           if (Flags != SCEV::FlagAnyWrap) {
6077             const SCEV *LHS = getSCEV(BO->LHS);
6078             if (BO->Opcode == Instruction::Sub)
6079               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6080             else
6081               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6082             break;
6083           }
6084         }
6085 
6086         if (BO->Opcode == Instruction::Sub)
6087           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6088         else
6089           AddOps.push_back(getSCEV(BO->RHS));
6090 
6091         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6092         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6093                        NewBO->Opcode != Instruction::Sub)) {
6094           AddOps.push_back(getSCEV(BO->LHS));
6095           break;
6096         }
6097         BO = NewBO;
6098       } while (true);
6099 
6100       return getAddExpr(AddOps);
6101     }
6102 
6103     case Instruction::Mul: {
6104       SmallVector<const SCEV *, 4> MulOps;
6105       do {
6106         if (BO->Op) {
6107           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6108             MulOps.push_back(OpSCEV);
6109             break;
6110           }
6111 
6112           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6113           if (Flags != SCEV::FlagAnyWrap) {
6114             MulOps.push_back(
6115                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6116             break;
6117           }
6118         }
6119 
6120         MulOps.push_back(getSCEV(BO->RHS));
6121         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6122         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6123           MulOps.push_back(getSCEV(BO->LHS));
6124           break;
6125         }
6126         BO = NewBO;
6127       } while (true);
6128 
6129       return getMulExpr(MulOps);
6130     }
6131     case Instruction::UDiv:
6132       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6133     case Instruction::URem:
6134       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6135     case Instruction::Sub: {
6136       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6137       if (BO->Op)
6138         Flags = getNoWrapFlagsFromUB(BO->Op);
6139       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6140     }
6141     case Instruction::And:
6142       // For an expression like x&255 that merely masks off the high bits,
6143       // use zext(trunc(x)) as the SCEV expression.
6144       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6145         if (CI->isZero())
6146           return getSCEV(BO->RHS);
6147         if (CI->isMinusOne())
6148           return getSCEV(BO->LHS);
6149         const APInt &A = CI->getValue();
6150 
6151         // Instcombine's ShrinkDemandedConstant may strip bits out of
6152         // constants, obscuring what would otherwise be a low-bits mask.
6153         // Use computeKnownBits to compute what ShrinkDemandedConstant
6154         // knew about to reconstruct a low-bits mask value.
6155         unsigned LZ = A.countLeadingZeros();
6156         unsigned TZ = A.countTrailingZeros();
6157         unsigned BitWidth = A.getBitWidth();
6158         KnownBits Known(BitWidth);
6159         computeKnownBits(BO->LHS, Known, getDataLayout(),
6160                          0, &AC, nullptr, &DT);
6161 
6162         APInt EffectiveMask =
6163             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6164         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6165           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6166           const SCEV *LHS = getSCEV(BO->LHS);
6167           const SCEV *ShiftedLHS = nullptr;
6168           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6169             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6170               // For an expression like (x * 8) & 8, simplify the multiply.
6171               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6172               unsigned GCD = std::min(MulZeros, TZ);
6173               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6174               SmallVector<const SCEV*, 4> MulOps;
6175               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6176               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6177               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6178               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6179             }
6180           }
6181           if (!ShiftedLHS)
6182             ShiftedLHS = getUDivExpr(LHS, MulCount);
6183           return getMulExpr(
6184               getZeroExtendExpr(
6185                   getTruncateExpr(ShiftedLHS,
6186                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6187                   BO->LHS->getType()),
6188               MulCount);
6189         }
6190       }
6191       break;
6192 
6193     case Instruction::Or:
6194       // If the RHS of the Or is a constant, we may have something like:
6195       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6196       // optimizations will transparently handle this case.
6197       //
6198       // In order for this transformation to be safe, the LHS must be of the
6199       // form X*(2^n) and the Or constant must be less than 2^n.
6200       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6201         const SCEV *LHS = getSCEV(BO->LHS);
6202         const APInt &CIVal = CI->getValue();
6203         if (GetMinTrailingZeros(LHS) >=
6204             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6205           // Build a plain add SCEV.
6206           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6207           // If the LHS of the add was an addrec and it has no-wrap flags,
6208           // transfer the no-wrap flags, since an or won't introduce a wrap.
6209           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6210             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6211             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6212                 OldAR->getNoWrapFlags());
6213           }
6214           return S;
6215         }
6216       }
6217       break;
6218 
6219     case Instruction::Xor:
6220       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6221         // If the RHS of xor is -1, then this is a not operation.
6222         if (CI->isMinusOne())
6223           return getNotSCEV(getSCEV(BO->LHS));
6224 
6225         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6226         // This is a variant of the check for xor with -1, and it handles
6227         // the case where instcombine has trimmed non-demanded bits out
6228         // of an xor with -1.
6229         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6230           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6231             if (LBO->getOpcode() == Instruction::And &&
6232                 LCI->getValue() == CI->getValue())
6233               if (const SCEVZeroExtendExpr *Z =
6234                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6235                 Type *UTy = BO->LHS->getType();
6236                 const SCEV *Z0 = Z->getOperand();
6237                 Type *Z0Ty = Z0->getType();
6238                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6239 
6240                 // If C is a low-bits mask, the zero extend is serving to
6241                 // mask off the high bits. Complement the operand and
6242                 // re-apply the zext.
6243                 if (CI->getValue().isMask(Z0TySize))
6244                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6245 
6246                 // If C is a single bit, it may be in the sign-bit position
6247                 // before the zero-extend. In this case, represent the xor
6248                 // using an add, which is equivalent, and re-apply the zext.
6249                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6250                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6251                     Trunc.isSignMask())
6252                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6253                                            UTy);
6254               }
6255       }
6256       break;
6257 
6258     case Instruction::Shl:
6259       // Turn shift left of a constant amount into a multiply.
6260       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6261         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6262 
6263         // If the shift count is not less than the bitwidth, the result of
6264         // the shift is undefined. Don't try to analyze it, because the
6265         // resolution chosen here may differ from the resolution chosen in
6266         // other parts of the compiler.
6267         if (SA->getValue().uge(BitWidth))
6268           break;
6269 
6270         // It is currently not resolved how to interpret NSW for left
6271         // shift by BitWidth - 1, so we avoid applying flags in that
6272         // case. Remove this check (or this comment) once the situation
6273         // is resolved. See
6274         // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6275         // and http://reviews.llvm.org/D8890 .
6276         auto Flags = SCEV::FlagAnyWrap;
6277         if (BO->Op && SA->getValue().ult(BitWidth - 1))
6278           Flags = getNoWrapFlagsFromUB(BO->Op);
6279 
6280         Constant *X = ConstantInt::get(
6281             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6282         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6283       }
6284       break;
6285 
6286     case Instruction::AShr: {
6287       // AShr X, C, where C is a constant.
6288       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6289       if (!CI)
6290         break;
6291 
6292       Type *OuterTy = BO->LHS->getType();
6293       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6294       // If the shift count is not less than the bitwidth, the result of
6295       // the shift is undefined. Don't try to analyze it, because the
6296       // resolution chosen here may differ from the resolution chosen in
6297       // other parts of the compiler.
6298       if (CI->getValue().uge(BitWidth))
6299         break;
6300 
6301       if (CI->isZero())
6302         return getSCEV(BO->LHS); // shift by zero --> noop
6303 
6304       uint64_t AShrAmt = CI->getZExtValue();
6305       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6306 
6307       Operator *L = dyn_cast<Operator>(BO->LHS);
6308       if (L && L->getOpcode() == Instruction::Shl) {
6309         // X = Shl A, n
6310         // Y = AShr X, m
6311         // Both n and m are constant.
6312 
6313         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6314         if (L->getOperand(1) == BO->RHS)
6315           // For a two-shift sext-inreg, i.e. n = m,
6316           // use sext(trunc(x)) as the SCEV expression.
6317           return getSignExtendExpr(
6318               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6319 
6320         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6321         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6322           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6323           if (ShlAmt > AShrAmt) {
6324             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6325             // expression. We already checked that ShlAmt < BitWidth, so
6326             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6327             // ShlAmt - AShrAmt < Amt.
6328             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6329                                             ShlAmt - AShrAmt);
6330             return getSignExtendExpr(
6331                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6332                 getConstant(Mul)), OuterTy);
6333           }
6334         }
6335       }
6336       break;
6337     }
6338     }
6339   }
6340 
6341   switch (U->getOpcode()) {
6342   case Instruction::Trunc:
6343     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6344 
6345   case Instruction::ZExt:
6346     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6347 
6348   case Instruction::SExt:
6349     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6350       // The NSW flag of a subtract does not always survive the conversion to
6351       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6352       // more likely to preserve NSW and allow later AddRec optimisations.
6353       //
6354       // NOTE: This is effectively duplicating this logic from getSignExtend:
6355       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6356       // but by that point the NSW information has potentially been lost.
6357       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6358         Type *Ty = U->getType();
6359         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6360         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6361         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6362       }
6363     }
6364     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6365 
6366   case Instruction::BitCast:
6367     // BitCasts are no-op casts so we just eliminate the cast.
6368     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6369       return getSCEV(U->getOperand(0));
6370     break;
6371 
6372   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6373   // lead to pointer expressions which cannot safely be expanded to GEPs,
6374   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6375   // simplifying integer expressions.
6376 
6377   case Instruction::GetElementPtr:
6378     return createNodeForGEP(cast<GEPOperator>(U));
6379 
6380   case Instruction::PHI:
6381     return createNodeForPHI(cast<PHINode>(U));
6382 
6383   case Instruction::Select:
6384     // U can also be a select constant expr, which let fall through.  Since
6385     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6386     // constant expressions cannot have instructions as operands, we'd have
6387     // returned getUnknown for a select constant expressions anyway.
6388     if (isa<Instruction>(U))
6389       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6390                                       U->getOperand(1), U->getOperand(2));
6391     break;
6392 
6393   case Instruction::Call:
6394   case Instruction::Invoke:
6395     if (Value *RV = CallSite(U).getReturnedArgOperand())
6396       return getSCEV(RV);
6397     break;
6398   }
6399 
6400   return getUnknown(V);
6401 }
6402 
6403 //===----------------------------------------------------------------------===//
6404 //                   Iteration Count Computation Code
6405 //
6406 
6407 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6408   if (!ExitCount)
6409     return 0;
6410 
6411   ConstantInt *ExitConst = ExitCount->getValue();
6412 
6413   // Guard against huge trip counts.
6414   if (ExitConst->getValue().getActiveBits() > 32)
6415     return 0;
6416 
6417   // In case of integer overflow, this returns 0, which is correct.
6418   return ((unsigned)ExitConst->getZExtValue()) + 1;
6419 }
6420 
6421 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6422   if (BasicBlock *ExitingBB = L->getExitingBlock())
6423     return getSmallConstantTripCount(L, ExitingBB);
6424 
6425   // No trip count information for multiple exits.
6426   return 0;
6427 }
6428 
6429 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6430                                                     BasicBlock *ExitingBlock) {
6431   assert(ExitingBlock && "Must pass a non-null exiting block!");
6432   assert(L->isLoopExiting(ExitingBlock) &&
6433          "Exiting block must actually branch out of the loop!");
6434   const SCEVConstant *ExitCount =
6435       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6436   return getConstantTripCount(ExitCount);
6437 }
6438 
6439 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6440   const auto *MaxExitCount =
6441       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6442   return getConstantTripCount(MaxExitCount);
6443 }
6444 
6445 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6446   if (BasicBlock *ExitingBB = L->getExitingBlock())
6447     return getSmallConstantTripMultiple(L, ExitingBB);
6448 
6449   // No trip multiple information for multiple exits.
6450   return 0;
6451 }
6452 
6453 /// Returns the largest constant divisor of the trip count of this loop as a
6454 /// normal unsigned value, if possible. This means that the actual trip count is
6455 /// always a multiple of the returned value (don't forget the trip count could
6456 /// very well be zero as well!).
6457 ///
6458 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6459 /// multiple of a constant (which is also the case if the trip count is simply
6460 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6461 /// if the trip count is very large (>= 2^32).
6462 ///
6463 /// As explained in the comments for getSmallConstantTripCount, this assumes
6464 /// that control exits the loop via ExitingBlock.
6465 unsigned
6466 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6467                                               BasicBlock *ExitingBlock) {
6468   assert(ExitingBlock && "Must pass a non-null exiting block!");
6469   assert(L->isLoopExiting(ExitingBlock) &&
6470          "Exiting block must actually branch out of the loop!");
6471   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6472   if (ExitCount == getCouldNotCompute())
6473     return 1;
6474 
6475   // Get the trip count from the BE count by adding 1.
6476   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6477 
6478   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6479   if (!TC)
6480     // Attempt to factor more general cases. Returns the greatest power of
6481     // two divisor. If overflow happens, the trip count expression is still
6482     // divisible by the greatest power of 2 divisor returned.
6483     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6484 
6485   ConstantInt *Result = TC->getValue();
6486 
6487   // Guard against huge trip counts (this requires checking
6488   // for zero to handle the case where the trip count == -1 and the
6489   // addition wraps).
6490   if (!Result || Result->getValue().getActiveBits() > 32 ||
6491       Result->getValue().getActiveBits() == 0)
6492     return 1;
6493 
6494   return (unsigned)Result->getZExtValue();
6495 }
6496 
6497 /// Get the expression for the number of loop iterations for which this loop is
6498 /// guaranteed not to exit via ExitingBlock. Otherwise return
6499 /// SCEVCouldNotCompute.
6500 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6501                                           BasicBlock *ExitingBlock) {
6502   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6503 }
6504 
6505 const SCEV *
6506 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6507                                                  SCEVUnionPredicate &Preds) {
6508   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6509 }
6510 
6511 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6512   return getBackedgeTakenInfo(L).getExact(L, this);
6513 }
6514 
6515 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6516 /// known never to be less than the actual backedge taken count.
6517 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6518   return getBackedgeTakenInfo(L).getMax(this);
6519 }
6520 
6521 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6522   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6523 }
6524 
6525 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6526 static void
6527 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6528   BasicBlock *Header = L->getHeader();
6529 
6530   // Push all Loop-header PHIs onto the Worklist stack.
6531   for (PHINode &PN : Header->phis())
6532     Worklist.push_back(&PN);
6533 }
6534 
6535 const ScalarEvolution::BackedgeTakenInfo &
6536 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6537   auto &BTI = getBackedgeTakenInfo(L);
6538   if (BTI.hasFullInfo())
6539     return BTI;
6540 
6541   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6542 
6543   if (!Pair.second)
6544     return Pair.first->second;
6545 
6546   BackedgeTakenInfo Result =
6547       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6548 
6549   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6550 }
6551 
6552 const ScalarEvolution::BackedgeTakenInfo &
6553 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6554   // Initially insert an invalid entry for this loop. If the insertion
6555   // succeeds, proceed to actually compute a backedge-taken count and
6556   // update the value. The temporary CouldNotCompute value tells SCEV
6557   // code elsewhere that it shouldn't attempt to request a new
6558   // backedge-taken count, which could result in infinite recursion.
6559   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6560       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6561   if (!Pair.second)
6562     return Pair.first->second;
6563 
6564   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6565   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6566   // must be cleared in this scope.
6567   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6568 
6569   // In product build, there are no usage of statistic.
6570   (void)NumTripCountsComputed;
6571   (void)NumTripCountsNotComputed;
6572 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6573   const SCEV *BEExact = Result.getExact(L, this);
6574   if (BEExact != getCouldNotCompute()) {
6575     assert(isLoopInvariant(BEExact, L) &&
6576            isLoopInvariant(Result.getMax(this), L) &&
6577            "Computed backedge-taken count isn't loop invariant for loop!");
6578     ++NumTripCountsComputed;
6579   }
6580   else if (Result.getMax(this) == getCouldNotCompute() &&
6581            isa<PHINode>(L->getHeader()->begin())) {
6582     // Only count loops that have phi nodes as not being computable.
6583     ++NumTripCountsNotComputed;
6584   }
6585 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6586 
6587   // Now that we know more about the trip count for this loop, forget any
6588   // existing SCEV values for PHI nodes in this loop since they are only
6589   // conservative estimates made without the benefit of trip count
6590   // information. This is similar to the code in forgetLoop, except that
6591   // it handles SCEVUnknown PHI nodes specially.
6592   if (Result.hasAnyInfo()) {
6593     SmallVector<Instruction *, 16> Worklist;
6594     PushLoopPHIs(L, Worklist);
6595 
6596     SmallPtrSet<Instruction *, 8> Discovered;
6597     while (!Worklist.empty()) {
6598       Instruction *I = Worklist.pop_back_val();
6599 
6600       ValueExprMapType::iterator It =
6601         ValueExprMap.find_as(static_cast<Value *>(I));
6602       if (It != ValueExprMap.end()) {
6603         const SCEV *Old = It->second;
6604 
6605         // SCEVUnknown for a PHI either means that it has an unrecognized
6606         // structure, or it's a PHI that's in the progress of being computed
6607         // by createNodeForPHI.  In the former case, additional loop trip
6608         // count information isn't going to change anything. In the later
6609         // case, createNodeForPHI will perform the necessary updates on its
6610         // own when it gets to that point.
6611         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6612           eraseValueFromMap(It->first);
6613           forgetMemoizedResults(Old);
6614         }
6615         if (PHINode *PN = dyn_cast<PHINode>(I))
6616           ConstantEvolutionLoopExitValue.erase(PN);
6617       }
6618 
6619       // Since we don't need to invalidate anything for correctness and we're
6620       // only invalidating to make SCEV's results more precise, we get to stop
6621       // early to avoid invalidating too much.  This is especially important in
6622       // cases like:
6623       //
6624       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6625       // loop0:
6626       //   %pn0 = phi
6627       //   ...
6628       // loop1:
6629       //   %pn1 = phi
6630       //   ...
6631       //
6632       // where both loop0 and loop1's backedge taken count uses the SCEV
6633       // expression for %v.  If we don't have the early stop below then in cases
6634       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6635       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6636       // count for loop1, effectively nullifying SCEV's trip count cache.
6637       for (auto *U : I->users())
6638         if (auto *I = dyn_cast<Instruction>(U)) {
6639           auto *LoopForUser = LI.getLoopFor(I->getParent());
6640           if (LoopForUser && L->contains(LoopForUser) &&
6641               Discovered.insert(I).second)
6642             Worklist.push_back(I);
6643         }
6644     }
6645   }
6646 
6647   // Re-lookup the insert position, since the call to
6648   // computeBackedgeTakenCount above could result in a
6649   // recusive call to getBackedgeTakenInfo (on a different
6650   // loop), which would invalidate the iterator computed
6651   // earlier.
6652   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6653 }
6654 
6655 void ScalarEvolution::forgetLoop(const Loop *L) {
6656   // Drop any stored trip count value.
6657   auto RemoveLoopFromBackedgeMap =
6658       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6659         auto BTCPos = Map.find(L);
6660         if (BTCPos != Map.end()) {
6661           BTCPos->second.clear();
6662           Map.erase(BTCPos);
6663         }
6664       };
6665 
6666   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6667   SmallVector<Instruction *, 32> Worklist;
6668   SmallPtrSet<Instruction *, 16> Visited;
6669 
6670   // Iterate over all the loops and sub-loops to drop SCEV information.
6671   while (!LoopWorklist.empty()) {
6672     auto *CurrL = LoopWorklist.pop_back_val();
6673 
6674     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6675     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6676 
6677     // Drop information about predicated SCEV rewrites for this loop.
6678     for (auto I = PredicatedSCEVRewrites.begin();
6679          I != PredicatedSCEVRewrites.end();) {
6680       std::pair<const SCEV *, const Loop *> Entry = I->first;
6681       if (Entry.second == CurrL)
6682         PredicatedSCEVRewrites.erase(I++);
6683       else
6684         ++I;
6685     }
6686 
6687     auto LoopUsersItr = LoopUsers.find(CurrL);
6688     if (LoopUsersItr != LoopUsers.end()) {
6689       for (auto *S : LoopUsersItr->second)
6690         forgetMemoizedResults(S);
6691       LoopUsers.erase(LoopUsersItr);
6692     }
6693 
6694     // Drop information about expressions based on loop-header PHIs.
6695     PushLoopPHIs(CurrL, Worklist);
6696 
6697     while (!Worklist.empty()) {
6698       Instruction *I = Worklist.pop_back_val();
6699       if (!Visited.insert(I).second)
6700         continue;
6701 
6702       ValueExprMapType::iterator It =
6703           ValueExprMap.find_as(static_cast<Value *>(I));
6704       if (It != ValueExprMap.end()) {
6705         eraseValueFromMap(It->first);
6706         forgetMemoizedResults(It->second);
6707         if (PHINode *PN = dyn_cast<PHINode>(I))
6708           ConstantEvolutionLoopExitValue.erase(PN);
6709       }
6710 
6711       PushDefUseChildren(I, Worklist);
6712     }
6713 
6714     LoopPropertiesCache.erase(CurrL);
6715     // Forget all contained loops too, to avoid dangling entries in the
6716     // ValuesAtScopes map.
6717     LoopWorklist.append(CurrL->begin(), CurrL->end());
6718   }
6719 }
6720 
6721 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6722   while (Loop *Parent = L->getParentLoop())
6723     L = Parent;
6724   forgetLoop(L);
6725 }
6726 
6727 void ScalarEvolution::forgetValue(Value *V) {
6728   Instruction *I = dyn_cast<Instruction>(V);
6729   if (!I) return;
6730 
6731   // Drop information about expressions based on loop-header PHIs.
6732   SmallVector<Instruction *, 16> Worklist;
6733   Worklist.push_back(I);
6734 
6735   SmallPtrSet<Instruction *, 8> Visited;
6736   while (!Worklist.empty()) {
6737     I = Worklist.pop_back_val();
6738     if (!Visited.insert(I).second)
6739       continue;
6740 
6741     ValueExprMapType::iterator It =
6742       ValueExprMap.find_as(static_cast<Value *>(I));
6743     if (It != ValueExprMap.end()) {
6744       eraseValueFromMap(It->first);
6745       forgetMemoizedResults(It->second);
6746       if (PHINode *PN = dyn_cast<PHINode>(I))
6747         ConstantEvolutionLoopExitValue.erase(PN);
6748     }
6749 
6750     PushDefUseChildren(I, Worklist);
6751   }
6752 }
6753 
6754 /// Get the exact loop backedge taken count considering all loop exits. A
6755 /// computable result can only be returned for loops with all exiting blocks
6756 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6757 /// is never skipped. This is a valid assumption as long as the loop exits via
6758 /// that test. For precise results, it is the caller's responsibility to specify
6759 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6760 const SCEV *
6761 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6762                                              SCEVUnionPredicate *Preds) const {
6763   // If any exits were not computable, the loop is not computable.
6764   if (!isComplete() || ExitNotTaken.empty())
6765     return SE->getCouldNotCompute();
6766 
6767   const BasicBlock *Latch = L->getLoopLatch();
6768   // All exiting blocks we have collected must dominate the only backedge.
6769   if (!Latch)
6770     return SE->getCouldNotCompute();
6771 
6772   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6773   // count is simply a minimum out of all these calculated exit counts.
6774   SmallVector<const SCEV *, 2> Ops;
6775   for (auto &ENT : ExitNotTaken) {
6776     const SCEV *BECount = ENT.ExactNotTaken;
6777     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6778     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6779            "We should only have known counts for exiting blocks that dominate "
6780            "latch!");
6781 
6782     Ops.push_back(BECount);
6783 
6784     if (Preds && !ENT.hasAlwaysTruePredicate())
6785       Preds->add(ENT.Predicate.get());
6786 
6787     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6788            "Predicate should be always true!");
6789   }
6790 
6791   return SE->getUMinFromMismatchedTypes(Ops);
6792 }
6793 
6794 /// Get the exact not taken count for this loop exit.
6795 const SCEV *
6796 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6797                                              ScalarEvolution *SE) const {
6798   for (auto &ENT : ExitNotTaken)
6799     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6800       return ENT.ExactNotTaken;
6801 
6802   return SE->getCouldNotCompute();
6803 }
6804 
6805 /// getMax - Get the max backedge taken count for the loop.
6806 const SCEV *
6807 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6808   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6809     return !ENT.hasAlwaysTruePredicate();
6810   };
6811 
6812   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6813     return SE->getCouldNotCompute();
6814 
6815   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6816          "No point in having a non-constant max backedge taken count!");
6817   return getMax();
6818 }
6819 
6820 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6821   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6822     return !ENT.hasAlwaysTruePredicate();
6823   };
6824   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6825 }
6826 
6827 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6828                                                     ScalarEvolution *SE) const {
6829   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6830       SE->hasOperand(getMax(), S))
6831     return true;
6832 
6833   for (auto &ENT : ExitNotTaken)
6834     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6835         SE->hasOperand(ENT.ExactNotTaken, S))
6836       return true;
6837 
6838   return false;
6839 }
6840 
6841 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6842     : ExactNotTaken(E), MaxNotTaken(E) {
6843   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6844           isa<SCEVConstant>(MaxNotTaken)) &&
6845          "No point in having a non-constant max backedge taken count!");
6846 }
6847 
6848 ScalarEvolution::ExitLimit::ExitLimit(
6849     const SCEV *E, const SCEV *M, bool MaxOrZero,
6850     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6851     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6852   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6853           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6854          "Exact is not allowed to be less precise than Max");
6855   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6856           isa<SCEVConstant>(MaxNotTaken)) &&
6857          "No point in having a non-constant max backedge taken count!");
6858   for (auto *PredSet : PredSetList)
6859     for (auto *P : *PredSet)
6860       addPredicate(P);
6861 }
6862 
6863 ScalarEvolution::ExitLimit::ExitLimit(
6864     const SCEV *E, const SCEV *M, bool MaxOrZero,
6865     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6866     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6867   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6868           isa<SCEVConstant>(MaxNotTaken)) &&
6869          "No point in having a non-constant max backedge taken count!");
6870 }
6871 
6872 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6873                                       bool MaxOrZero)
6874     : ExitLimit(E, M, MaxOrZero, None) {
6875   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6876           isa<SCEVConstant>(MaxNotTaken)) &&
6877          "No point in having a non-constant max backedge taken count!");
6878 }
6879 
6880 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6881 /// computable exit into a persistent ExitNotTakenInfo array.
6882 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6883     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6884         &&ExitCounts,
6885     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6886     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6887   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6888 
6889   ExitNotTaken.reserve(ExitCounts.size());
6890   std::transform(
6891       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6892       [&](const EdgeExitInfo &EEI) {
6893         BasicBlock *ExitBB = EEI.first;
6894         const ExitLimit &EL = EEI.second;
6895         if (EL.Predicates.empty())
6896           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6897 
6898         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6899         for (auto *Pred : EL.Predicates)
6900           Predicate->add(Pred);
6901 
6902         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6903       });
6904   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6905          "No point in having a non-constant max backedge taken count!");
6906 }
6907 
6908 /// Invalidate this result and free the ExitNotTakenInfo array.
6909 void ScalarEvolution::BackedgeTakenInfo::clear() {
6910   ExitNotTaken.clear();
6911 }
6912 
6913 /// Compute the number of times the backedge of the specified loop will execute.
6914 ScalarEvolution::BackedgeTakenInfo
6915 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6916                                            bool AllowPredicates) {
6917   SmallVector<BasicBlock *, 8> ExitingBlocks;
6918   L->getExitingBlocks(ExitingBlocks);
6919 
6920   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6921 
6922   SmallVector<EdgeExitInfo, 4> ExitCounts;
6923   bool CouldComputeBECount = true;
6924   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6925   const SCEV *MustExitMaxBECount = nullptr;
6926   const SCEV *MayExitMaxBECount = nullptr;
6927   bool MustExitMaxOrZero = false;
6928 
6929   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6930   // and compute maxBECount.
6931   // Do a union of all the predicates here.
6932   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6933     BasicBlock *ExitBB = ExitingBlocks[i];
6934     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6935 
6936     assert((AllowPredicates || EL.Predicates.empty()) &&
6937            "Predicated exit limit when predicates are not allowed!");
6938 
6939     // 1. For each exit that can be computed, add an entry to ExitCounts.
6940     // CouldComputeBECount is true only if all exits can be computed.
6941     if (EL.ExactNotTaken == getCouldNotCompute())
6942       // We couldn't compute an exact value for this exit, so
6943       // we won't be able to compute an exact value for the loop.
6944       CouldComputeBECount = false;
6945     else
6946       ExitCounts.emplace_back(ExitBB, EL);
6947 
6948     // 2. Derive the loop's MaxBECount from each exit's max number of
6949     // non-exiting iterations. Partition the loop exits into two kinds:
6950     // LoopMustExits and LoopMayExits.
6951     //
6952     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6953     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6954     // MaxBECount is the minimum EL.MaxNotTaken of computable
6955     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6956     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6957     // computable EL.MaxNotTaken.
6958     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6959         DT.dominates(ExitBB, Latch)) {
6960       if (!MustExitMaxBECount) {
6961         MustExitMaxBECount = EL.MaxNotTaken;
6962         MustExitMaxOrZero = EL.MaxOrZero;
6963       } else {
6964         MustExitMaxBECount =
6965             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6966       }
6967     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6968       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6969         MayExitMaxBECount = EL.MaxNotTaken;
6970       else {
6971         MayExitMaxBECount =
6972             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6973       }
6974     }
6975   }
6976   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6977     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6978   // The loop backedge will be taken the maximum or zero times if there's
6979   // a single exit that must be taken the maximum or zero times.
6980   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6981   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6982                            MaxBECount, MaxOrZero);
6983 }
6984 
6985 ScalarEvolution::ExitLimit
6986 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6987                                       bool AllowPredicates) {
6988   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
6989   // If our exiting block does not dominate the latch, then its connection with
6990   // loop's exit limit may be far from trivial.
6991   const BasicBlock *Latch = L->getLoopLatch();
6992   if (!Latch || !DT.dominates(ExitingBlock, Latch))
6993     return getCouldNotCompute();
6994 
6995   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6996   TerminatorInst *Term = ExitingBlock->getTerminator();
6997   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6998     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6999     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7000     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7001            "It should have one successor in loop and one exit block!");
7002     // Proceed to the next level to examine the exit condition expression.
7003     return computeExitLimitFromCond(
7004         L, BI->getCondition(), ExitIfTrue,
7005         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7006   }
7007 
7008   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7009     // For switch, make sure that there is a single exit from the loop.
7010     BasicBlock *Exit = nullptr;
7011     for (auto *SBB : successors(ExitingBlock))
7012       if (!L->contains(SBB)) {
7013         if (Exit) // Multiple exit successors.
7014           return getCouldNotCompute();
7015         Exit = SBB;
7016       }
7017     assert(Exit && "Exiting block must have at least one exit");
7018     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7019                                                 /*ControlsExit=*/IsOnlyExit);
7020   }
7021 
7022   return getCouldNotCompute();
7023 }
7024 
7025 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7026     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7027     bool ControlsExit, bool AllowPredicates) {
7028   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7029   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7030                                         ControlsExit, AllowPredicates);
7031 }
7032 
7033 Optional<ScalarEvolution::ExitLimit>
7034 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7035                                       bool ExitIfTrue, bool ControlsExit,
7036                                       bool AllowPredicates) {
7037   (void)this->L;
7038   (void)this->ExitIfTrue;
7039   (void)this->AllowPredicates;
7040 
7041   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7042          this->AllowPredicates == AllowPredicates &&
7043          "Variance in assumed invariant key components!");
7044   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7045   if (Itr == TripCountMap.end())
7046     return None;
7047   return Itr->second;
7048 }
7049 
7050 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7051                                              bool ExitIfTrue,
7052                                              bool ControlsExit,
7053                                              bool AllowPredicates,
7054                                              const ExitLimit &EL) {
7055   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7056          this->AllowPredicates == AllowPredicates &&
7057          "Variance in assumed invariant key components!");
7058 
7059   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7060   assert(InsertResult.second && "Expected successful insertion!");
7061   (void)InsertResult;
7062   (void)ExitIfTrue;
7063 }
7064 
7065 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7066     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7067     bool ControlsExit, bool AllowPredicates) {
7068 
7069   if (auto MaybeEL =
7070           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7071     return *MaybeEL;
7072 
7073   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7074                                               ControlsExit, AllowPredicates);
7075   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7076   return EL;
7077 }
7078 
7079 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7080     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7081     bool ControlsExit, bool AllowPredicates) {
7082   // Check if the controlling expression for this loop is an And or Or.
7083   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7084     if (BO->getOpcode() == Instruction::And) {
7085       // Recurse on the operands of the and.
7086       bool EitherMayExit = !ExitIfTrue;
7087       ExitLimit EL0 = computeExitLimitFromCondCached(
7088           Cache, L, BO->getOperand(0), ExitIfTrue,
7089           ControlsExit && !EitherMayExit, AllowPredicates);
7090       ExitLimit EL1 = computeExitLimitFromCondCached(
7091           Cache, L, BO->getOperand(1), ExitIfTrue,
7092           ControlsExit && !EitherMayExit, AllowPredicates);
7093       const SCEV *BECount = getCouldNotCompute();
7094       const SCEV *MaxBECount = getCouldNotCompute();
7095       if (EitherMayExit) {
7096         // Both conditions must be true for the loop to continue executing.
7097         // Choose the less conservative count.
7098         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7099             EL1.ExactNotTaken == getCouldNotCompute())
7100           BECount = getCouldNotCompute();
7101         else
7102           BECount =
7103               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7104         if (EL0.MaxNotTaken == getCouldNotCompute())
7105           MaxBECount = EL1.MaxNotTaken;
7106         else if (EL1.MaxNotTaken == getCouldNotCompute())
7107           MaxBECount = EL0.MaxNotTaken;
7108         else
7109           MaxBECount =
7110               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7111       } else {
7112         // Both conditions must be true at the same time for the loop to exit.
7113         // For now, be conservative.
7114         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7115           MaxBECount = EL0.MaxNotTaken;
7116         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7117           BECount = EL0.ExactNotTaken;
7118       }
7119 
7120       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7121       // to be more aggressive when computing BECount than when computing
7122       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7123       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7124       // to not.
7125       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7126           !isa<SCEVCouldNotCompute>(BECount))
7127         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7128 
7129       return ExitLimit(BECount, MaxBECount, false,
7130                        {&EL0.Predicates, &EL1.Predicates});
7131     }
7132     if (BO->getOpcode() == Instruction::Or) {
7133       // Recurse on the operands of the or.
7134       bool EitherMayExit = ExitIfTrue;
7135       ExitLimit EL0 = computeExitLimitFromCondCached(
7136           Cache, L, BO->getOperand(0), ExitIfTrue,
7137           ControlsExit && !EitherMayExit, AllowPredicates);
7138       ExitLimit EL1 = computeExitLimitFromCondCached(
7139           Cache, L, BO->getOperand(1), ExitIfTrue,
7140           ControlsExit && !EitherMayExit, AllowPredicates);
7141       const SCEV *BECount = getCouldNotCompute();
7142       const SCEV *MaxBECount = getCouldNotCompute();
7143       if (EitherMayExit) {
7144         // Both conditions must be false for the loop to continue executing.
7145         // Choose the less conservative count.
7146         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7147             EL1.ExactNotTaken == getCouldNotCompute())
7148           BECount = getCouldNotCompute();
7149         else
7150           BECount =
7151               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7152         if (EL0.MaxNotTaken == getCouldNotCompute())
7153           MaxBECount = EL1.MaxNotTaken;
7154         else if (EL1.MaxNotTaken == getCouldNotCompute())
7155           MaxBECount = EL0.MaxNotTaken;
7156         else
7157           MaxBECount =
7158               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7159       } else {
7160         // Both conditions must be false at the same time for the loop to exit.
7161         // For now, be conservative.
7162         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7163           MaxBECount = EL0.MaxNotTaken;
7164         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7165           BECount = EL0.ExactNotTaken;
7166       }
7167 
7168       return ExitLimit(BECount, MaxBECount, false,
7169                        {&EL0.Predicates, &EL1.Predicates});
7170     }
7171   }
7172 
7173   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7174   // Proceed to the next level to examine the icmp.
7175   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7176     ExitLimit EL =
7177         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7178     if (EL.hasFullInfo() || !AllowPredicates)
7179       return EL;
7180 
7181     // Try again, but use SCEV predicates this time.
7182     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7183                                     /*AllowPredicates=*/true);
7184   }
7185 
7186   // Check for a constant condition. These are normally stripped out by
7187   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7188   // preserve the CFG and is temporarily leaving constant conditions
7189   // in place.
7190   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7191     if (ExitIfTrue == !CI->getZExtValue())
7192       // The backedge is always taken.
7193       return getCouldNotCompute();
7194     else
7195       // The backedge is never taken.
7196       return getZero(CI->getType());
7197   }
7198 
7199   // If it's not an integer or pointer comparison then compute it the hard way.
7200   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7201 }
7202 
7203 ScalarEvolution::ExitLimit
7204 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7205                                           ICmpInst *ExitCond,
7206                                           bool ExitIfTrue,
7207                                           bool ControlsExit,
7208                                           bool AllowPredicates) {
7209   // If the condition was exit on true, convert the condition to exit on false
7210   ICmpInst::Predicate Pred;
7211   if (!ExitIfTrue)
7212     Pred = ExitCond->getPredicate();
7213   else
7214     Pred = ExitCond->getInversePredicate();
7215   const ICmpInst::Predicate OriginalPred = Pred;
7216 
7217   // Handle common loops like: for (X = "string"; *X; ++X)
7218   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7219     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7220       ExitLimit ItCnt =
7221         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7222       if (ItCnt.hasAnyInfo())
7223         return ItCnt;
7224     }
7225 
7226   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7227   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7228 
7229   // Try to evaluate any dependencies out of the loop.
7230   LHS = getSCEVAtScope(LHS, L);
7231   RHS = getSCEVAtScope(RHS, L);
7232 
7233   // At this point, we would like to compute how many iterations of the
7234   // loop the predicate will return true for these inputs.
7235   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7236     // If there is a loop-invariant, force it into the RHS.
7237     std::swap(LHS, RHS);
7238     Pred = ICmpInst::getSwappedPredicate(Pred);
7239   }
7240 
7241   // Simplify the operands before analyzing them.
7242   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7243 
7244   // If we have a comparison of a chrec against a constant, try to use value
7245   // ranges to answer this query.
7246   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7247     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7248       if (AddRec->getLoop() == L) {
7249         // Form the constant range.
7250         ConstantRange CompRange =
7251             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7252 
7253         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7254         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7255       }
7256 
7257   switch (Pred) {
7258   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7259     // Convert to: while (X-Y != 0)
7260     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7261                                 AllowPredicates);
7262     if (EL.hasAnyInfo()) return EL;
7263     break;
7264   }
7265   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7266     // Convert to: while (X-Y == 0)
7267     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7268     if (EL.hasAnyInfo()) return EL;
7269     break;
7270   }
7271   case ICmpInst::ICMP_SLT:
7272   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7273     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7274     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7275                                     AllowPredicates);
7276     if (EL.hasAnyInfo()) return EL;
7277     break;
7278   }
7279   case ICmpInst::ICMP_SGT:
7280   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7281     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7282     ExitLimit EL =
7283         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7284                             AllowPredicates);
7285     if (EL.hasAnyInfo()) return EL;
7286     break;
7287   }
7288   default:
7289     break;
7290   }
7291 
7292   auto *ExhaustiveCount =
7293       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7294 
7295   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7296     return ExhaustiveCount;
7297 
7298   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7299                                       ExitCond->getOperand(1), L, OriginalPred);
7300 }
7301 
7302 ScalarEvolution::ExitLimit
7303 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7304                                                       SwitchInst *Switch,
7305                                                       BasicBlock *ExitingBlock,
7306                                                       bool ControlsExit) {
7307   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7308 
7309   // Give up if the exit is the default dest of a switch.
7310   if (Switch->getDefaultDest() == ExitingBlock)
7311     return getCouldNotCompute();
7312 
7313   assert(L->contains(Switch->getDefaultDest()) &&
7314          "Default case must not exit the loop!");
7315   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7316   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7317 
7318   // while (X != Y) --> while (X-Y != 0)
7319   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7320   if (EL.hasAnyInfo())
7321     return EL;
7322 
7323   return getCouldNotCompute();
7324 }
7325 
7326 static ConstantInt *
7327 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7328                                 ScalarEvolution &SE) {
7329   const SCEV *InVal = SE.getConstant(C);
7330   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7331   assert(isa<SCEVConstant>(Val) &&
7332          "Evaluation of SCEV at constant didn't fold correctly?");
7333   return cast<SCEVConstant>(Val)->getValue();
7334 }
7335 
7336 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7337 /// compute the backedge execution count.
7338 ScalarEvolution::ExitLimit
7339 ScalarEvolution::computeLoadConstantCompareExitLimit(
7340   LoadInst *LI,
7341   Constant *RHS,
7342   const Loop *L,
7343   ICmpInst::Predicate predicate) {
7344   if (LI->isVolatile()) return getCouldNotCompute();
7345 
7346   // Check to see if the loaded pointer is a getelementptr of a global.
7347   // TODO: Use SCEV instead of manually grubbing with GEPs.
7348   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7349   if (!GEP) return getCouldNotCompute();
7350 
7351   // Make sure that it is really a constant global we are gepping, with an
7352   // initializer, and make sure the first IDX is really 0.
7353   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7354   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7355       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7356       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7357     return getCouldNotCompute();
7358 
7359   // Okay, we allow one non-constant index into the GEP instruction.
7360   Value *VarIdx = nullptr;
7361   std::vector<Constant*> Indexes;
7362   unsigned VarIdxNum = 0;
7363   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7364     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7365       Indexes.push_back(CI);
7366     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7367       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7368       VarIdx = GEP->getOperand(i);
7369       VarIdxNum = i-2;
7370       Indexes.push_back(nullptr);
7371     }
7372 
7373   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7374   if (!VarIdx)
7375     return getCouldNotCompute();
7376 
7377   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7378   // Check to see if X is a loop variant variable value now.
7379   const SCEV *Idx = getSCEV(VarIdx);
7380   Idx = getSCEVAtScope(Idx, L);
7381 
7382   // We can only recognize very limited forms of loop index expressions, in
7383   // particular, only affine AddRec's like {C1,+,C2}.
7384   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7385   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7386       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7387       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7388     return getCouldNotCompute();
7389 
7390   unsigned MaxSteps = MaxBruteForceIterations;
7391   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7392     ConstantInt *ItCst = ConstantInt::get(
7393                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7394     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7395 
7396     // Form the GEP offset.
7397     Indexes[VarIdxNum] = Val;
7398 
7399     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7400                                                          Indexes);
7401     if (!Result) break;  // Cannot compute!
7402 
7403     // Evaluate the condition for this iteration.
7404     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7405     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7406     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7407       ++NumArrayLenItCounts;
7408       return getConstant(ItCst);   // Found terminating iteration!
7409     }
7410   }
7411   return getCouldNotCompute();
7412 }
7413 
7414 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7415     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7416   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7417   if (!RHS)
7418     return getCouldNotCompute();
7419 
7420   const BasicBlock *Latch = L->getLoopLatch();
7421   if (!Latch)
7422     return getCouldNotCompute();
7423 
7424   const BasicBlock *Predecessor = L->getLoopPredecessor();
7425   if (!Predecessor)
7426     return getCouldNotCompute();
7427 
7428   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7429   // Return LHS in OutLHS and shift_opt in OutOpCode.
7430   auto MatchPositiveShift =
7431       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7432 
7433     using namespace PatternMatch;
7434 
7435     ConstantInt *ShiftAmt;
7436     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7437       OutOpCode = Instruction::LShr;
7438     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7439       OutOpCode = Instruction::AShr;
7440     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7441       OutOpCode = Instruction::Shl;
7442     else
7443       return false;
7444 
7445     return ShiftAmt->getValue().isStrictlyPositive();
7446   };
7447 
7448   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7449   //
7450   // loop:
7451   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7452   //   %iv.shifted = lshr i32 %iv, <positive constant>
7453   //
7454   // Return true on a successful match.  Return the corresponding PHI node (%iv
7455   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7456   auto MatchShiftRecurrence =
7457       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7458     Optional<Instruction::BinaryOps> PostShiftOpCode;
7459 
7460     {
7461       Instruction::BinaryOps OpC;
7462       Value *V;
7463 
7464       // If we encounter a shift instruction, "peel off" the shift operation,
7465       // and remember that we did so.  Later when we inspect %iv's backedge
7466       // value, we will make sure that the backedge value uses the same
7467       // operation.
7468       //
7469       // Note: the peeled shift operation does not have to be the same
7470       // instruction as the one feeding into the PHI's backedge value.  We only
7471       // really care about it being the same *kind* of shift instruction --
7472       // that's all that is required for our later inferences to hold.
7473       if (MatchPositiveShift(LHS, V, OpC)) {
7474         PostShiftOpCode = OpC;
7475         LHS = V;
7476       }
7477     }
7478 
7479     PNOut = dyn_cast<PHINode>(LHS);
7480     if (!PNOut || PNOut->getParent() != L->getHeader())
7481       return false;
7482 
7483     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7484     Value *OpLHS;
7485 
7486     return
7487         // The backedge value for the PHI node must be a shift by a positive
7488         // amount
7489         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7490 
7491         // of the PHI node itself
7492         OpLHS == PNOut &&
7493 
7494         // and the kind of shift should be match the kind of shift we peeled
7495         // off, if any.
7496         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7497   };
7498 
7499   PHINode *PN;
7500   Instruction::BinaryOps OpCode;
7501   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7502     return getCouldNotCompute();
7503 
7504   const DataLayout &DL = getDataLayout();
7505 
7506   // The key rationale for this optimization is that for some kinds of shift
7507   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7508   // within a finite number of iterations.  If the condition guarding the
7509   // backedge (in the sense that the backedge is taken if the condition is true)
7510   // is false for the value the shift recurrence stabilizes to, then we know
7511   // that the backedge is taken only a finite number of times.
7512 
7513   ConstantInt *StableValue = nullptr;
7514   switch (OpCode) {
7515   default:
7516     llvm_unreachable("Impossible case!");
7517 
7518   case Instruction::AShr: {
7519     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7520     // bitwidth(K) iterations.
7521     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7522     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7523                                        Predecessor->getTerminator(), &DT);
7524     auto *Ty = cast<IntegerType>(RHS->getType());
7525     if (Known.isNonNegative())
7526       StableValue = ConstantInt::get(Ty, 0);
7527     else if (Known.isNegative())
7528       StableValue = ConstantInt::get(Ty, -1, true);
7529     else
7530       return getCouldNotCompute();
7531 
7532     break;
7533   }
7534   case Instruction::LShr:
7535   case Instruction::Shl:
7536     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7537     // stabilize to 0 in at most bitwidth(K) iterations.
7538     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7539     break;
7540   }
7541 
7542   auto *Result =
7543       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7544   assert(Result->getType()->isIntegerTy(1) &&
7545          "Otherwise cannot be an operand to a branch instruction");
7546 
7547   if (Result->isZeroValue()) {
7548     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7549     const SCEV *UpperBound =
7550         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7551     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7552   }
7553 
7554   return getCouldNotCompute();
7555 }
7556 
7557 /// Return true if we can constant fold an instruction of the specified type,
7558 /// assuming that all operands were constants.
7559 static bool CanConstantFold(const Instruction *I) {
7560   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7561       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7562       isa<LoadInst>(I))
7563     return true;
7564 
7565   if (const CallInst *CI = dyn_cast<CallInst>(I))
7566     if (const Function *F = CI->getCalledFunction())
7567       return canConstantFoldCallTo(CI, F);
7568   return false;
7569 }
7570 
7571 /// Determine whether this instruction can constant evolve within this loop
7572 /// assuming its operands can all constant evolve.
7573 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7574   // An instruction outside of the loop can't be derived from a loop PHI.
7575   if (!L->contains(I)) return false;
7576 
7577   if (isa<PHINode>(I)) {
7578     // We don't currently keep track of the control flow needed to evaluate
7579     // PHIs, so we cannot handle PHIs inside of loops.
7580     return L->getHeader() == I->getParent();
7581   }
7582 
7583   // If we won't be able to constant fold this expression even if the operands
7584   // are constants, bail early.
7585   return CanConstantFold(I);
7586 }
7587 
7588 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7589 /// recursing through each instruction operand until reaching a loop header phi.
7590 static PHINode *
7591 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7592                                DenseMap<Instruction *, PHINode *> &PHIMap,
7593                                unsigned Depth) {
7594   if (Depth > MaxConstantEvolvingDepth)
7595     return nullptr;
7596 
7597   // Otherwise, we can evaluate this instruction if all of its operands are
7598   // constant or derived from a PHI node themselves.
7599   PHINode *PHI = nullptr;
7600   for (Value *Op : UseInst->operands()) {
7601     if (isa<Constant>(Op)) continue;
7602 
7603     Instruction *OpInst = dyn_cast<Instruction>(Op);
7604     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7605 
7606     PHINode *P = dyn_cast<PHINode>(OpInst);
7607     if (!P)
7608       // If this operand is already visited, reuse the prior result.
7609       // We may have P != PHI if this is the deepest point at which the
7610       // inconsistent paths meet.
7611       P = PHIMap.lookup(OpInst);
7612     if (!P) {
7613       // Recurse and memoize the results, whether a phi is found or not.
7614       // This recursive call invalidates pointers into PHIMap.
7615       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7616       PHIMap[OpInst] = P;
7617     }
7618     if (!P)
7619       return nullptr;  // Not evolving from PHI
7620     if (PHI && PHI != P)
7621       return nullptr;  // Evolving from multiple different PHIs.
7622     PHI = P;
7623   }
7624   // This is a expression evolving from a constant PHI!
7625   return PHI;
7626 }
7627 
7628 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7629 /// in the loop that V is derived from.  We allow arbitrary operations along the
7630 /// way, but the operands of an operation must either be constants or a value
7631 /// derived from a constant PHI.  If this expression does not fit with these
7632 /// constraints, return null.
7633 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7634   Instruction *I = dyn_cast<Instruction>(V);
7635   if (!I || !canConstantEvolve(I, L)) return nullptr;
7636 
7637   if (PHINode *PN = dyn_cast<PHINode>(I))
7638     return PN;
7639 
7640   // Record non-constant instructions contained by the loop.
7641   DenseMap<Instruction *, PHINode *> PHIMap;
7642   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7643 }
7644 
7645 /// EvaluateExpression - Given an expression that passes the
7646 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7647 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7648 /// reason, return null.
7649 static Constant *EvaluateExpression(Value *V, const Loop *L,
7650                                     DenseMap<Instruction *, Constant *> &Vals,
7651                                     const DataLayout &DL,
7652                                     const TargetLibraryInfo *TLI) {
7653   // Convenient constant check, but redundant for recursive calls.
7654   if (Constant *C = dyn_cast<Constant>(V)) return C;
7655   Instruction *I = dyn_cast<Instruction>(V);
7656   if (!I) return nullptr;
7657 
7658   if (Constant *C = Vals.lookup(I)) return C;
7659 
7660   // An instruction inside the loop depends on a value outside the loop that we
7661   // weren't given a mapping for, or a value such as a call inside the loop.
7662   if (!canConstantEvolve(I, L)) return nullptr;
7663 
7664   // An unmapped PHI can be due to a branch or another loop inside this loop,
7665   // or due to this not being the initial iteration through a loop where we
7666   // couldn't compute the evolution of this particular PHI last time.
7667   if (isa<PHINode>(I)) return nullptr;
7668 
7669   std::vector<Constant*> Operands(I->getNumOperands());
7670 
7671   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7672     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7673     if (!Operand) {
7674       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7675       if (!Operands[i]) return nullptr;
7676       continue;
7677     }
7678     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7679     Vals[Operand] = C;
7680     if (!C) return nullptr;
7681     Operands[i] = C;
7682   }
7683 
7684   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7685     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7686                                            Operands[1], DL, TLI);
7687   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7688     if (!LI->isVolatile())
7689       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7690   }
7691   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7692 }
7693 
7694 
7695 // If every incoming value to PN except the one for BB is a specific Constant,
7696 // return that, else return nullptr.
7697 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7698   Constant *IncomingVal = nullptr;
7699 
7700   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7701     if (PN->getIncomingBlock(i) == BB)
7702       continue;
7703 
7704     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7705     if (!CurrentVal)
7706       return nullptr;
7707 
7708     if (IncomingVal != CurrentVal) {
7709       if (IncomingVal)
7710         return nullptr;
7711       IncomingVal = CurrentVal;
7712     }
7713   }
7714 
7715   return IncomingVal;
7716 }
7717 
7718 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7719 /// in the header of its containing loop, we know the loop executes a
7720 /// constant number of times, and the PHI node is just a recurrence
7721 /// involving constants, fold it.
7722 Constant *
7723 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7724                                                    const APInt &BEs,
7725                                                    const Loop *L) {
7726   auto I = ConstantEvolutionLoopExitValue.find(PN);
7727   if (I != ConstantEvolutionLoopExitValue.end())
7728     return I->second;
7729 
7730   if (BEs.ugt(MaxBruteForceIterations))
7731     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7732 
7733   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7734 
7735   DenseMap<Instruction *, Constant *> CurrentIterVals;
7736   BasicBlock *Header = L->getHeader();
7737   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7738 
7739   BasicBlock *Latch = L->getLoopLatch();
7740   if (!Latch)
7741     return nullptr;
7742 
7743   for (PHINode &PHI : Header->phis()) {
7744     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7745       CurrentIterVals[&PHI] = StartCST;
7746   }
7747   if (!CurrentIterVals.count(PN))
7748     return RetVal = nullptr;
7749 
7750   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7751 
7752   // Execute the loop symbolically to determine the exit value.
7753   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7754          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7755 
7756   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7757   unsigned IterationNum = 0;
7758   const DataLayout &DL = getDataLayout();
7759   for (; ; ++IterationNum) {
7760     if (IterationNum == NumIterations)
7761       return RetVal = CurrentIterVals[PN];  // Got exit value!
7762 
7763     // Compute the value of the PHIs for the next iteration.
7764     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7765     DenseMap<Instruction *, Constant *> NextIterVals;
7766     Constant *NextPHI =
7767         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7768     if (!NextPHI)
7769       return nullptr;        // Couldn't evaluate!
7770     NextIterVals[PN] = NextPHI;
7771 
7772     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7773 
7774     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7775     // cease to be able to evaluate one of them or if they stop evolving,
7776     // because that doesn't necessarily prevent us from computing PN.
7777     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7778     for (const auto &I : CurrentIterVals) {
7779       PHINode *PHI = dyn_cast<PHINode>(I.first);
7780       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7781       PHIsToCompute.emplace_back(PHI, I.second);
7782     }
7783     // We use two distinct loops because EvaluateExpression may invalidate any
7784     // iterators into CurrentIterVals.
7785     for (const auto &I : PHIsToCompute) {
7786       PHINode *PHI = I.first;
7787       Constant *&NextPHI = NextIterVals[PHI];
7788       if (!NextPHI) {   // Not already computed.
7789         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7790         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7791       }
7792       if (NextPHI != I.second)
7793         StoppedEvolving = false;
7794     }
7795 
7796     // If all entries in CurrentIterVals == NextIterVals then we can stop
7797     // iterating, the loop can't continue to change.
7798     if (StoppedEvolving)
7799       return RetVal = CurrentIterVals[PN];
7800 
7801     CurrentIterVals.swap(NextIterVals);
7802   }
7803 }
7804 
7805 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7806                                                           Value *Cond,
7807                                                           bool ExitWhen) {
7808   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7809   if (!PN) return getCouldNotCompute();
7810 
7811   // If the loop is canonicalized, the PHI will have exactly two entries.
7812   // That's the only form we support here.
7813   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7814 
7815   DenseMap<Instruction *, Constant *> CurrentIterVals;
7816   BasicBlock *Header = L->getHeader();
7817   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7818 
7819   BasicBlock *Latch = L->getLoopLatch();
7820   assert(Latch && "Should follow from NumIncomingValues == 2!");
7821 
7822   for (PHINode &PHI : Header->phis()) {
7823     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7824       CurrentIterVals[&PHI] = StartCST;
7825   }
7826   if (!CurrentIterVals.count(PN))
7827     return getCouldNotCompute();
7828 
7829   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7830   // the loop symbolically to determine when the condition gets a value of
7831   // "ExitWhen".
7832   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7833   const DataLayout &DL = getDataLayout();
7834   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7835     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7836         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7837 
7838     // Couldn't symbolically evaluate.
7839     if (!CondVal) return getCouldNotCompute();
7840 
7841     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7842       ++NumBruteForceTripCountsComputed;
7843       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7844     }
7845 
7846     // Update all the PHI nodes for the next iteration.
7847     DenseMap<Instruction *, Constant *> NextIterVals;
7848 
7849     // Create a list of which PHIs we need to compute. We want to do this before
7850     // calling EvaluateExpression on them because that may invalidate iterators
7851     // into CurrentIterVals.
7852     SmallVector<PHINode *, 8> PHIsToCompute;
7853     for (const auto &I : CurrentIterVals) {
7854       PHINode *PHI = dyn_cast<PHINode>(I.first);
7855       if (!PHI || PHI->getParent() != Header) continue;
7856       PHIsToCompute.push_back(PHI);
7857     }
7858     for (PHINode *PHI : PHIsToCompute) {
7859       Constant *&NextPHI = NextIterVals[PHI];
7860       if (NextPHI) continue;    // Already computed!
7861 
7862       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7863       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7864     }
7865     CurrentIterVals.swap(NextIterVals);
7866   }
7867 
7868   // Too many iterations were needed to evaluate.
7869   return getCouldNotCompute();
7870 }
7871 
7872 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7873   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7874       ValuesAtScopes[V];
7875   // Check to see if we've folded this expression at this loop before.
7876   for (auto &LS : Values)
7877     if (LS.first == L)
7878       return LS.second ? LS.second : V;
7879 
7880   Values.emplace_back(L, nullptr);
7881 
7882   // Otherwise compute it.
7883   const SCEV *C = computeSCEVAtScope(V, L);
7884   for (auto &LS : reverse(ValuesAtScopes[V]))
7885     if (LS.first == L) {
7886       LS.second = C;
7887       break;
7888     }
7889   return C;
7890 }
7891 
7892 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7893 /// will return Constants for objects which aren't represented by a
7894 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7895 /// Returns NULL if the SCEV isn't representable as a Constant.
7896 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7897   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7898     case scCouldNotCompute:
7899     case scAddRecExpr:
7900       break;
7901     case scConstant:
7902       return cast<SCEVConstant>(V)->getValue();
7903     case scUnknown:
7904       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7905     case scSignExtend: {
7906       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7907       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7908         return ConstantExpr::getSExt(CastOp, SS->getType());
7909       break;
7910     }
7911     case scZeroExtend: {
7912       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7913       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7914         return ConstantExpr::getZExt(CastOp, SZ->getType());
7915       break;
7916     }
7917     case scTruncate: {
7918       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7919       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7920         return ConstantExpr::getTrunc(CastOp, ST->getType());
7921       break;
7922     }
7923     case scAddExpr: {
7924       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7925       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7926         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7927           unsigned AS = PTy->getAddressSpace();
7928           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7929           C = ConstantExpr::getBitCast(C, DestPtrTy);
7930         }
7931         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7932           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7933           if (!C2) return nullptr;
7934 
7935           // First pointer!
7936           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7937             unsigned AS = C2->getType()->getPointerAddressSpace();
7938             std::swap(C, C2);
7939             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7940             // The offsets have been converted to bytes.  We can add bytes to an
7941             // i8* by GEP with the byte count in the first index.
7942             C = ConstantExpr::getBitCast(C, DestPtrTy);
7943           }
7944 
7945           // Don't bother trying to sum two pointers. We probably can't
7946           // statically compute a load that results from it anyway.
7947           if (C2->getType()->isPointerTy())
7948             return nullptr;
7949 
7950           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7951             if (PTy->getElementType()->isStructTy())
7952               C2 = ConstantExpr::getIntegerCast(
7953                   C2, Type::getInt32Ty(C->getContext()), true);
7954             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7955           } else
7956             C = ConstantExpr::getAdd(C, C2);
7957         }
7958         return C;
7959       }
7960       break;
7961     }
7962     case scMulExpr: {
7963       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7964       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7965         // Don't bother with pointers at all.
7966         if (C->getType()->isPointerTy()) return nullptr;
7967         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7968           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7969           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7970           C = ConstantExpr::getMul(C, C2);
7971         }
7972         return C;
7973       }
7974       break;
7975     }
7976     case scUDivExpr: {
7977       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7978       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7979         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7980           if (LHS->getType() == RHS->getType())
7981             return ConstantExpr::getUDiv(LHS, RHS);
7982       break;
7983     }
7984     case scSMaxExpr:
7985     case scUMaxExpr:
7986       break; // TODO: smax, umax.
7987   }
7988   return nullptr;
7989 }
7990 
7991 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7992   if (isa<SCEVConstant>(V)) return V;
7993 
7994   // If this instruction is evolved from a constant-evolving PHI, compute the
7995   // exit value from the loop without using SCEVs.
7996   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7997     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7998       const Loop *LI = this->LI[I->getParent()];
7999       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
8000         if (PHINode *PN = dyn_cast<PHINode>(I))
8001           if (PN->getParent() == LI->getHeader()) {
8002             // Okay, there is no closed form solution for the PHI node.  Check
8003             // to see if the loop that contains it has a known backedge-taken
8004             // count.  If so, we may be able to force computation of the exit
8005             // value.
8006             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8007             if (const SCEVConstant *BTCC =
8008                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8009 
8010               // This trivial case can show up in some degenerate cases where
8011               // the incoming IR has not yet been fully simplified.
8012               if (BTCC->getValue()->isZero()) {
8013                 Value *InitValue = nullptr;
8014                 bool MultipleInitValues = false;
8015                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8016                   if (!LI->contains(PN->getIncomingBlock(i))) {
8017                     if (!InitValue)
8018                       InitValue = PN->getIncomingValue(i);
8019                     else if (InitValue != PN->getIncomingValue(i)) {
8020                       MultipleInitValues = true;
8021                       break;
8022                     }
8023                   }
8024                   if (!MultipleInitValues && InitValue)
8025                     return getSCEV(InitValue);
8026                 }
8027               }
8028               // Okay, we know how many times the containing loop executes.  If
8029               // this is a constant evolving PHI node, get the final value at
8030               // the specified iteration number.
8031               Constant *RV =
8032                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8033               if (RV) return getSCEV(RV);
8034             }
8035           }
8036 
8037       // Okay, this is an expression that we cannot symbolically evaluate
8038       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8039       // the arguments into constants, and if so, try to constant propagate the
8040       // result.  This is particularly useful for computing loop exit values.
8041       if (CanConstantFold(I)) {
8042         SmallVector<Constant *, 4> Operands;
8043         bool MadeImprovement = false;
8044         for (Value *Op : I->operands()) {
8045           if (Constant *C = dyn_cast<Constant>(Op)) {
8046             Operands.push_back(C);
8047             continue;
8048           }
8049 
8050           // If any of the operands is non-constant and if they are
8051           // non-integer and non-pointer, don't even try to analyze them
8052           // with scev techniques.
8053           if (!isSCEVable(Op->getType()))
8054             return V;
8055 
8056           const SCEV *OrigV = getSCEV(Op);
8057           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8058           MadeImprovement |= OrigV != OpV;
8059 
8060           Constant *C = BuildConstantFromSCEV(OpV);
8061           if (!C) return V;
8062           if (C->getType() != Op->getType())
8063             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8064                                                               Op->getType(),
8065                                                               false),
8066                                       C, Op->getType());
8067           Operands.push_back(C);
8068         }
8069 
8070         // Check to see if getSCEVAtScope actually made an improvement.
8071         if (MadeImprovement) {
8072           Constant *C = nullptr;
8073           const DataLayout &DL = getDataLayout();
8074           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8075             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8076                                                 Operands[1], DL, &TLI);
8077           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8078             if (!LI->isVolatile())
8079               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8080           } else
8081             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8082           if (!C) return V;
8083           return getSCEV(C);
8084         }
8085       }
8086     }
8087 
8088     // This is some other type of SCEVUnknown, just return it.
8089     return V;
8090   }
8091 
8092   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8093     // Avoid performing the look-up in the common case where the specified
8094     // expression has no loop-variant portions.
8095     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8096       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8097       if (OpAtScope != Comm->getOperand(i)) {
8098         // Okay, at least one of these operands is loop variant but might be
8099         // foldable.  Build a new instance of the folded commutative expression.
8100         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8101                                             Comm->op_begin()+i);
8102         NewOps.push_back(OpAtScope);
8103 
8104         for (++i; i != e; ++i) {
8105           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8106           NewOps.push_back(OpAtScope);
8107         }
8108         if (isa<SCEVAddExpr>(Comm))
8109           return getAddExpr(NewOps);
8110         if (isa<SCEVMulExpr>(Comm))
8111           return getMulExpr(NewOps);
8112         if (isa<SCEVSMaxExpr>(Comm))
8113           return getSMaxExpr(NewOps);
8114         if (isa<SCEVUMaxExpr>(Comm))
8115           return getUMaxExpr(NewOps);
8116         llvm_unreachable("Unknown commutative SCEV type!");
8117       }
8118     }
8119     // If we got here, all operands are loop invariant.
8120     return Comm;
8121   }
8122 
8123   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8124     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8125     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8126     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8127       return Div;   // must be loop invariant
8128     return getUDivExpr(LHS, RHS);
8129   }
8130 
8131   // If this is a loop recurrence for a loop that does not contain L, then we
8132   // are dealing with the final value computed by the loop.
8133   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8134     // First, attempt to evaluate each operand.
8135     // Avoid performing the look-up in the common case where the specified
8136     // expression has no loop-variant portions.
8137     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8138       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8139       if (OpAtScope == AddRec->getOperand(i))
8140         continue;
8141 
8142       // Okay, at least one of these operands is loop variant but might be
8143       // foldable.  Build a new instance of the folded commutative expression.
8144       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8145                                           AddRec->op_begin()+i);
8146       NewOps.push_back(OpAtScope);
8147       for (++i; i != e; ++i)
8148         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8149 
8150       const SCEV *FoldedRec =
8151         getAddRecExpr(NewOps, AddRec->getLoop(),
8152                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8153       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8154       // The addrec may be folded to a nonrecurrence, for example, if the
8155       // induction variable is multiplied by zero after constant folding. Go
8156       // ahead and return the folded value.
8157       if (!AddRec)
8158         return FoldedRec;
8159       break;
8160     }
8161 
8162     // If the scope is outside the addrec's loop, evaluate it by using the
8163     // loop exit value of the addrec.
8164     if (!AddRec->getLoop()->contains(L)) {
8165       // To evaluate this recurrence, we need to know how many times the AddRec
8166       // loop iterates.  Compute this now.
8167       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8168       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8169 
8170       // Then, evaluate the AddRec.
8171       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8172     }
8173 
8174     return AddRec;
8175   }
8176 
8177   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8178     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8179     if (Op == Cast->getOperand())
8180       return Cast;  // must be loop invariant
8181     return getZeroExtendExpr(Op, Cast->getType());
8182   }
8183 
8184   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8185     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8186     if (Op == Cast->getOperand())
8187       return Cast;  // must be loop invariant
8188     return getSignExtendExpr(Op, Cast->getType());
8189   }
8190 
8191   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8192     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8193     if (Op == Cast->getOperand())
8194       return Cast;  // must be loop invariant
8195     return getTruncateExpr(Op, Cast->getType());
8196   }
8197 
8198   llvm_unreachable("Unknown SCEV type!");
8199 }
8200 
8201 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8202   return getSCEVAtScope(getSCEV(V), L);
8203 }
8204 
8205 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8206   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8207     return stripInjectiveFunctions(ZExt->getOperand());
8208   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8209     return stripInjectiveFunctions(SExt->getOperand());
8210   return S;
8211 }
8212 
8213 /// Finds the minimum unsigned root of the following equation:
8214 ///
8215 ///     A * X = B (mod N)
8216 ///
8217 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8218 /// A and B isn't important.
8219 ///
8220 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8221 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8222                                                ScalarEvolution &SE) {
8223   uint32_t BW = A.getBitWidth();
8224   assert(BW == SE.getTypeSizeInBits(B->getType()));
8225   assert(A != 0 && "A must be non-zero.");
8226 
8227   // 1. D = gcd(A, N)
8228   //
8229   // The gcd of A and N may have only one prime factor: 2. The number of
8230   // trailing zeros in A is its multiplicity
8231   uint32_t Mult2 = A.countTrailingZeros();
8232   // D = 2^Mult2
8233 
8234   // 2. Check if B is divisible by D.
8235   //
8236   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8237   // is not less than multiplicity of this prime factor for D.
8238   if (SE.GetMinTrailingZeros(B) < Mult2)
8239     return SE.getCouldNotCompute();
8240 
8241   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8242   // modulo (N / D).
8243   //
8244   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8245   // (N / D) in general. The inverse itself always fits into BW bits, though,
8246   // so we immediately truncate it.
8247   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8248   APInt Mod(BW + 1, 0);
8249   Mod.setBit(BW - Mult2);  // Mod = N / D
8250   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8251 
8252   // 4. Compute the minimum unsigned root of the equation:
8253   // I * (B / D) mod (N / D)
8254   // To simplify the computation, we factor out the divide by D:
8255   // (I * B mod N) / D
8256   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8257   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8258 }
8259 
8260 /// Find the roots of the quadratic equation for the given quadratic chrec
8261 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8262 /// two SCEVCouldNotCompute objects.
8263 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8264 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8265   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8266   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8267   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8268   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8269 
8270   // We currently can only solve this if the coefficients are constants.
8271   if (!LC || !MC || !NC)
8272     return None;
8273 
8274   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8275   const APInt &L = LC->getAPInt();
8276   const APInt &M = MC->getAPInt();
8277   const APInt &N = NC->getAPInt();
8278   APInt Two(BitWidth, 2);
8279 
8280   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8281 
8282   // The A coefficient is N/2
8283   APInt A = N.sdiv(Two);
8284 
8285   // The B coefficient is M-N/2
8286   APInt B = M;
8287   B -= A; // A is the same as N/2.
8288 
8289   // The C coefficient is L.
8290   const APInt& C = L;
8291 
8292   // Compute the B^2-4ac term.
8293   APInt SqrtTerm = B;
8294   SqrtTerm *= B;
8295   SqrtTerm -= 4 * (A * C);
8296 
8297   if (SqrtTerm.isNegative()) {
8298     // The loop is provably infinite.
8299     return None;
8300   }
8301 
8302   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8303   // integer value or else APInt::sqrt() will assert.
8304   APInt SqrtVal = SqrtTerm.sqrt();
8305 
8306   // Compute the two solutions for the quadratic formula.
8307   // The divisions must be performed as signed divisions.
8308   APInt NegB = -std::move(B);
8309   APInt TwoA = std::move(A);
8310   TwoA <<= 1;
8311   if (TwoA.isNullValue())
8312     return None;
8313 
8314   LLVMContext &Context = SE.getContext();
8315 
8316   ConstantInt *Solution1 =
8317     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8318   ConstantInt *Solution2 =
8319     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8320 
8321   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8322                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8323 }
8324 
8325 ScalarEvolution::ExitLimit
8326 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8327                               bool AllowPredicates) {
8328 
8329   // This is only used for loops with a "x != y" exit test. The exit condition
8330   // is now expressed as a single expression, V = x-y. So the exit test is
8331   // effectively V != 0.  We know and take advantage of the fact that this
8332   // expression only being used in a comparison by zero context.
8333 
8334   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8335   // If the value is a constant
8336   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8337     // If the value is already zero, the branch will execute zero times.
8338     if (C->getValue()->isZero()) return C;
8339     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8340   }
8341 
8342   const SCEVAddRecExpr *AddRec =
8343       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8344 
8345   if (!AddRec && AllowPredicates)
8346     // Try to make this an AddRec using runtime tests, in the first X
8347     // iterations of this loop, where X is the SCEV expression found by the
8348     // algorithm below.
8349     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8350 
8351   if (!AddRec || AddRec->getLoop() != L)
8352     return getCouldNotCompute();
8353 
8354   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8355   // the quadratic equation to solve it.
8356   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8357     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8358       const SCEVConstant *R1 = Roots->first;
8359       const SCEVConstant *R2 = Roots->second;
8360       // Pick the smallest positive root value.
8361       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8362               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8363         if (!CB->getZExtValue())
8364           std::swap(R1, R2); // R1 is the minimum root now.
8365 
8366         // We can only use this value if the chrec ends up with an exact zero
8367         // value at this index.  When solving for "X*X != 5", for example, we
8368         // should not accept a root of 2.
8369         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8370         if (Val->isZero())
8371           // We found a quadratic root!
8372           return ExitLimit(R1, R1, false, Predicates);
8373       }
8374     }
8375     return getCouldNotCompute();
8376   }
8377 
8378   // Otherwise we can only handle this if it is affine.
8379   if (!AddRec->isAffine())
8380     return getCouldNotCompute();
8381 
8382   // If this is an affine expression, the execution count of this branch is
8383   // the minimum unsigned root of the following equation:
8384   //
8385   //     Start + Step*N = 0 (mod 2^BW)
8386   //
8387   // equivalent to:
8388   //
8389   //             Step*N = -Start (mod 2^BW)
8390   //
8391   // where BW is the common bit width of Start and Step.
8392 
8393   // Get the initial value for the loop.
8394   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8395   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8396 
8397   // For now we handle only constant steps.
8398   //
8399   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8400   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8401   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8402   // We have not yet seen any such cases.
8403   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8404   if (!StepC || StepC->getValue()->isZero())
8405     return getCouldNotCompute();
8406 
8407   // For positive steps (counting up until unsigned overflow):
8408   //   N = -Start/Step (as unsigned)
8409   // For negative steps (counting down to zero):
8410   //   N = Start/-Step
8411   // First compute the unsigned distance from zero in the direction of Step.
8412   bool CountDown = StepC->getAPInt().isNegative();
8413   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8414 
8415   // Handle unitary steps, which cannot wraparound.
8416   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8417   //   N = Distance (as unsigned)
8418   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8419     APInt MaxBECount = getUnsignedRangeMax(Distance);
8420 
8421     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8422     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8423     // case, and see if we can improve the bound.
8424     //
8425     // Explicitly handling this here is necessary because getUnsignedRange
8426     // isn't context-sensitive; it doesn't know that we only care about the
8427     // range inside the loop.
8428     const SCEV *Zero = getZero(Distance->getType());
8429     const SCEV *One = getOne(Distance->getType());
8430     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8431     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8432       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8433       // as "unsigned_max(Distance + 1) - 1".
8434       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8435       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8436     }
8437     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8438   }
8439 
8440   // If the condition controls loop exit (the loop exits only if the expression
8441   // is true) and the addition is no-wrap we can use unsigned divide to
8442   // compute the backedge count.  In this case, the step may not divide the
8443   // distance, but we don't care because if the condition is "missed" the loop
8444   // will have undefined behavior due to wrapping.
8445   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8446       loopHasNoAbnormalExits(AddRec->getLoop())) {
8447     const SCEV *Exact =
8448         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8449     const SCEV *Max =
8450         Exact == getCouldNotCompute()
8451             ? Exact
8452             : getConstant(getUnsignedRangeMax(Exact));
8453     return ExitLimit(Exact, Max, false, Predicates);
8454   }
8455 
8456   // Solve the general equation.
8457   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8458                                                getNegativeSCEV(Start), *this);
8459   const SCEV *M = E == getCouldNotCompute()
8460                       ? E
8461                       : getConstant(getUnsignedRangeMax(E));
8462   return ExitLimit(E, M, false, Predicates);
8463 }
8464 
8465 ScalarEvolution::ExitLimit
8466 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8467   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8468   // handle them yet except for the trivial case.  This could be expanded in the
8469   // future as needed.
8470 
8471   // If the value is a constant, check to see if it is known to be non-zero
8472   // already.  If so, the backedge will execute zero times.
8473   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8474     if (!C->getValue()->isZero())
8475       return getZero(C->getType());
8476     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8477   }
8478 
8479   // We could implement others, but I really doubt anyone writes loops like
8480   // this, and if they did, they would already be constant folded.
8481   return getCouldNotCompute();
8482 }
8483 
8484 std::pair<BasicBlock *, BasicBlock *>
8485 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8486   // If the block has a unique predecessor, then there is no path from the
8487   // predecessor to the block that does not go through the direct edge
8488   // from the predecessor to the block.
8489   if (BasicBlock *Pred = BB->getSinglePredecessor())
8490     return {Pred, BB};
8491 
8492   // A loop's header is defined to be a block that dominates the loop.
8493   // If the header has a unique predecessor outside the loop, it must be
8494   // a block that has exactly one successor that can reach the loop.
8495   if (Loop *L = LI.getLoopFor(BB))
8496     return {L->getLoopPredecessor(), L->getHeader()};
8497 
8498   return {nullptr, nullptr};
8499 }
8500 
8501 /// SCEV structural equivalence is usually sufficient for testing whether two
8502 /// expressions are equal, however for the purposes of looking for a condition
8503 /// guarding a loop, it can be useful to be a little more general, since a
8504 /// front-end may have replicated the controlling expression.
8505 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8506   // Quick check to see if they are the same SCEV.
8507   if (A == B) return true;
8508 
8509   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8510     // Not all instructions that are "identical" compute the same value.  For
8511     // instance, two distinct alloca instructions allocating the same type are
8512     // identical and do not read memory; but compute distinct values.
8513     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8514   };
8515 
8516   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8517   // two different instructions with the same value. Check for this case.
8518   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8519     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8520       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8521         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8522           if (ComputesEqualValues(AI, BI))
8523             return true;
8524 
8525   // Otherwise assume they may have a different value.
8526   return false;
8527 }
8528 
8529 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8530                                            const SCEV *&LHS, const SCEV *&RHS,
8531                                            unsigned Depth) {
8532   bool Changed = false;
8533 
8534   // If we hit the max recursion limit bail out.
8535   if (Depth >= 3)
8536     return false;
8537 
8538   // Canonicalize a constant to the right side.
8539   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8540     // Check for both operands constant.
8541     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8542       if (ConstantExpr::getICmp(Pred,
8543                                 LHSC->getValue(),
8544                                 RHSC->getValue())->isNullValue())
8545         goto trivially_false;
8546       else
8547         goto trivially_true;
8548     }
8549     // Otherwise swap the operands to put the constant on the right.
8550     std::swap(LHS, RHS);
8551     Pred = ICmpInst::getSwappedPredicate(Pred);
8552     Changed = true;
8553   }
8554 
8555   // If we're comparing an addrec with a value which is loop-invariant in the
8556   // addrec's loop, put the addrec on the left. Also make a dominance check,
8557   // as both operands could be addrecs loop-invariant in each other's loop.
8558   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8559     const Loop *L = AR->getLoop();
8560     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8561       std::swap(LHS, RHS);
8562       Pred = ICmpInst::getSwappedPredicate(Pred);
8563       Changed = true;
8564     }
8565   }
8566 
8567   // If there's a constant operand, canonicalize comparisons with boundary
8568   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8569   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8570     const APInt &RA = RC->getAPInt();
8571 
8572     bool SimplifiedByConstantRange = false;
8573 
8574     if (!ICmpInst::isEquality(Pred)) {
8575       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8576       if (ExactCR.isFullSet())
8577         goto trivially_true;
8578       else if (ExactCR.isEmptySet())
8579         goto trivially_false;
8580 
8581       APInt NewRHS;
8582       CmpInst::Predicate NewPred;
8583       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8584           ICmpInst::isEquality(NewPred)) {
8585         // We were able to convert an inequality to an equality.
8586         Pred = NewPred;
8587         RHS = getConstant(NewRHS);
8588         Changed = SimplifiedByConstantRange = true;
8589       }
8590     }
8591 
8592     if (!SimplifiedByConstantRange) {
8593       switch (Pred) {
8594       default:
8595         break;
8596       case ICmpInst::ICMP_EQ:
8597       case ICmpInst::ICMP_NE:
8598         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8599         if (!RA)
8600           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8601             if (const SCEVMulExpr *ME =
8602                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8603               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8604                   ME->getOperand(0)->isAllOnesValue()) {
8605                 RHS = AE->getOperand(1);
8606                 LHS = ME->getOperand(1);
8607                 Changed = true;
8608               }
8609         break;
8610 
8611 
8612         // The "Should have been caught earlier!" messages refer to the fact
8613         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8614         // should have fired on the corresponding cases, and canonicalized the
8615         // check to trivially_true or trivially_false.
8616 
8617       case ICmpInst::ICMP_UGE:
8618         assert(!RA.isMinValue() && "Should have been caught earlier!");
8619         Pred = ICmpInst::ICMP_UGT;
8620         RHS = getConstant(RA - 1);
8621         Changed = true;
8622         break;
8623       case ICmpInst::ICMP_ULE:
8624         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8625         Pred = ICmpInst::ICMP_ULT;
8626         RHS = getConstant(RA + 1);
8627         Changed = true;
8628         break;
8629       case ICmpInst::ICMP_SGE:
8630         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8631         Pred = ICmpInst::ICMP_SGT;
8632         RHS = getConstant(RA - 1);
8633         Changed = true;
8634         break;
8635       case ICmpInst::ICMP_SLE:
8636         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8637         Pred = ICmpInst::ICMP_SLT;
8638         RHS = getConstant(RA + 1);
8639         Changed = true;
8640         break;
8641       }
8642     }
8643   }
8644 
8645   // Check for obvious equality.
8646   if (HasSameValue(LHS, RHS)) {
8647     if (ICmpInst::isTrueWhenEqual(Pred))
8648       goto trivially_true;
8649     if (ICmpInst::isFalseWhenEqual(Pred))
8650       goto trivially_false;
8651   }
8652 
8653   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8654   // adding or subtracting 1 from one of the operands.
8655   switch (Pred) {
8656   case ICmpInst::ICMP_SLE:
8657     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8658       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8659                        SCEV::FlagNSW);
8660       Pred = ICmpInst::ICMP_SLT;
8661       Changed = true;
8662     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8663       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8664                        SCEV::FlagNSW);
8665       Pred = ICmpInst::ICMP_SLT;
8666       Changed = true;
8667     }
8668     break;
8669   case ICmpInst::ICMP_SGE:
8670     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8671       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8672                        SCEV::FlagNSW);
8673       Pred = ICmpInst::ICMP_SGT;
8674       Changed = true;
8675     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8676       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8677                        SCEV::FlagNSW);
8678       Pred = ICmpInst::ICMP_SGT;
8679       Changed = true;
8680     }
8681     break;
8682   case ICmpInst::ICMP_ULE:
8683     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8684       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8685                        SCEV::FlagNUW);
8686       Pred = ICmpInst::ICMP_ULT;
8687       Changed = true;
8688     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8689       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8690       Pred = ICmpInst::ICMP_ULT;
8691       Changed = true;
8692     }
8693     break;
8694   case ICmpInst::ICMP_UGE:
8695     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8696       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8697       Pred = ICmpInst::ICMP_UGT;
8698       Changed = true;
8699     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8700       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8701                        SCEV::FlagNUW);
8702       Pred = ICmpInst::ICMP_UGT;
8703       Changed = true;
8704     }
8705     break;
8706   default:
8707     break;
8708   }
8709 
8710   // TODO: More simplifications are possible here.
8711 
8712   // Recursively simplify until we either hit a recursion limit or nothing
8713   // changes.
8714   if (Changed)
8715     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8716 
8717   return Changed;
8718 
8719 trivially_true:
8720   // Return 0 == 0.
8721   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8722   Pred = ICmpInst::ICMP_EQ;
8723   return true;
8724 
8725 trivially_false:
8726   // Return 0 != 0.
8727   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8728   Pred = ICmpInst::ICMP_NE;
8729   return true;
8730 }
8731 
8732 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8733   return getSignedRangeMax(S).isNegative();
8734 }
8735 
8736 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8737   return getSignedRangeMin(S).isStrictlyPositive();
8738 }
8739 
8740 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8741   return !getSignedRangeMin(S).isNegative();
8742 }
8743 
8744 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8745   return !getSignedRangeMax(S).isStrictlyPositive();
8746 }
8747 
8748 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8749   return isKnownNegative(S) || isKnownPositive(S);
8750 }
8751 
8752 std::pair<const SCEV *, const SCEV *>
8753 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
8754   // Compute SCEV on entry of loop L.
8755   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
8756   if (Start == getCouldNotCompute())
8757     return { Start, Start };
8758   // Compute post increment SCEV for loop L.
8759   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
8760   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
8761   return { Start, PostInc };
8762 }
8763 
8764 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
8765                                           const SCEV *LHS, const SCEV *RHS) {
8766   // First collect all loops.
8767   SmallPtrSet<const Loop *, 8> LoopsUsed;
8768   getUsedLoops(LHS, LoopsUsed);
8769   getUsedLoops(RHS, LoopsUsed);
8770 
8771   if (LoopsUsed.empty())
8772     return false;
8773 
8774   // Domination relationship must be a linear order on collected loops.
8775 #ifndef NDEBUG
8776   for (auto *L1 : LoopsUsed)
8777     for (auto *L2 : LoopsUsed)
8778       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
8779               DT.dominates(L2->getHeader(), L1->getHeader())) &&
8780              "Domination relationship is not a linear order");
8781 #endif
8782 
8783   const Loop *MDL =
8784       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
8785                         [&](const Loop *L1, const Loop *L2) {
8786          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
8787        });
8788 
8789   // Get init and post increment value for LHS.
8790   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
8791   // if LHS contains unknown non-invariant SCEV then bail out.
8792   if (SplitLHS.first == getCouldNotCompute())
8793     return false;
8794   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
8795   // Get init and post increment value for RHS.
8796   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
8797   // if RHS contains unknown non-invariant SCEV then bail out.
8798   if (SplitRHS.first == getCouldNotCompute())
8799     return false;
8800   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
8801   // It is possible that init SCEV contains an invariant load but it does
8802   // not dominate MDL and is not available at MDL loop entry, so we should
8803   // check it here.
8804   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
8805       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
8806     return false;
8807 
8808   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
8809          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
8810                                      SplitRHS.second);
8811 }
8812 
8813 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8814                                        const SCEV *LHS, const SCEV *RHS) {
8815   // Canonicalize the inputs first.
8816   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8817 
8818   if (isKnownViaInduction(Pred, LHS, RHS))
8819     return true;
8820 
8821   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8822     return true;
8823 
8824   // Otherwise see what can be done with some simple reasoning.
8825   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
8826 }
8827 
8828 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
8829                                               const SCEVAddRecExpr *LHS,
8830                                               const SCEV *RHS) {
8831   const Loop *L = LHS->getLoop();
8832   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
8833          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
8834 }
8835 
8836 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8837                                            ICmpInst::Predicate Pred,
8838                                            bool &Increasing) {
8839   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8840 
8841 #ifndef NDEBUG
8842   // Verify an invariant: inverting the predicate should turn a monotonically
8843   // increasing change to a monotonically decreasing one, and vice versa.
8844   bool IncreasingSwapped;
8845   bool ResultSwapped = isMonotonicPredicateImpl(
8846       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8847 
8848   assert(Result == ResultSwapped && "should be able to analyze both!");
8849   if (ResultSwapped)
8850     assert(Increasing == !IncreasingSwapped &&
8851            "monotonicity should flip as we flip the predicate");
8852 #endif
8853 
8854   return Result;
8855 }
8856 
8857 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8858                                                ICmpInst::Predicate Pred,
8859                                                bool &Increasing) {
8860 
8861   // A zero step value for LHS means the induction variable is essentially a
8862   // loop invariant value. We don't really depend on the predicate actually
8863   // flipping from false to true (for increasing predicates, and the other way
8864   // around for decreasing predicates), all we care about is that *if* the
8865   // predicate changes then it only changes from false to true.
8866   //
8867   // A zero step value in itself is not very useful, but there may be places
8868   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8869   // as general as possible.
8870 
8871   switch (Pred) {
8872   default:
8873     return false; // Conservative answer
8874 
8875   case ICmpInst::ICMP_UGT:
8876   case ICmpInst::ICMP_UGE:
8877   case ICmpInst::ICMP_ULT:
8878   case ICmpInst::ICMP_ULE:
8879     if (!LHS->hasNoUnsignedWrap())
8880       return false;
8881 
8882     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8883     return true;
8884 
8885   case ICmpInst::ICMP_SGT:
8886   case ICmpInst::ICMP_SGE:
8887   case ICmpInst::ICMP_SLT:
8888   case ICmpInst::ICMP_SLE: {
8889     if (!LHS->hasNoSignedWrap())
8890       return false;
8891 
8892     const SCEV *Step = LHS->getStepRecurrence(*this);
8893 
8894     if (isKnownNonNegative(Step)) {
8895       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8896       return true;
8897     }
8898 
8899     if (isKnownNonPositive(Step)) {
8900       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8901       return true;
8902     }
8903 
8904     return false;
8905   }
8906 
8907   }
8908 
8909   llvm_unreachable("switch has default clause!");
8910 }
8911 
8912 bool ScalarEvolution::isLoopInvariantPredicate(
8913     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8914     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8915     const SCEV *&InvariantRHS) {
8916 
8917   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8918   if (!isLoopInvariant(RHS, L)) {
8919     if (!isLoopInvariant(LHS, L))
8920       return false;
8921 
8922     std::swap(LHS, RHS);
8923     Pred = ICmpInst::getSwappedPredicate(Pred);
8924   }
8925 
8926   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8927   if (!ArLHS || ArLHS->getLoop() != L)
8928     return false;
8929 
8930   bool Increasing;
8931   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8932     return false;
8933 
8934   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8935   // true as the loop iterates, and the backedge is control dependent on
8936   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8937   //
8938   //   * if the predicate was false in the first iteration then the predicate
8939   //     is never evaluated again, since the loop exits without taking the
8940   //     backedge.
8941   //   * if the predicate was true in the first iteration then it will
8942   //     continue to be true for all future iterations since it is
8943   //     monotonically increasing.
8944   //
8945   // For both the above possibilities, we can replace the loop varying
8946   // predicate with its value on the first iteration of the loop (which is
8947   // loop invariant).
8948   //
8949   // A similar reasoning applies for a monotonically decreasing predicate, by
8950   // replacing true with false and false with true in the above two bullets.
8951 
8952   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8953 
8954   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8955     return false;
8956 
8957   InvariantPred = Pred;
8958   InvariantLHS = ArLHS->getStart();
8959   InvariantRHS = RHS;
8960   return true;
8961 }
8962 
8963 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8964     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8965   if (HasSameValue(LHS, RHS))
8966     return ICmpInst::isTrueWhenEqual(Pred);
8967 
8968   // This code is split out from isKnownPredicate because it is called from
8969   // within isLoopEntryGuardedByCond.
8970 
8971   auto CheckRanges =
8972       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8973     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8974         .contains(RangeLHS);
8975   };
8976 
8977   // The check at the top of the function catches the case where the values are
8978   // known to be equal.
8979   if (Pred == CmpInst::ICMP_EQ)
8980     return false;
8981 
8982   if (Pred == CmpInst::ICMP_NE)
8983     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8984            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8985            isKnownNonZero(getMinusSCEV(LHS, RHS));
8986 
8987   if (CmpInst::isSigned(Pred))
8988     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8989 
8990   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8991 }
8992 
8993 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8994                                                     const SCEV *LHS,
8995                                                     const SCEV *RHS) {
8996   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8997   // Return Y via OutY.
8998   auto MatchBinaryAddToConst =
8999       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9000              SCEV::NoWrapFlags ExpectedFlags) {
9001     const SCEV *NonConstOp, *ConstOp;
9002     SCEV::NoWrapFlags FlagsPresent;
9003 
9004     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9005         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9006       return false;
9007 
9008     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9009     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9010   };
9011 
9012   APInt C;
9013 
9014   switch (Pred) {
9015   default:
9016     break;
9017 
9018   case ICmpInst::ICMP_SGE:
9019     std::swap(LHS, RHS);
9020     LLVM_FALLTHROUGH;
9021   case ICmpInst::ICMP_SLE:
9022     // X s<= (X + C)<nsw> if C >= 0
9023     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9024       return true;
9025 
9026     // (X + C)<nsw> s<= X if C <= 0
9027     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9028         !C.isStrictlyPositive())
9029       return true;
9030     break;
9031 
9032   case ICmpInst::ICMP_SGT:
9033     std::swap(LHS, RHS);
9034     LLVM_FALLTHROUGH;
9035   case ICmpInst::ICMP_SLT:
9036     // X s< (X + C)<nsw> if C > 0
9037     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9038         C.isStrictlyPositive())
9039       return true;
9040 
9041     // (X + C)<nsw> s< X if C < 0
9042     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9043       return true;
9044     break;
9045   }
9046 
9047   return false;
9048 }
9049 
9050 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9051                                                    const SCEV *LHS,
9052                                                    const SCEV *RHS) {
9053   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9054     return false;
9055 
9056   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9057   // the stack can result in exponential time complexity.
9058   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9059 
9060   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9061   //
9062   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9063   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9064   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9065   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9066   // use isKnownPredicate later if needed.
9067   return isKnownNonNegative(RHS) &&
9068          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9069          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9070 }
9071 
9072 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9073                                         ICmpInst::Predicate Pred,
9074                                         const SCEV *LHS, const SCEV *RHS) {
9075   // No need to even try if we know the module has no guards.
9076   if (!HasGuards)
9077     return false;
9078 
9079   return any_of(*BB, [&](Instruction &I) {
9080     using namespace llvm::PatternMatch;
9081 
9082     Value *Condition;
9083     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9084                          m_Value(Condition))) &&
9085            isImpliedCond(Pred, LHS, RHS, Condition, false);
9086   });
9087 }
9088 
9089 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9090 /// protected by a conditional between LHS and RHS.  This is used to
9091 /// to eliminate casts.
9092 bool
9093 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9094                                              ICmpInst::Predicate Pred,
9095                                              const SCEV *LHS, const SCEV *RHS) {
9096   // Interpret a null as meaning no loop, where there is obviously no guard
9097   // (interprocedural conditions notwithstanding).
9098   if (!L) return true;
9099 
9100   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9101     return true;
9102 
9103   BasicBlock *Latch = L->getLoopLatch();
9104   if (!Latch)
9105     return false;
9106 
9107   BranchInst *LoopContinuePredicate =
9108     dyn_cast<BranchInst>(Latch->getTerminator());
9109   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9110       isImpliedCond(Pred, LHS, RHS,
9111                     LoopContinuePredicate->getCondition(),
9112                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9113     return true;
9114 
9115   // We don't want more than one activation of the following loops on the stack
9116   // -- that can lead to O(n!) time complexity.
9117   if (WalkingBEDominatingConds)
9118     return false;
9119 
9120   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9121 
9122   // See if we can exploit a trip count to prove the predicate.
9123   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9124   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9125   if (LatchBECount != getCouldNotCompute()) {
9126     // We know that Latch branches back to the loop header exactly
9127     // LatchBECount times.  This means the backdege condition at Latch is
9128     // equivalent to  "{0,+,1} u< LatchBECount".
9129     Type *Ty = LatchBECount->getType();
9130     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9131     const SCEV *LoopCounter =
9132       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9133     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9134                       LatchBECount))
9135       return true;
9136   }
9137 
9138   // Check conditions due to any @llvm.assume intrinsics.
9139   for (auto &AssumeVH : AC.assumptions()) {
9140     if (!AssumeVH)
9141       continue;
9142     auto *CI = cast<CallInst>(AssumeVH);
9143     if (!DT.dominates(CI, Latch->getTerminator()))
9144       continue;
9145 
9146     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9147       return true;
9148   }
9149 
9150   // If the loop is not reachable from the entry block, we risk running into an
9151   // infinite loop as we walk up into the dom tree.  These loops do not matter
9152   // anyway, so we just return a conservative answer when we see them.
9153   if (!DT.isReachableFromEntry(L->getHeader()))
9154     return false;
9155 
9156   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9157     return true;
9158 
9159   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9160        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9161     assert(DTN && "should reach the loop header before reaching the root!");
9162 
9163     BasicBlock *BB = DTN->getBlock();
9164     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9165       return true;
9166 
9167     BasicBlock *PBB = BB->getSinglePredecessor();
9168     if (!PBB)
9169       continue;
9170 
9171     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9172     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9173       continue;
9174 
9175     Value *Condition = ContinuePredicate->getCondition();
9176 
9177     // If we have an edge `E` within the loop body that dominates the only
9178     // latch, the condition guarding `E` also guards the backedge.  This
9179     // reasoning works only for loops with a single latch.
9180 
9181     BasicBlockEdge DominatingEdge(PBB, BB);
9182     if (DominatingEdge.isSingleEdge()) {
9183       // We're constructively (and conservatively) enumerating edges within the
9184       // loop body that dominate the latch.  The dominator tree better agree
9185       // with us on this:
9186       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9187 
9188       if (isImpliedCond(Pred, LHS, RHS, Condition,
9189                         BB != ContinuePredicate->getSuccessor(0)))
9190         return true;
9191     }
9192   }
9193 
9194   return false;
9195 }
9196 
9197 bool
9198 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9199                                           ICmpInst::Predicate Pred,
9200                                           const SCEV *LHS, const SCEV *RHS) {
9201   // Interpret a null as meaning no loop, where there is obviously no guard
9202   // (interprocedural conditions notwithstanding).
9203   if (!L) return false;
9204 
9205   // Both LHS and RHS must be available at loop entry.
9206   assert(isAvailableAtLoopEntry(LHS, L) &&
9207          "LHS is not available at Loop Entry");
9208   assert(isAvailableAtLoopEntry(RHS, L) &&
9209          "RHS is not available at Loop Entry");
9210 
9211   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9212     return true;
9213 
9214   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9215   // the facts (a >= b && a != b) separately. A typical situation is when the
9216   // non-strict comparison is known from ranges and non-equality is known from
9217   // dominating predicates. If we are proving strict comparison, we always try
9218   // to prove non-equality and non-strict comparison separately.
9219   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9220   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9221   bool ProvedNonStrictComparison = false;
9222   bool ProvedNonEquality = false;
9223 
9224   if (ProvingStrictComparison) {
9225     ProvedNonStrictComparison =
9226         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9227     ProvedNonEquality =
9228         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9229     if (ProvedNonStrictComparison && ProvedNonEquality)
9230       return true;
9231   }
9232 
9233   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9234   auto ProveViaGuard = [&](BasicBlock *Block) {
9235     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9236       return true;
9237     if (ProvingStrictComparison) {
9238       if (!ProvedNonStrictComparison)
9239         ProvedNonStrictComparison =
9240             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9241       if (!ProvedNonEquality)
9242         ProvedNonEquality =
9243             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9244       if (ProvedNonStrictComparison && ProvedNonEquality)
9245         return true;
9246     }
9247     return false;
9248   };
9249 
9250   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9251   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9252     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9253       return true;
9254     if (ProvingStrictComparison) {
9255       if (!ProvedNonStrictComparison)
9256         ProvedNonStrictComparison =
9257             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9258       if (!ProvedNonEquality)
9259         ProvedNonEquality =
9260             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9261       if (ProvedNonStrictComparison && ProvedNonEquality)
9262         return true;
9263     }
9264     return false;
9265   };
9266 
9267   // Starting at the loop predecessor, climb up the predecessor chain, as long
9268   // as there are predecessors that can be found that have unique successors
9269   // leading to the original header.
9270   for (std::pair<BasicBlock *, BasicBlock *>
9271          Pair(L->getLoopPredecessor(), L->getHeader());
9272        Pair.first;
9273        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9274 
9275     if (ProveViaGuard(Pair.first))
9276       return true;
9277 
9278     BranchInst *LoopEntryPredicate =
9279       dyn_cast<BranchInst>(Pair.first->getTerminator());
9280     if (!LoopEntryPredicate ||
9281         LoopEntryPredicate->isUnconditional())
9282       continue;
9283 
9284     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9285                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9286       return true;
9287   }
9288 
9289   // Check conditions due to any @llvm.assume intrinsics.
9290   for (auto &AssumeVH : AC.assumptions()) {
9291     if (!AssumeVH)
9292       continue;
9293     auto *CI = cast<CallInst>(AssumeVH);
9294     if (!DT.dominates(CI, L->getHeader()))
9295       continue;
9296 
9297     if (ProveViaCond(CI->getArgOperand(0), false))
9298       return true;
9299   }
9300 
9301   return false;
9302 }
9303 
9304 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9305                                     const SCEV *LHS, const SCEV *RHS,
9306                                     Value *FoundCondValue,
9307                                     bool Inverse) {
9308   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9309     return false;
9310 
9311   auto ClearOnExit =
9312       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9313 
9314   // Recursively handle And and Or conditions.
9315   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9316     if (BO->getOpcode() == Instruction::And) {
9317       if (!Inverse)
9318         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9319                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9320     } else if (BO->getOpcode() == Instruction::Or) {
9321       if (Inverse)
9322         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9323                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9324     }
9325   }
9326 
9327   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9328   if (!ICI) return false;
9329 
9330   // Now that we found a conditional branch that dominates the loop or controls
9331   // the loop latch. Check to see if it is the comparison we are looking for.
9332   ICmpInst::Predicate FoundPred;
9333   if (Inverse)
9334     FoundPred = ICI->getInversePredicate();
9335   else
9336     FoundPred = ICI->getPredicate();
9337 
9338   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9339   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9340 
9341   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9342 }
9343 
9344 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9345                                     const SCEV *RHS,
9346                                     ICmpInst::Predicate FoundPred,
9347                                     const SCEV *FoundLHS,
9348                                     const SCEV *FoundRHS) {
9349   // Balance the types.
9350   if (getTypeSizeInBits(LHS->getType()) <
9351       getTypeSizeInBits(FoundLHS->getType())) {
9352     if (CmpInst::isSigned(Pred)) {
9353       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9354       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9355     } else {
9356       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9357       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9358     }
9359   } else if (getTypeSizeInBits(LHS->getType()) >
9360       getTypeSizeInBits(FoundLHS->getType())) {
9361     if (CmpInst::isSigned(FoundPred)) {
9362       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9363       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9364     } else {
9365       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9366       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9367     }
9368   }
9369 
9370   // Canonicalize the query to match the way instcombine will have
9371   // canonicalized the comparison.
9372   if (SimplifyICmpOperands(Pred, LHS, RHS))
9373     if (LHS == RHS)
9374       return CmpInst::isTrueWhenEqual(Pred);
9375   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9376     if (FoundLHS == FoundRHS)
9377       return CmpInst::isFalseWhenEqual(FoundPred);
9378 
9379   // Check to see if we can make the LHS or RHS match.
9380   if (LHS == FoundRHS || RHS == FoundLHS) {
9381     if (isa<SCEVConstant>(RHS)) {
9382       std::swap(FoundLHS, FoundRHS);
9383       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9384     } else {
9385       std::swap(LHS, RHS);
9386       Pred = ICmpInst::getSwappedPredicate(Pred);
9387     }
9388   }
9389 
9390   // Check whether the found predicate is the same as the desired predicate.
9391   if (FoundPred == Pred)
9392     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9393 
9394   // Check whether swapping the found predicate makes it the same as the
9395   // desired predicate.
9396   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9397     if (isa<SCEVConstant>(RHS))
9398       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9399     else
9400       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9401                                    RHS, LHS, FoundLHS, FoundRHS);
9402   }
9403 
9404   // Unsigned comparison is the same as signed comparison when both the operands
9405   // are non-negative.
9406   if (CmpInst::isUnsigned(FoundPred) &&
9407       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9408       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9409     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9410 
9411   // Check if we can make progress by sharpening ranges.
9412   if (FoundPred == ICmpInst::ICMP_NE &&
9413       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9414 
9415     const SCEVConstant *C = nullptr;
9416     const SCEV *V = nullptr;
9417 
9418     if (isa<SCEVConstant>(FoundLHS)) {
9419       C = cast<SCEVConstant>(FoundLHS);
9420       V = FoundRHS;
9421     } else {
9422       C = cast<SCEVConstant>(FoundRHS);
9423       V = FoundLHS;
9424     }
9425 
9426     // The guarding predicate tells us that C != V. If the known range
9427     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9428     // range we consider has to correspond to same signedness as the
9429     // predicate we're interested in folding.
9430 
9431     APInt Min = ICmpInst::isSigned(Pred) ?
9432         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9433 
9434     if (Min == C->getAPInt()) {
9435       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9436       // This is true even if (Min + 1) wraps around -- in case of
9437       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9438 
9439       APInt SharperMin = Min + 1;
9440 
9441       switch (Pred) {
9442         case ICmpInst::ICMP_SGE:
9443         case ICmpInst::ICMP_UGE:
9444           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9445           // RHS, we're done.
9446           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9447                                     getConstant(SharperMin)))
9448             return true;
9449           LLVM_FALLTHROUGH;
9450 
9451         case ICmpInst::ICMP_SGT:
9452         case ICmpInst::ICMP_UGT:
9453           // We know from the range information that (V `Pred` Min ||
9454           // V == Min).  We know from the guarding condition that !(V
9455           // == Min).  This gives us
9456           //
9457           //       V `Pred` Min || V == Min && !(V == Min)
9458           //   =>  V `Pred` Min
9459           //
9460           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9461 
9462           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9463             return true;
9464           LLVM_FALLTHROUGH;
9465 
9466         default:
9467           // No change
9468           break;
9469       }
9470     }
9471   }
9472 
9473   // Check whether the actual condition is beyond sufficient.
9474   if (FoundPred == ICmpInst::ICMP_EQ)
9475     if (ICmpInst::isTrueWhenEqual(Pred))
9476       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9477         return true;
9478   if (Pred == ICmpInst::ICMP_NE)
9479     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9480       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9481         return true;
9482 
9483   // Otherwise assume the worst.
9484   return false;
9485 }
9486 
9487 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9488                                      const SCEV *&L, const SCEV *&R,
9489                                      SCEV::NoWrapFlags &Flags) {
9490   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9491   if (!AE || AE->getNumOperands() != 2)
9492     return false;
9493 
9494   L = AE->getOperand(0);
9495   R = AE->getOperand(1);
9496   Flags = AE->getNoWrapFlags();
9497   return true;
9498 }
9499 
9500 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9501                                                            const SCEV *Less) {
9502   // We avoid subtracting expressions here because this function is usually
9503   // fairly deep in the call stack (i.e. is called many times).
9504 
9505   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9506     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9507     const auto *MAR = cast<SCEVAddRecExpr>(More);
9508 
9509     if (LAR->getLoop() != MAR->getLoop())
9510       return None;
9511 
9512     // We look at affine expressions only; not for correctness but to keep
9513     // getStepRecurrence cheap.
9514     if (!LAR->isAffine() || !MAR->isAffine())
9515       return None;
9516 
9517     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9518       return None;
9519 
9520     Less = LAR->getStart();
9521     More = MAR->getStart();
9522 
9523     // fall through
9524   }
9525 
9526   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9527     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9528     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9529     return M - L;
9530   }
9531 
9532   SCEV::NoWrapFlags Flags;
9533   const SCEV *LLess = nullptr, *RLess = nullptr;
9534   const SCEV *LMore = nullptr, *RMore = nullptr;
9535   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9536   // Compare (X + C1) vs X.
9537   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9538     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9539       if (RLess == More)
9540         return -(C1->getAPInt());
9541 
9542   // Compare X vs (X + C2).
9543   if (splitBinaryAdd(More, LMore, RMore, Flags))
9544     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9545       if (RMore == Less)
9546         return C2->getAPInt();
9547 
9548   // Compare (X + C1) vs (X + C2).
9549   if (C1 && C2 && RLess == RMore)
9550     return C2->getAPInt() - C1->getAPInt();
9551 
9552   return None;
9553 }
9554 
9555 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9556     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9557     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9558   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9559     return false;
9560 
9561   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9562   if (!AddRecLHS)
9563     return false;
9564 
9565   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9566   if (!AddRecFoundLHS)
9567     return false;
9568 
9569   // We'd like to let SCEV reason about control dependencies, so we constrain
9570   // both the inequalities to be about add recurrences on the same loop.  This
9571   // way we can use isLoopEntryGuardedByCond later.
9572 
9573   const Loop *L = AddRecFoundLHS->getLoop();
9574   if (L != AddRecLHS->getLoop())
9575     return false;
9576 
9577   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9578   //
9579   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9580   //                                                                  ... (2)
9581   //
9582   // Informal proof for (2), assuming (1) [*]:
9583   //
9584   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9585   //
9586   // Then
9587   //
9588   //       FoundLHS s< FoundRHS s< INT_MIN - C
9589   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9590   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9591   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9592   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9593   // <=>  FoundLHS + C s< FoundRHS + C
9594   //
9595   // [*]: (1) can be proved by ruling out overflow.
9596   //
9597   // [**]: This can be proved by analyzing all the four possibilities:
9598   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9599   //    (A s>= 0, B s>= 0).
9600   //
9601   // Note:
9602   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9603   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9604   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9605   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9606   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9607   // C)".
9608 
9609   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9610   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9611   if (!LDiff || !RDiff || *LDiff != *RDiff)
9612     return false;
9613 
9614   if (LDiff->isMinValue())
9615     return true;
9616 
9617   APInt FoundRHSLimit;
9618 
9619   if (Pred == CmpInst::ICMP_ULT) {
9620     FoundRHSLimit = -(*RDiff);
9621   } else {
9622     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9623     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9624   }
9625 
9626   // Try to prove (1) or (2), as needed.
9627   return isAvailableAtLoopEntry(FoundRHS, L) &&
9628          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9629                                   getConstant(FoundRHSLimit));
9630 }
9631 
9632 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9633                                         const SCEV *LHS, const SCEV *RHS,
9634                                         const SCEV *FoundLHS,
9635                                         const SCEV *FoundRHS, unsigned Depth) {
9636   const PHINode *LPhi = nullptr, *RPhi = nullptr;
9637 
9638   auto ClearOnExit = make_scope_exit([&]() {
9639     if (LPhi) {
9640       bool Erased = PendingMerges.erase(LPhi);
9641       assert(Erased && "Failed to erase LPhi!");
9642       (void)Erased;
9643     }
9644     if (RPhi) {
9645       bool Erased = PendingMerges.erase(RPhi);
9646       assert(Erased && "Failed to erase RPhi!");
9647       (void)Erased;
9648     }
9649   });
9650 
9651   // Find respective Phis and check that they are not being pending.
9652   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9653     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9654       if (!PendingMerges.insert(Phi).second)
9655         return false;
9656       LPhi = Phi;
9657     }
9658   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9659     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9660       // If we detect a loop of Phi nodes being processed by this method, for
9661       // example:
9662       //
9663       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9664       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9665       //
9666       // we don't want to deal with a case that complex, so return conservative
9667       // answer false.
9668       if (!PendingMerges.insert(Phi).second)
9669         return false;
9670       RPhi = Phi;
9671     }
9672 
9673   // If none of LHS, RHS is a Phi, nothing to do here.
9674   if (!LPhi && !RPhi)
9675     return false;
9676 
9677   // If there is a SCEVUnknown Phi we are interested in, make it left.
9678   if (!LPhi) {
9679     std::swap(LHS, RHS);
9680     std::swap(FoundLHS, FoundRHS);
9681     std::swap(LPhi, RPhi);
9682     Pred = ICmpInst::getSwappedPredicate(Pred);
9683   }
9684 
9685   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
9686   const BasicBlock *LBB = LPhi->getParent();
9687   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9688 
9689   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
9690     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
9691            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
9692            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
9693   };
9694 
9695   if (RPhi && RPhi->getParent() == LBB) {
9696     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
9697     // If we compare two Phis from the same block, and for each entry block
9698     // the predicate is true for incoming values from this block, then the
9699     // predicate is also true for the Phis.
9700     for (const BasicBlock *IncBB : predecessors(LBB)) {
9701       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9702       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
9703       if (!ProvedEasily(L, R))
9704         return false;
9705     }
9706   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
9707     // Case two: RHS is also a Phi from the same basic block, and it is an
9708     // AddRec. It means that there is a loop which has both AddRec and Unknown
9709     // PHIs, for it we can compare incoming values of AddRec from above the loop
9710     // and latch with their respective incoming values of LPhi.
9711     assert(LPhi->getNumIncomingValues() == 2 &&
9712            "Phi node standing in loop header does not have exactly 2 inputs?");
9713     auto *RLoop = RAR->getLoop();
9714     auto *Predecessor = RLoop->getLoopPredecessor();
9715     assert(Predecessor && "Loop with AddRec with no predecessor?");
9716     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
9717     if (!ProvedEasily(L1, RAR->getStart()))
9718       return false;
9719     auto *Latch = RLoop->getLoopLatch();
9720     assert(Latch && "Loop with AddRec with no latch?");
9721     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
9722     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
9723       return false;
9724   } else {
9725     // In all other cases go over inputs of LHS and compare each of them to RHS,
9726     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
9727     // At this point RHS is either a non-Phi, or it is a Phi from some block
9728     // different from LBB.
9729     for (const BasicBlock *IncBB : predecessors(LBB)) {
9730       // Check that RHS is available in this block.
9731       if (!dominates(RHS, IncBB))
9732         return false;
9733       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9734       if (!ProvedEasily(L, RHS))
9735         return false;
9736     }
9737   }
9738   return true;
9739 }
9740 
9741 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9742                                             const SCEV *LHS, const SCEV *RHS,
9743                                             const SCEV *FoundLHS,
9744                                             const SCEV *FoundRHS) {
9745   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9746     return true;
9747 
9748   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9749     return true;
9750 
9751   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9752                                      FoundLHS, FoundRHS) ||
9753          // ~x < ~y --> x > y
9754          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9755                                      getNotSCEV(FoundRHS),
9756                                      getNotSCEV(FoundLHS));
9757 }
9758 
9759 /// If Expr computes ~A, return A else return nullptr
9760 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9761   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9762   if (!Add || Add->getNumOperands() != 2 ||
9763       !Add->getOperand(0)->isAllOnesValue())
9764     return nullptr;
9765 
9766   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9767   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9768       !AddRHS->getOperand(0)->isAllOnesValue())
9769     return nullptr;
9770 
9771   return AddRHS->getOperand(1);
9772 }
9773 
9774 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9775 template<typename MaxExprType>
9776 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9777                               const SCEV *Candidate) {
9778   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9779   if (!MaxExpr) return false;
9780 
9781   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9782 }
9783 
9784 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9785 template<typename MaxExprType>
9786 static bool IsMinConsistingOf(ScalarEvolution &SE,
9787                               const SCEV *MaybeMinExpr,
9788                               const SCEV *Candidate) {
9789   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9790   if (!MaybeMaxExpr)
9791     return false;
9792 
9793   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9794 }
9795 
9796 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9797                                            ICmpInst::Predicate Pred,
9798                                            const SCEV *LHS, const SCEV *RHS) {
9799   // If both sides are affine addrecs for the same loop, with equal
9800   // steps, and we know the recurrences don't wrap, then we only
9801   // need to check the predicate on the starting values.
9802 
9803   if (!ICmpInst::isRelational(Pred))
9804     return false;
9805 
9806   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9807   if (!LAR)
9808     return false;
9809   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9810   if (!RAR)
9811     return false;
9812   if (LAR->getLoop() != RAR->getLoop())
9813     return false;
9814   if (!LAR->isAffine() || !RAR->isAffine())
9815     return false;
9816 
9817   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9818     return false;
9819 
9820   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9821                          SCEV::FlagNSW : SCEV::FlagNUW;
9822   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9823     return false;
9824 
9825   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9826 }
9827 
9828 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9829 /// expression?
9830 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9831                                         ICmpInst::Predicate Pred,
9832                                         const SCEV *LHS, const SCEV *RHS) {
9833   switch (Pred) {
9834   default:
9835     return false;
9836 
9837   case ICmpInst::ICMP_SGE:
9838     std::swap(LHS, RHS);
9839     LLVM_FALLTHROUGH;
9840   case ICmpInst::ICMP_SLE:
9841     return
9842       // min(A, ...) <= A
9843       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9844       // A <= max(A, ...)
9845       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9846 
9847   case ICmpInst::ICMP_UGE:
9848     std::swap(LHS, RHS);
9849     LLVM_FALLTHROUGH;
9850   case ICmpInst::ICMP_ULE:
9851     return
9852       // min(A, ...) <= A
9853       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9854       // A <= max(A, ...)
9855       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9856   }
9857 
9858   llvm_unreachable("covered switch fell through?!");
9859 }
9860 
9861 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9862                                              const SCEV *LHS, const SCEV *RHS,
9863                                              const SCEV *FoundLHS,
9864                                              const SCEV *FoundRHS,
9865                                              unsigned Depth) {
9866   assert(getTypeSizeInBits(LHS->getType()) ==
9867              getTypeSizeInBits(RHS->getType()) &&
9868          "LHS and RHS have different sizes?");
9869   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9870              getTypeSizeInBits(FoundRHS->getType()) &&
9871          "FoundLHS and FoundRHS have different sizes?");
9872   // We want to avoid hurting the compile time with analysis of too big trees.
9873   if (Depth > MaxSCEVOperationsImplicationDepth)
9874     return false;
9875   // We only want to work with ICMP_SGT comparison so far.
9876   // TODO: Extend to ICMP_UGT?
9877   if (Pred == ICmpInst::ICMP_SLT) {
9878     Pred = ICmpInst::ICMP_SGT;
9879     std::swap(LHS, RHS);
9880     std::swap(FoundLHS, FoundRHS);
9881   }
9882   if (Pred != ICmpInst::ICMP_SGT)
9883     return false;
9884 
9885   auto GetOpFromSExt = [&](const SCEV *S) {
9886     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9887       return Ext->getOperand();
9888     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9889     // the constant in some cases.
9890     return S;
9891   };
9892 
9893   // Acquire values from extensions.
9894   auto *OrigLHS = LHS;
9895   auto *OrigFoundLHS = FoundLHS;
9896   LHS = GetOpFromSExt(LHS);
9897   FoundLHS = GetOpFromSExt(FoundLHS);
9898 
9899   // Is the SGT predicate can be proved trivially or using the found context.
9900   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9901     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9902            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9903                                   FoundRHS, Depth + 1);
9904   };
9905 
9906   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9907     // We want to avoid creation of any new non-constant SCEV. Since we are
9908     // going to compare the operands to RHS, we should be certain that we don't
9909     // need any size extensions for this. So let's decline all cases when the
9910     // sizes of types of LHS and RHS do not match.
9911     // TODO: Maybe try to get RHS from sext to catch more cases?
9912     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9913       return false;
9914 
9915     // Should not overflow.
9916     if (!LHSAddExpr->hasNoSignedWrap())
9917       return false;
9918 
9919     auto *LL = LHSAddExpr->getOperand(0);
9920     auto *LR = LHSAddExpr->getOperand(1);
9921     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9922 
9923     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9924     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9925       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9926     };
9927     // Try to prove the following rule:
9928     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9929     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9930     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9931       return true;
9932   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9933     Value *LL, *LR;
9934     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9935 
9936     using namespace llvm::PatternMatch;
9937 
9938     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9939       // Rules for division.
9940       // We are going to perform some comparisons with Denominator and its
9941       // derivative expressions. In general case, creating a SCEV for it may
9942       // lead to a complex analysis of the entire graph, and in particular it
9943       // can request trip count recalculation for the same loop. This would
9944       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9945       // this, we only want to create SCEVs that are constants in this section.
9946       // So we bail if Denominator is not a constant.
9947       if (!isa<ConstantInt>(LR))
9948         return false;
9949 
9950       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9951 
9952       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9953       // then a SCEV for the numerator already exists and matches with FoundLHS.
9954       auto *Numerator = getExistingSCEV(LL);
9955       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9956         return false;
9957 
9958       // Make sure that the numerator matches with FoundLHS and the denominator
9959       // is positive.
9960       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9961         return false;
9962 
9963       auto *DTy = Denominator->getType();
9964       auto *FRHSTy = FoundRHS->getType();
9965       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9966         // One of types is a pointer and another one is not. We cannot extend
9967         // them properly to a wider type, so let us just reject this case.
9968         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9969         // to avoid this check.
9970         return false;
9971 
9972       // Given that:
9973       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9974       auto *WTy = getWiderType(DTy, FRHSTy);
9975       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9976       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9977 
9978       // Try to prove the following rule:
9979       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9980       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9981       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9982       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9983       if (isKnownNonPositive(RHS) &&
9984           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9985         return true;
9986 
9987       // Try to prove the following rule:
9988       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9989       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9990       // If we divide it by Denominator > 2, then:
9991       // 1. If FoundLHS is negative, then the result is 0.
9992       // 2. If FoundLHS is non-negative, then the result is non-negative.
9993       // Anyways, the result is non-negative.
9994       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9995       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9996       if (isKnownNegative(RHS) &&
9997           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9998         return true;
9999     }
10000   }
10001 
10002   // If our expression contained SCEVUnknown Phis, and we split it down and now
10003   // need to prove something for them, try to prove the predicate for every
10004   // possible incoming values of those Phis.
10005   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10006     return true;
10007 
10008   return false;
10009 }
10010 
10011 bool
10012 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10013                                            const SCEV *LHS, const SCEV *RHS) {
10014   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10015          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10016          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10017          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10018 }
10019 
10020 bool
10021 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10022                                              const SCEV *LHS, const SCEV *RHS,
10023                                              const SCEV *FoundLHS,
10024                                              const SCEV *FoundRHS) {
10025   switch (Pred) {
10026   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10027   case ICmpInst::ICMP_EQ:
10028   case ICmpInst::ICMP_NE:
10029     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10030       return true;
10031     break;
10032   case ICmpInst::ICMP_SLT:
10033   case ICmpInst::ICMP_SLE:
10034     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10035         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10036       return true;
10037     break;
10038   case ICmpInst::ICMP_SGT:
10039   case ICmpInst::ICMP_SGE:
10040     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10041         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10042       return true;
10043     break;
10044   case ICmpInst::ICMP_ULT:
10045   case ICmpInst::ICMP_ULE:
10046     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10047         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10048       return true;
10049     break;
10050   case ICmpInst::ICMP_UGT:
10051   case ICmpInst::ICMP_UGE:
10052     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10053         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10054       return true;
10055     break;
10056   }
10057 
10058   // Maybe it can be proved via operations?
10059   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10060     return true;
10061 
10062   return false;
10063 }
10064 
10065 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10066                                                      const SCEV *LHS,
10067                                                      const SCEV *RHS,
10068                                                      const SCEV *FoundLHS,
10069                                                      const SCEV *FoundRHS) {
10070   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10071     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10072     // reduce the compile time impact of this optimization.
10073     return false;
10074 
10075   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10076   if (!Addend)
10077     return false;
10078 
10079   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10080 
10081   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10082   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10083   ConstantRange FoundLHSRange =
10084       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10085 
10086   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10087   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10088 
10089   // We can also compute the range of values for `LHS` that satisfy the
10090   // consequent, "`LHS` `Pred` `RHS`":
10091   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10092   ConstantRange SatisfyingLHSRange =
10093       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10094 
10095   // The antecedent implies the consequent if every value of `LHS` that
10096   // satisfies the antecedent also satisfies the consequent.
10097   return SatisfyingLHSRange.contains(LHSRange);
10098 }
10099 
10100 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10101                                          bool IsSigned, bool NoWrap) {
10102   assert(isKnownPositive(Stride) && "Positive stride expected!");
10103 
10104   if (NoWrap) return false;
10105 
10106   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10107   const SCEV *One = getOne(Stride->getType());
10108 
10109   if (IsSigned) {
10110     APInt MaxRHS = getSignedRangeMax(RHS);
10111     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10112     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10113 
10114     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10115     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10116   }
10117 
10118   APInt MaxRHS = getUnsignedRangeMax(RHS);
10119   APInt MaxValue = APInt::getMaxValue(BitWidth);
10120   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10121 
10122   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10123   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10124 }
10125 
10126 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10127                                          bool IsSigned, bool NoWrap) {
10128   if (NoWrap) return false;
10129 
10130   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10131   const SCEV *One = getOne(Stride->getType());
10132 
10133   if (IsSigned) {
10134     APInt MinRHS = getSignedRangeMin(RHS);
10135     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10136     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10137 
10138     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10139     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10140   }
10141 
10142   APInt MinRHS = getUnsignedRangeMin(RHS);
10143   APInt MinValue = APInt::getMinValue(BitWidth);
10144   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10145 
10146   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10147   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10148 }
10149 
10150 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10151                                             bool Equality) {
10152   const SCEV *One = getOne(Step->getType());
10153   Delta = Equality ? getAddExpr(Delta, Step)
10154                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10155   return getUDivExpr(Delta, Step);
10156 }
10157 
10158 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10159                                                     const SCEV *Stride,
10160                                                     const SCEV *End,
10161                                                     unsigned BitWidth,
10162                                                     bool IsSigned) {
10163 
10164   assert(!isKnownNonPositive(Stride) &&
10165          "Stride is expected strictly positive!");
10166   // Calculate the maximum backedge count based on the range of values
10167   // permitted by Start, End, and Stride.
10168   const SCEV *MaxBECount;
10169   APInt MinStart =
10170       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10171 
10172   APInt StrideForMaxBECount =
10173       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10174 
10175   // We already know that the stride is positive, so we paper over conservatism
10176   // in our range computation by forcing StrideForMaxBECount to be at least one.
10177   // In theory this is unnecessary, but we expect MaxBECount to be a
10178   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10179   // is nothing to constant fold it to).
10180   APInt One(BitWidth, 1, IsSigned);
10181   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10182 
10183   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10184                             : APInt::getMaxValue(BitWidth);
10185   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10186 
10187   // Although End can be a MAX expression we estimate MaxEnd considering only
10188   // the case End = RHS of the loop termination condition. This is safe because
10189   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10190   // taken count.
10191   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10192                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10193 
10194   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10195                               getConstant(StrideForMaxBECount) /* Step */,
10196                               false /* Equality */);
10197 
10198   return MaxBECount;
10199 }
10200 
10201 ScalarEvolution::ExitLimit
10202 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10203                                   const Loop *L, bool IsSigned,
10204                                   bool ControlsExit, bool AllowPredicates) {
10205   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10206 
10207   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10208   bool PredicatedIV = false;
10209 
10210   if (!IV && AllowPredicates) {
10211     // Try to make this an AddRec using runtime tests, in the first X
10212     // iterations of this loop, where X is the SCEV expression found by the
10213     // algorithm below.
10214     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10215     PredicatedIV = true;
10216   }
10217 
10218   // Avoid weird loops
10219   if (!IV || IV->getLoop() != L || !IV->isAffine())
10220     return getCouldNotCompute();
10221 
10222   bool NoWrap = ControlsExit &&
10223                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10224 
10225   const SCEV *Stride = IV->getStepRecurrence(*this);
10226 
10227   bool PositiveStride = isKnownPositive(Stride);
10228 
10229   // Avoid negative or zero stride values.
10230   if (!PositiveStride) {
10231     // We can compute the correct backedge taken count for loops with unknown
10232     // strides if we can prove that the loop is not an infinite loop with side
10233     // effects. Here's the loop structure we are trying to handle -
10234     //
10235     // i = start
10236     // do {
10237     //   A[i] = i;
10238     //   i += s;
10239     // } while (i < end);
10240     //
10241     // The backedge taken count for such loops is evaluated as -
10242     // (max(end, start + stride) - start - 1) /u stride
10243     //
10244     // The additional preconditions that we need to check to prove correctness
10245     // of the above formula is as follows -
10246     //
10247     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10248     //    NoWrap flag).
10249     // b) loop is single exit with no side effects.
10250     //
10251     //
10252     // Precondition a) implies that if the stride is negative, this is a single
10253     // trip loop. The backedge taken count formula reduces to zero in this case.
10254     //
10255     // Precondition b) implies that the unknown stride cannot be zero otherwise
10256     // we have UB.
10257     //
10258     // The positive stride case is the same as isKnownPositive(Stride) returning
10259     // true (original behavior of the function).
10260     //
10261     // We want to make sure that the stride is truly unknown as there are edge
10262     // cases where ScalarEvolution propagates no wrap flags to the
10263     // post-increment/decrement IV even though the increment/decrement operation
10264     // itself is wrapping. The computed backedge taken count may be wrong in
10265     // such cases. This is prevented by checking that the stride is not known to
10266     // be either positive or non-positive. For example, no wrap flags are
10267     // propagated to the post-increment IV of this loop with a trip count of 2 -
10268     //
10269     // unsigned char i;
10270     // for(i=127; i<128; i+=129)
10271     //   A[i] = i;
10272     //
10273     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10274         !loopHasNoSideEffects(L))
10275       return getCouldNotCompute();
10276   } else if (!Stride->isOne() &&
10277              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10278     // Avoid proven overflow cases: this will ensure that the backedge taken
10279     // count will not generate any unsigned overflow. Relaxed no-overflow
10280     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10281     // undefined behaviors like the case of C language.
10282     return getCouldNotCompute();
10283 
10284   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10285                                       : ICmpInst::ICMP_ULT;
10286   const SCEV *Start = IV->getStart();
10287   const SCEV *End = RHS;
10288   // When the RHS is not invariant, we do not know the end bound of the loop and
10289   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10290   // calculate the MaxBECount, given the start, stride and max value for the end
10291   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10292   // checked above).
10293   if (!isLoopInvariant(RHS, L)) {
10294     const SCEV *MaxBECount = computeMaxBECountForLT(
10295         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10296     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10297                      false /*MaxOrZero*/, Predicates);
10298   }
10299   // If the backedge is taken at least once, then it will be taken
10300   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10301   // is the LHS value of the less-than comparison the first time it is evaluated
10302   // and End is the RHS.
10303   const SCEV *BECountIfBackedgeTaken =
10304     computeBECount(getMinusSCEV(End, Start), Stride, false);
10305   // If the loop entry is guarded by the result of the backedge test of the
10306   // first loop iteration, then we know the backedge will be taken at least
10307   // once and so the backedge taken count is as above. If not then we use the
10308   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10309   // as if the backedge is taken at least once max(End,Start) is End and so the
10310   // result is as above, and if not max(End,Start) is Start so we get a backedge
10311   // count of zero.
10312   const SCEV *BECount;
10313   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10314     BECount = BECountIfBackedgeTaken;
10315   else {
10316     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10317     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10318   }
10319 
10320   const SCEV *MaxBECount;
10321   bool MaxOrZero = false;
10322   if (isa<SCEVConstant>(BECount))
10323     MaxBECount = BECount;
10324   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10325     // If we know exactly how many times the backedge will be taken if it's
10326     // taken at least once, then the backedge count will either be that or
10327     // zero.
10328     MaxBECount = BECountIfBackedgeTaken;
10329     MaxOrZero = true;
10330   } else {
10331     MaxBECount = computeMaxBECountForLT(
10332         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10333   }
10334 
10335   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10336       !isa<SCEVCouldNotCompute>(BECount))
10337     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10338 
10339   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10340 }
10341 
10342 ScalarEvolution::ExitLimit
10343 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10344                                      const Loop *L, bool IsSigned,
10345                                      bool ControlsExit, bool AllowPredicates) {
10346   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10347   // We handle only IV > Invariant
10348   if (!isLoopInvariant(RHS, L))
10349     return getCouldNotCompute();
10350 
10351   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10352   if (!IV && AllowPredicates)
10353     // Try to make this an AddRec using runtime tests, in the first X
10354     // iterations of this loop, where X is the SCEV expression found by the
10355     // algorithm below.
10356     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10357 
10358   // Avoid weird loops
10359   if (!IV || IV->getLoop() != L || !IV->isAffine())
10360     return getCouldNotCompute();
10361 
10362   bool NoWrap = ControlsExit &&
10363                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10364 
10365   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10366 
10367   // Avoid negative or zero stride values
10368   if (!isKnownPositive(Stride))
10369     return getCouldNotCompute();
10370 
10371   // Avoid proven overflow cases: this will ensure that the backedge taken count
10372   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10373   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10374   // behaviors like the case of C language.
10375   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10376     return getCouldNotCompute();
10377 
10378   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10379                                       : ICmpInst::ICMP_UGT;
10380 
10381   const SCEV *Start = IV->getStart();
10382   const SCEV *End = RHS;
10383   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10384     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10385 
10386   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10387 
10388   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10389                             : getUnsignedRangeMax(Start);
10390 
10391   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10392                              : getUnsignedRangeMin(Stride);
10393 
10394   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10395   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10396                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10397 
10398   // Although End can be a MIN expression we estimate MinEnd considering only
10399   // the case End = RHS. This is safe because in the other case (Start - End)
10400   // is zero, leading to a zero maximum backedge taken count.
10401   APInt MinEnd =
10402     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10403              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10404 
10405 
10406   const SCEV *MaxBECount = getCouldNotCompute();
10407   if (isa<SCEVConstant>(BECount))
10408     MaxBECount = BECount;
10409   else
10410     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10411                                 getConstant(MinStride), false);
10412 
10413   if (isa<SCEVCouldNotCompute>(MaxBECount))
10414     MaxBECount = BECount;
10415 
10416   return ExitLimit(BECount, MaxBECount, false, Predicates);
10417 }
10418 
10419 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10420                                                     ScalarEvolution &SE) const {
10421   if (Range.isFullSet())  // Infinite loop.
10422     return SE.getCouldNotCompute();
10423 
10424   // If the start is a non-zero constant, shift the range to simplify things.
10425   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10426     if (!SC->getValue()->isZero()) {
10427       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10428       Operands[0] = SE.getZero(SC->getType());
10429       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10430                                              getNoWrapFlags(FlagNW));
10431       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10432         return ShiftedAddRec->getNumIterationsInRange(
10433             Range.subtract(SC->getAPInt()), SE);
10434       // This is strange and shouldn't happen.
10435       return SE.getCouldNotCompute();
10436     }
10437 
10438   // The only time we can solve this is when we have all constant indices.
10439   // Otherwise, we cannot determine the overflow conditions.
10440   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10441     return SE.getCouldNotCompute();
10442 
10443   // Okay at this point we know that all elements of the chrec are constants and
10444   // that the start element is zero.
10445 
10446   // First check to see if the range contains zero.  If not, the first
10447   // iteration exits.
10448   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10449   if (!Range.contains(APInt(BitWidth, 0)))
10450     return SE.getZero(getType());
10451 
10452   if (isAffine()) {
10453     // If this is an affine expression then we have this situation:
10454     //   Solve {0,+,A} in Range  ===  Ax in Range
10455 
10456     // We know that zero is in the range.  If A is positive then we know that
10457     // the upper value of the range must be the first possible exit value.
10458     // If A is negative then the lower of the range is the last possible loop
10459     // value.  Also note that we already checked for a full range.
10460     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10461     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10462 
10463     // The exit value should be (End+A)/A.
10464     APInt ExitVal = (End + A).udiv(A);
10465     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10466 
10467     // Evaluate at the exit value.  If we really did fall out of the valid
10468     // range, then we computed our trip count, otherwise wrap around or other
10469     // things must have happened.
10470     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10471     if (Range.contains(Val->getValue()))
10472       return SE.getCouldNotCompute();  // Something strange happened
10473 
10474     // Ensure that the previous value is in the range.  This is a sanity check.
10475     assert(Range.contains(
10476            EvaluateConstantChrecAtConstant(this,
10477            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10478            "Linear scev computation is off in a bad way!");
10479     return SE.getConstant(ExitValue);
10480   } else if (isQuadratic()) {
10481     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10482     // quadratic equation to solve it.  To do this, we must frame our problem in
10483     // terms of figuring out when zero is crossed, instead of when
10484     // Range.getUpper() is crossed.
10485     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10486     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10487     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10488 
10489     // Next, solve the constructed addrec
10490     if (auto Roots =
10491             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10492       const SCEVConstant *R1 = Roots->first;
10493       const SCEVConstant *R2 = Roots->second;
10494       // Pick the smallest positive root value.
10495       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10496               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10497         if (!CB->getZExtValue())
10498           std::swap(R1, R2); // R1 is the minimum root now.
10499 
10500         // Make sure the root is not off by one.  The returned iteration should
10501         // not be in the range, but the previous one should be.  When solving
10502         // for "X*X < 5", for example, we should not return a root of 2.
10503         ConstantInt *R1Val =
10504             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10505         if (Range.contains(R1Val->getValue())) {
10506           // The next iteration must be out of the range...
10507           ConstantInt *NextVal =
10508               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10509 
10510           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10511           if (!Range.contains(R1Val->getValue()))
10512             return SE.getConstant(NextVal);
10513           return SE.getCouldNotCompute(); // Something strange happened
10514         }
10515 
10516         // If R1 was not in the range, then it is a good return value.  Make
10517         // sure that R1-1 WAS in the range though, just in case.
10518         ConstantInt *NextVal =
10519             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10520         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10521         if (Range.contains(R1Val->getValue()))
10522           return R1;
10523         return SE.getCouldNotCompute(); // Something strange happened
10524       }
10525     }
10526   }
10527 
10528   return SE.getCouldNotCompute();
10529 }
10530 
10531 const SCEVAddRecExpr *
10532 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10533   assert(getNumOperands() > 1 && "AddRec with zero step?");
10534   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10535   // but in this case we cannot guarantee that the value returned will be an
10536   // AddRec because SCEV does not have a fixed point where it stops
10537   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10538   // may happen if we reach arithmetic depth limit while simplifying. So we
10539   // construct the returned value explicitly.
10540   SmallVector<const SCEV *, 3> Ops;
10541   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10542   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10543   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10544     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10545   // We know that the last operand is not a constant zero (otherwise it would
10546   // have been popped out earlier). This guarantees us that if the result has
10547   // the same last operand, then it will also not be popped out, meaning that
10548   // the returned value will be an AddRec.
10549   const SCEV *Last = getOperand(getNumOperands() - 1);
10550   assert(!Last->isZero() && "Recurrency with zero step?");
10551   Ops.push_back(Last);
10552   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10553                                                SCEV::FlagAnyWrap));
10554 }
10555 
10556 // Return true when S contains at least an undef value.
10557 static inline bool containsUndefs(const SCEV *S) {
10558   return SCEVExprContains(S, [](const SCEV *S) {
10559     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10560       return isa<UndefValue>(SU->getValue());
10561     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10562       return isa<UndefValue>(SC->getValue());
10563     return false;
10564   });
10565 }
10566 
10567 namespace {
10568 
10569 // Collect all steps of SCEV expressions.
10570 struct SCEVCollectStrides {
10571   ScalarEvolution &SE;
10572   SmallVectorImpl<const SCEV *> &Strides;
10573 
10574   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10575       : SE(SE), Strides(S) {}
10576 
10577   bool follow(const SCEV *S) {
10578     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10579       Strides.push_back(AR->getStepRecurrence(SE));
10580     return true;
10581   }
10582 
10583   bool isDone() const { return false; }
10584 };
10585 
10586 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10587 struct SCEVCollectTerms {
10588   SmallVectorImpl<const SCEV *> &Terms;
10589 
10590   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10591 
10592   bool follow(const SCEV *S) {
10593     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10594         isa<SCEVSignExtendExpr>(S)) {
10595       if (!containsUndefs(S))
10596         Terms.push_back(S);
10597 
10598       // Stop recursion: once we collected a term, do not walk its operands.
10599       return false;
10600     }
10601 
10602     // Keep looking.
10603     return true;
10604   }
10605 
10606   bool isDone() const { return false; }
10607 };
10608 
10609 // Check if a SCEV contains an AddRecExpr.
10610 struct SCEVHasAddRec {
10611   bool &ContainsAddRec;
10612 
10613   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10614     ContainsAddRec = false;
10615   }
10616 
10617   bool follow(const SCEV *S) {
10618     if (isa<SCEVAddRecExpr>(S)) {
10619       ContainsAddRec = true;
10620 
10621       // Stop recursion: once we collected a term, do not walk its operands.
10622       return false;
10623     }
10624 
10625     // Keep looking.
10626     return true;
10627   }
10628 
10629   bool isDone() const { return false; }
10630 };
10631 
10632 // Find factors that are multiplied with an expression that (possibly as a
10633 // subexpression) contains an AddRecExpr. In the expression:
10634 //
10635 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10636 //
10637 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10638 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10639 // parameters as they form a product with an induction variable.
10640 //
10641 // This collector expects all array size parameters to be in the same MulExpr.
10642 // It might be necessary to later add support for collecting parameters that are
10643 // spread over different nested MulExpr.
10644 struct SCEVCollectAddRecMultiplies {
10645   SmallVectorImpl<const SCEV *> &Terms;
10646   ScalarEvolution &SE;
10647 
10648   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10649       : Terms(T), SE(SE) {}
10650 
10651   bool follow(const SCEV *S) {
10652     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10653       bool HasAddRec = false;
10654       SmallVector<const SCEV *, 0> Operands;
10655       for (auto Op : Mul->operands()) {
10656         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10657         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10658           Operands.push_back(Op);
10659         } else if (Unknown) {
10660           HasAddRec = true;
10661         } else {
10662           bool ContainsAddRec;
10663           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10664           visitAll(Op, ContiansAddRec);
10665           HasAddRec |= ContainsAddRec;
10666         }
10667       }
10668       if (Operands.size() == 0)
10669         return true;
10670 
10671       if (!HasAddRec)
10672         return false;
10673 
10674       Terms.push_back(SE.getMulExpr(Operands));
10675       // Stop recursion: once we collected a term, do not walk its operands.
10676       return false;
10677     }
10678 
10679     // Keep looking.
10680     return true;
10681   }
10682 
10683   bool isDone() const { return false; }
10684 };
10685 
10686 } // end anonymous namespace
10687 
10688 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10689 /// two places:
10690 ///   1) The strides of AddRec expressions.
10691 ///   2) Unknowns that are multiplied with AddRec expressions.
10692 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10693     SmallVectorImpl<const SCEV *> &Terms) {
10694   SmallVector<const SCEV *, 4> Strides;
10695   SCEVCollectStrides StrideCollector(*this, Strides);
10696   visitAll(Expr, StrideCollector);
10697 
10698   LLVM_DEBUG({
10699     dbgs() << "Strides:\n";
10700     for (const SCEV *S : Strides)
10701       dbgs() << *S << "\n";
10702   });
10703 
10704   for (const SCEV *S : Strides) {
10705     SCEVCollectTerms TermCollector(Terms);
10706     visitAll(S, TermCollector);
10707   }
10708 
10709   LLVM_DEBUG({
10710     dbgs() << "Terms:\n";
10711     for (const SCEV *T : Terms)
10712       dbgs() << *T << "\n";
10713   });
10714 
10715   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10716   visitAll(Expr, MulCollector);
10717 }
10718 
10719 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10720                                    SmallVectorImpl<const SCEV *> &Terms,
10721                                    SmallVectorImpl<const SCEV *> &Sizes) {
10722   int Last = Terms.size() - 1;
10723   const SCEV *Step = Terms[Last];
10724 
10725   // End of recursion.
10726   if (Last == 0) {
10727     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10728       SmallVector<const SCEV *, 2> Qs;
10729       for (const SCEV *Op : M->operands())
10730         if (!isa<SCEVConstant>(Op))
10731           Qs.push_back(Op);
10732 
10733       Step = SE.getMulExpr(Qs);
10734     }
10735 
10736     Sizes.push_back(Step);
10737     return true;
10738   }
10739 
10740   for (const SCEV *&Term : Terms) {
10741     // Normalize the terms before the next call to findArrayDimensionsRec.
10742     const SCEV *Q, *R;
10743     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10744 
10745     // Bail out when GCD does not evenly divide one of the terms.
10746     if (!R->isZero())
10747       return false;
10748 
10749     Term = Q;
10750   }
10751 
10752   // Remove all SCEVConstants.
10753   Terms.erase(
10754       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10755       Terms.end());
10756 
10757   if (Terms.size() > 0)
10758     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10759       return false;
10760 
10761   Sizes.push_back(Step);
10762   return true;
10763 }
10764 
10765 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10766 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10767   for (const SCEV *T : Terms)
10768     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10769       return true;
10770   return false;
10771 }
10772 
10773 // Return the number of product terms in S.
10774 static inline int numberOfTerms(const SCEV *S) {
10775   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10776     return Expr->getNumOperands();
10777   return 1;
10778 }
10779 
10780 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10781   if (isa<SCEVConstant>(T))
10782     return nullptr;
10783 
10784   if (isa<SCEVUnknown>(T))
10785     return T;
10786 
10787   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10788     SmallVector<const SCEV *, 2> Factors;
10789     for (const SCEV *Op : M->operands())
10790       if (!isa<SCEVConstant>(Op))
10791         Factors.push_back(Op);
10792 
10793     return SE.getMulExpr(Factors);
10794   }
10795 
10796   return T;
10797 }
10798 
10799 /// Return the size of an element read or written by Inst.
10800 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10801   Type *Ty;
10802   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10803     Ty = Store->getValueOperand()->getType();
10804   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10805     Ty = Load->getType();
10806   else
10807     return nullptr;
10808 
10809   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10810   return getSizeOfExpr(ETy, Ty);
10811 }
10812 
10813 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10814                                           SmallVectorImpl<const SCEV *> &Sizes,
10815                                           const SCEV *ElementSize) {
10816   if (Terms.size() < 1 || !ElementSize)
10817     return;
10818 
10819   // Early return when Terms do not contain parameters: we do not delinearize
10820   // non parametric SCEVs.
10821   if (!containsParameters(Terms))
10822     return;
10823 
10824   LLVM_DEBUG({
10825     dbgs() << "Terms:\n";
10826     for (const SCEV *T : Terms)
10827       dbgs() << *T << "\n";
10828   });
10829 
10830   // Remove duplicates.
10831   array_pod_sort(Terms.begin(), Terms.end());
10832   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10833 
10834   // Put larger terms first.
10835   llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10836     return numberOfTerms(LHS) > numberOfTerms(RHS);
10837   });
10838 
10839   // Try to divide all terms by the element size. If term is not divisible by
10840   // element size, proceed with the original term.
10841   for (const SCEV *&Term : Terms) {
10842     const SCEV *Q, *R;
10843     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10844     if (!Q->isZero())
10845       Term = Q;
10846   }
10847 
10848   SmallVector<const SCEV *, 4> NewTerms;
10849 
10850   // Remove constant factors.
10851   for (const SCEV *T : Terms)
10852     if (const SCEV *NewT = removeConstantFactors(*this, T))
10853       NewTerms.push_back(NewT);
10854 
10855   LLVM_DEBUG({
10856     dbgs() << "Terms after sorting:\n";
10857     for (const SCEV *T : NewTerms)
10858       dbgs() << *T << "\n";
10859   });
10860 
10861   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10862     Sizes.clear();
10863     return;
10864   }
10865 
10866   // The last element to be pushed into Sizes is the size of an element.
10867   Sizes.push_back(ElementSize);
10868 
10869   LLVM_DEBUG({
10870     dbgs() << "Sizes:\n";
10871     for (const SCEV *S : Sizes)
10872       dbgs() << *S << "\n";
10873   });
10874 }
10875 
10876 void ScalarEvolution::computeAccessFunctions(
10877     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10878     SmallVectorImpl<const SCEV *> &Sizes) {
10879   // Early exit in case this SCEV is not an affine multivariate function.
10880   if (Sizes.empty())
10881     return;
10882 
10883   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10884     if (!AR->isAffine())
10885       return;
10886 
10887   const SCEV *Res = Expr;
10888   int Last = Sizes.size() - 1;
10889   for (int i = Last; i >= 0; i--) {
10890     const SCEV *Q, *R;
10891     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10892 
10893     LLVM_DEBUG({
10894       dbgs() << "Res: " << *Res << "\n";
10895       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10896       dbgs() << "Res divided by Sizes[i]:\n";
10897       dbgs() << "Quotient: " << *Q << "\n";
10898       dbgs() << "Remainder: " << *R << "\n";
10899     });
10900 
10901     Res = Q;
10902 
10903     // Do not record the last subscript corresponding to the size of elements in
10904     // the array.
10905     if (i == Last) {
10906 
10907       // Bail out if the remainder is too complex.
10908       if (isa<SCEVAddRecExpr>(R)) {
10909         Subscripts.clear();
10910         Sizes.clear();
10911         return;
10912       }
10913 
10914       continue;
10915     }
10916 
10917     // Record the access function for the current subscript.
10918     Subscripts.push_back(R);
10919   }
10920 
10921   // Also push in last position the remainder of the last division: it will be
10922   // the access function of the innermost dimension.
10923   Subscripts.push_back(Res);
10924 
10925   std::reverse(Subscripts.begin(), Subscripts.end());
10926 
10927   LLVM_DEBUG({
10928     dbgs() << "Subscripts:\n";
10929     for (const SCEV *S : Subscripts)
10930       dbgs() << *S << "\n";
10931   });
10932 }
10933 
10934 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10935 /// sizes of an array access. Returns the remainder of the delinearization that
10936 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10937 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10938 /// expressions in the stride and base of a SCEV corresponding to the
10939 /// computation of a GCD (greatest common divisor) of base and stride.  When
10940 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10941 ///
10942 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10943 ///
10944 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10945 ///
10946 ///    for (long i = 0; i < n; i++)
10947 ///      for (long j = 0; j < m; j++)
10948 ///        for (long k = 0; k < o; k++)
10949 ///          A[i][j][k] = 1.0;
10950 ///  }
10951 ///
10952 /// the delinearization input is the following AddRec SCEV:
10953 ///
10954 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10955 ///
10956 /// From this SCEV, we are able to say that the base offset of the access is %A
10957 /// because it appears as an offset that does not divide any of the strides in
10958 /// the loops:
10959 ///
10960 ///  CHECK: Base offset: %A
10961 ///
10962 /// and then SCEV->delinearize determines the size of some of the dimensions of
10963 /// the array as these are the multiples by which the strides are happening:
10964 ///
10965 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10966 ///
10967 /// Note that the outermost dimension remains of UnknownSize because there are
10968 /// no strides that would help identifying the size of the last dimension: when
10969 /// the array has been statically allocated, one could compute the size of that
10970 /// dimension by dividing the overall size of the array by the size of the known
10971 /// dimensions: %m * %o * 8.
10972 ///
10973 /// Finally delinearize provides the access functions for the array reference
10974 /// that does correspond to A[i][j][k] of the above C testcase:
10975 ///
10976 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10977 ///
10978 /// The testcases are checking the output of a function pass:
10979 /// DelinearizationPass that walks through all loads and stores of a function
10980 /// asking for the SCEV of the memory access with respect to all enclosing
10981 /// loops, calling SCEV->delinearize on that and printing the results.
10982 void ScalarEvolution::delinearize(const SCEV *Expr,
10983                                  SmallVectorImpl<const SCEV *> &Subscripts,
10984                                  SmallVectorImpl<const SCEV *> &Sizes,
10985                                  const SCEV *ElementSize) {
10986   // First step: collect parametric terms.
10987   SmallVector<const SCEV *, 4> Terms;
10988   collectParametricTerms(Expr, Terms);
10989 
10990   if (Terms.empty())
10991     return;
10992 
10993   // Second step: find subscript sizes.
10994   findArrayDimensions(Terms, Sizes, ElementSize);
10995 
10996   if (Sizes.empty())
10997     return;
10998 
10999   // Third step: compute the access functions for each subscript.
11000   computeAccessFunctions(Expr, Subscripts, Sizes);
11001 
11002   if (Subscripts.empty())
11003     return;
11004 
11005   LLVM_DEBUG({
11006     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11007     dbgs() << "ArrayDecl[UnknownSize]";
11008     for (const SCEV *S : Sizes)
11009       dbgs() << "[" << *S << "]";
11010 
11011     dbgs() << "\nArrayRef";
11012     for (const SCEV *S : Subscripts)
11013       dbgs() << "[" << *S << "]";
11014     dbgs() << "\n";
11015   });
11016 }
11017 
11018 //===----------------------------------------------------------------------===//
11019 //                   SCEVCallbackVH Class Implementation
11020 //===----------------------------------------------------------------------===//
11021 
11022 void ScalarEvolution::SCEVCallbackVH::deleted() {
11023   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11024   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11025     SE->ConstantEvolutionLoopExitValue.erase(PN);
11026   SE->eraseValueFromMap(getValPtr());
11027   // this now dangles!
11028 }
11029 
11030 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11031   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11032 
11033   // Forget all the expressions associated with users of the old value,
11034   // so that future queries will recompute the expressions using the new
11035   // value.
11036   Value *Old = getValPtr();
11037   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11038   SmallPtrSet<User *, 8> Visited;
11039   while (!Worklist.empty()) {
11040     User *U = Worklist.pop_back_val();
11041     // Deleting the Old value will cause this to dangle. Postpone
11042     // that until everything else is done.
11043     if (U == Old)
11044       continue;
11045     if (!Visited.insert(U).second)
11046       continue;
11047     if (PHINode *PN = dyn_cast<PHINode>(U))
11048       SE->ConstantEvolutionLoopExitValue.erase(PN);
11049     SE->eraseValueFromMap(U);
11050     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11051   }
11052   // Delete the Old value.
11053   if (PHINode *PN = dyn_cast<PHINode>(Old))
11054     SE->ConstantEvolutionLoopExitValue.erase(PN);
11055   SE->eraseValueFromMap(Old);
11056   // this now dangles!
11057 }
11058 
11059 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11060   : CallbackVH(V), SE(se) {}
11061 
11062 //===----------------------------------------------------------------------===//
11063 //                   ScalarEvolution Class Implementation
11064 //===----------------------------------------------------------------------===//
11065 
11066 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11067                                  AssumptionCache &AC, DominatorTree &DT,
11068                                  LoopInfo &LI)
11069     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11070       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11071       LoopDispositions(64), BlockDispositions(64) {
11072   // To use guards for proving predicates, we need to scan every instruction in
11073   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11074   // time if the IR does not actually contain any calls to
11075   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11076   //
11077   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11078   // to _add_ guards to the module when there weren't any before, and wants
11079   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11080   // efficient in lieu of being smart in that rather obscure case.
11081 
11082   auto *GuardDecl = F.getParent()->getFunction(
11083       Intrinsic::getName(Intrinsic::experimental_guard));
11084   HasGuards = GuardDecl && !GuardDecl->use_empty();
11085 }
11086 
11087 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11088     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11089       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11090       ValueExprMap(std::move(Arg.ValueExprMap)),
11091       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11092       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11093       PendingMerges(std::move(Arg.PendingMerges)),
11094       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11095       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11096       PredicatedBackedgeTakenCounts(
11097           std::move(Arg.PredicatedBackedgeTakenCounts)),
11098       ConstantEvolutionLoopExitValue(
11099           std::move(Arg.ConstantEvolutionLoopExitValue)),
11100       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11101       LoopDispositions(std::move(Arg.LoopDispositions)),
11102       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11103       BlockDispositions(std::move(Arg.BlockDispositions)),
11104       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11105       SignedRanges(std::move(Arg.SignedRanges)),
11106       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11107       UniquePreds(std::move(Arg.UniquePreds)),
11108       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11109       LoopUsers(std::move(Arg.LoopUsers)),
11110       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11111       FirstUnknown(Arg.FirstUnknown) {
11112   Arg.FirstUnknown = nullptr;
11113 }
11114 
11115 ScalarEvolution::~ScalarEvolution() {
11116   // Iterate through all the SCEVUnknown instances and call their
11117   // destructors, so that they release their references to their values.
11118   for (SCEVUnknown *U = FirstUnknown; U;) {
11119     SCEVUnknown *Tmp = U;
11120     U = U->Next;
11121     Tmp->~SCEVUnknown();
11122   }
11123   FirstUnknown = nullptr;
11124 
11125   ExprValueMap.clear();
11126   ValueExprMap.clear();
11127   HasRecMap.clear();
11128 
11129   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11130   // that a loop had multiple computable exits.
11131   for (auto &BTCI : BackedgeTakenCounts)
11132     BTCI.second.clear();
11133   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11134     BTCI.second.clear();
11135 
11136   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11137   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11138   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11139   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11140   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11141 }
11142 
11143 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11144   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11145 }
11146 
11147 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11148                           const Loop *L) {
11149   // Print all inner loops first
11150   for (Loop *I : *L)
11151     PrintLoopInfo(OS, SE, I);
11152 
11153   OS << "Loop ";
11154   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11155   OS << ": ";
11156 
11157   SmallVector<BasicBlock *, 8> ExitBlocks;
11158   L->getExitBlocks(ExitBlocks);
11159   if (ExitBlocks.size() != 1)
11160     OS << "<multiple exits> ";
11161 
11162   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11163     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
11164   } else {
11165     OS << "Unpredictable backedge-taken count. ";
11166   }
11167 
11168   OS << "\n"
11169         "Loop ";
11170   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11171   OS << ": ";
11172 
11173   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
11174     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
11175     if (SE->isBackedgeTakenCountMaxOrZero(L))
11176       OS << ", actual taken count either this or zero.";
11177   } else {
11178     OS << "Unpredictable max backedge-taken count. ";
11179   }
11180 
11181   OS << "\n"
11182         "Loop ";
11183   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11184   OS << ": ";
11185 
11186   SCEVUnionPredicate Pred;
11187   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11188   if (!isa<SCEVCouldNotCompute>(PBT)) {
11189     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11190     OS << " Predicates:\n";
11191     Pred.print(OS, 4);
11192   } else {
11193     OS << "Unpredictable predicated backedge-taken count. ";
11194   }
11195   OS << "\n";
11196 
11197   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11198     OS << "Loop ";
11199     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11200     OS << ": ";
11201     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11202   }
11203 }
11204 
11205 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11206   switch (LD) {
11207   case ScalarEvolution::LoopVariant:
11208     return "Variant";
11209   case ScalarEvolution::LoopInvariant:
11210     return "Invariant";
11211   case ScalarEvolution::LoopComputable:
11212     return "Computable";
11213   }
11214   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11215 }
11216 
11217 void ScalarEvolution::print(raw_ostream &OS) const {
11218   // ScalarEvolution's implementation of the print method is to print
11219   // out SCEV values of all instructions that are interesting. Doing
11220   // this potentially causes it to create new SCEV objects though,
11221   // which technically conflicts with the const qualifier. This isn't
11222   // observable from outside the class though, so casting away the
11223   // const isn't dangerous.
11224   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11225 
11226   OS << "Classifying expressions for: ";
11227   F.printAsOperand(OS, /*PrintType=*/false);
11228   OS << "\n";
11229   for (Instruction &I : instructions(F))
11230     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11231       OS << I << '\n';
11232       OS << "  -->  ";
11233       const SCEV *SV = SE.getSCEV(&I);
11234       SV->print(OS);
11235       if (!isa<SCEVCouldNotCompute>(SV)) {
11236         OS << " U: ";
11237         SE.getUnsignedRange(SV).print(OS);
11238         OS << " S: ";
11239         SE.getSignedRange(SV).print(OS);
11240       }
11241 
11242       const Loop *L = LI.getLoopFor(I.getParent());
11243 
11244       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11245       if (AtUse != SV) {
11246         OS << "  -->  ";
11247         AtUse->print(OS);
11248         if (!isa<SCEVCouldNotCompute>(AtUse)) {
11249           OS << " U: ";
11250           SE.getUnsignedRange(AtUse).print(OS);
11251           OS << " S: ";
11252           SE.getSignedRange(AtUse).print(OS);
11253         }
11254       }
11255 
11256       if (L) {
11257         OS << "\t\t" "Exits: ";
11258         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11259         if (!SE.isLoopInvariant(ExitValue, L)) {
11260           OS << "<<Unknown>>";
11261         } else {
11262           OS << *ExitValue;
11263         }
11264 
11265         bool First = true;
11266         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11267           if (First) {
11268             OS << "\t\t" "LoopDispositions: { ";
11269             First = false;
11270           } else {
11271             OS << ", ";
11272           }
11273 
11274           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11275           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11276         }
11277 
11278         for (auto *InnerL : depth_first(L)) {
11279           if (InnerL == L)
11280             continue;
11281           if (First) {
11282             OS << "\t\t" "LoopDispositions: { ";
11283             First = false;
11284           } else {
11285             OS << ", ";
11286           }
11287 
11288           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11289           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11290         }
11291 
11292         OS << " }";
11293       }
11294 
11295       OS << "\n";
11296     }
11297 
11298   OS << "Determining loop execution counts for: ";
11299   F.printAsOperand(OS, /*PrintType=*/false);
11300   OS << "\n";
11301   for (Loop *I : LI)
11302     PrintLoopInfo(OS, &SE, I);
11303 }
11304 
11305 ScalarEvolution::LoopDisposition
11306 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11307   auto &Values = LoopDispositions[S];
11308   for (auto &V : Values) {
11309     if (V.getPointer() == L)
11310       return V.getInt();
11311   }
11312   Values.emplace_back(L, LoopVariant);
11313   LoopDisposition D = computeLoopDisposition(S, L);
11314   auto &Values2 = LoopDispositions[S];
11315   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11316     if (V.getPointer() == L) {
11317       V.setInt(D);
11318       break;
11319     }
11320   }
11321   return D;
11322 }
11323 
11324 ScalarEvolution::LoopDisposition
11325 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11326   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11327   case scConstant:
11328     return LoopInvariant;
11329   case scTruncate:
11330   case scZeroExtend:
11331   case scSignExtend:
11332     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11333   case scAddRecExpr: {
11334     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11335 
11336     // If L is the addrec's loop, it's computable.
11337     if (AR->getLoop() == L)
11338       return LoopComputable;
11339 
11340     // Add recurrences are never invariant in the function-body (null loop).
11341     if (!L)
11342       return LoopVariant;
11343 
11344     // Everything that is not defined at loop entry is variant.
11345     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11346       return LoopVariant;
11347     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11348            " dominate the contained loop's header?");
11349 
11350     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11351     if (AR->getLoop()->contains(L))
11352       return LoopInvariant;
11353 
11354     // This recurrence is variant w.r.t. L if any of its operands
11355     // are variant.
11356     for (auto *Op : AR->operands())
11357       if (!isLoopInvariant(Op, L))
11358         return LoopVariant;
11359 
11360     // Otherwise it's loop-invariant.
11361     return LoopInvariant;
11362   }
11363   case scAddExpr:
11364   case scMulExpr:
11365   case scUMaxExpr:
11366   case scSMaxExpr: {
11367     bool HasVarying = false;
11368     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11369       LoopDisposition D = getLoopDisposition(Op, L);
11370       if (D == LoopVariant)
11371         return LoopVariant;
11372       if (D == LoopComputable)
11373         HasVarying = true;
11374     }
11375     return HasVarying ? LoopComputable : LoopInvariant;
11376   }
11377   case scUDivExpr: {
11378     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11379     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11380     if (LD == LoopVariant)
11381       return LoopVariant;
11382     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11383     if (RD == LoopVariant)
11384       return LoopVariant;
11385     return (LD == LoopInvariant && RD == LoopInvariant) ?
11386            LoopInvariant : LoopComputable;
11387   }
11388   case scUnknown:
11389     // All non-instruction values are loop invariant.  All instructions are loop
11390     // invariant if they are not contained in the specified loop.
11391     // Instructions are never considered invariant in the function body
11392     // (null loop) because they are defined within the "loop".
11393     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11394       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11395     return LoopInvariant;
11396   case scCouldNotCompute:
11397     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11398   }
11399   llvm_unreachable("Unknown SCEV kind!");
11400 }
11401 
11402 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11403   return getLoopDisposition(S, L) == LoopInvariant;
11404 }
11405 
11406 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11407   return getLoopDisposition(S, L) == LoopComputable;
11408 }
11409 
11410 ScalarEvolution::BlockDisposition
11411 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11412   auto &Values = BlockDispositions[S];
11413   for (auto &V : Values) {
11414     if (V.getPointer() == BB)
11415       return V.getInt();
11416   }
11417   Values.emplace_back(BB, DoesNotDominateBlock);
11418   BlockDisposition D = computeBlockDisposition(S, BB);
11419   auto &Values2 = BlockDispositions[S];
11420   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11421     if (V.getPointer() == BB) {
11422       V.setInt(D);
11423       break;
11424     }
11425   }
11426   return D;
11427 }
11428 
11429 ScalarEvolution::BlockDisposition
11430 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11431   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11432   case scConstant:
11433     return ProperlyDominatesBlock;
11434   case scTruncate:
11435   case scZeroExtend:
11436   case scSignExtend:
11437     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11438   case scAddRecExpr: {
11439     // This uses a "dominates" query instead of "properly dominates" query
11440     // to test for proper dominance too, because the instruction which
11441     // produces the addrec's value is a PHI, and a PHI effectively properly
11442     // dominates its entire containing block.
11443     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11444     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11445       return DoesNotDominateBlock;
11446 
11447     // Fall through into SCEVNAryExpr handling.
11448     LLVM_FALLTHROUGH;
11449   }
11450   case scAddExpr:
11451   case scMulExpr:
11452   case scUMaxExpr:
11453   case scSMaxExpr: {
11454     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11455     bool Proper = true;
11456     for (const SCEV *NAryOp : NAry->operands()) {
11457       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11458       if (D == DoesNotDominateBlock)
11459         return DoesNotDominateBlock;
11460       if (D == DominatesBlock)
11461         Proper = false;
11462     }
11463     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11464   }
11465   case scUDivExpr: {
11466     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11467     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11468     BlockDisposition LD = getBlockDisposition(LHS, BB);
11469     if (LD == DoesNotDominateBlock)
11470       return DoesNotDominateBlock;
11471     BlockDisposition RD = getBlockDisposition(RHS, BB);
11472     if (RD == DoesNotDominateBlock)
11473       return DoesNotDominateBlock;
11474     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11475       ProperlyDominatesBlock : DominatesBlock;
11476   }
11477   case scUnknown:
11478     if (Instruction *I =
11479           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11480       if (I->getParent() == BB)
11481         return DominatesBlock;
11482       if (DT.properlyDominates(I->getParent(), BB))
11483         return ProperlyDominatesBlock;
11484       return DoesNotDominateBlock;
11485     }
11486     return ProperlyDominatesBlock;
11487   case scCouldNotCompute:
11488     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11489   }
11490   llvm_unreachable("Unknown SCEV kind!");
11491 }
11492 
11493 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11494   return getBlockDisposition(S, BB) >= DominatesBlock;
11495 }
11496 
11497 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11498   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11499 }
11500 
11501 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11502   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11503 }
11504 
11505 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11506   auto IsS = [&](const SCEV *X) { return S == X; };
11507   auto ContainsS = [&](const SCEV *X) {
11508     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11509   };
11510   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11511 }
11512 
11513 void
11514 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11515   ValuesAtScopes.erase(S);
11516   LoopDispositions.erase(S);
11517   BlockDispositions.erase(S);
11518   UnsignedRanges.erase(S);
11519   SignedRanges.erase(S);
11520   ExprValueMap.erase(S);
11521   HasRecMap.erase(S);
11522   MinTrailingZerosCache.erase(S);
11523 
11524   for (auto I = PredicatedSCEVRewrites.begin();
11525        I != PredicatedSCEVRewrites.end();) {
11526     std::pair<const SCEV *, const Loop *> Entry = I->first;
11527     if (Entry.first == S)
11528       PredicatedSCEVRewrites.erase(I++);
11529     else
11530       ++I;
11531   }
11532 
11533   auto RemoveSCEVFromBackedgeMap =
11534       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11535         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11536           BackedgeTakenInfo &BEInfo = I->second;
11537           if (BEInfo.hasOperand(S, this)) {
11538             BEInfo.clear();
11539             Map.erase(I++);
11540           } else
11541             ++I;
11542         }
11543       };
11544 
11545   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11546   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11547 }
11548 
11549 void
11550 ScalarEvolution::getUsedLoops(const SCEV *S,
11551                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11552   struct FindUsedLoops {
11553     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11554         : LoopsUsed(LoopsUsed) {}
11555     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11556     bool follow(const SCEV *S) {
11557       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11558         LoopsUsed.insert(AR->getLoop());
11559       return true;
11560     }
11561 
11562     bool isDone() const { return false; }
11563   };
11564 
11565   FindUsedLoops F(LoopsUsed);
11566   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11567 }
11568 
11569 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11570   SmallPtrSet<const Loop *, 8> LoopsUsed;
11571   getUsedLoops(S, LoopsUsed);
11572   for (auto *L : LoopsUsed)
11573     LoopUsers[L].push_back(S);
11574 }
11575 
11576 void ScalarEvolution::verify() const {
11577   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11578   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11579 
11580   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11581 
11582   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11583   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11584     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11585 
11586     const SCEV *visitConstant(const SCEVConstant *Constant) {
11587       return SE.getConstant(Constant->getAPInt());
11588     }
11589 
11590     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11591       return SE.getUnknown(Expr->getValue());
11592     }
11593 
11594     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11595       return SE.getCouldNotCompute();
11596     }
11597   };
11598 
11599   SCEVMapper SCM(SE2);
11600 
11601   while (!LoopStack.empty()) {
11602     auto *L = LoopStack.pop_back_val();
11603     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11604 
11605     auto *CurBECount = SCM.visit(
11606         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11607     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11608 
11609     if (CurBECount == SE2.getCouldNotCompute() ||
11610         NewBECount == SE2.getCouldNotCompute()) {
11611       // NB! This situation is legal, but is very suspicious -- whatever pass
11612       // change the loop to make a trip count go from could not compute to
11613       // computable or vice-versa *should have* invalidated SCEV.  However, we
11614       // choose not to assert here (for now) since we don't want false
11615       // positives.
11616       continue;
11617     }
11618 
11619     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11620       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11621       // not propagate undef aggressively).  This means we can (and do) fail
11622       // verification in cases where a transform makes the trip count of a loop
11623       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11624       // both cases the loop iterates "undef" times, but SCEV thinks we
11625       // increased the trip count of the loop by 1 incorrectly.
11626       continue;
11627     }
11628 
11629     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11630         SE.getTypeSizeInBits(NewBECount->getType()))
11631       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11632     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11633              SE.getTypeSizeInBits(NewBECount->getType()))
11634       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11635 
11636     auto *ConstantDelta =
11637         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11638 
11639     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11640       dbgs() << "Trip Count Changed!\n";
11641       dbgs() << "Old: " << *CurBECount << "\n";
11642       dbgs() << "New: " << *NewBECount << "\n";
11643       dbgs() << "Delta: " << *ConstantDelta << "\n";
11644       std::abort();
11645     }
11646   }
11647 }
11648 
11649 bool ScalarEvolution::invalidate(
11650     Function &F, const PreservedAnalyses &PA,
11651     FunctionAnalysisManager::Invalidator &Inv) {
11652   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11653   // of its dependencies is invalidated.
11654   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11655   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11656          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11657          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11658          Inv.invalidate<LoopAnalysis>(F, PA);
11659 }
11660 
11661 AnalysisKey ScalarEvolutionAnalysis::Key;
11662 
11663 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11664                                              FunctionAnalysisManager &AM) {
11665   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11666                          AM.getResult<AssumptionAnalysis>(F),
11667                          AM.getResult<DominatorTreeAnalysis>(F),
11668                          AM.getResult<LoopAnalysis>(F));
11669 }
11670 
11671 PreservedAnalyses
11672 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11673   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11674   return PreservedAnalyses::all();
11675 }
11676 
11677 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11678                       "Scalar Evolution Analysis", false, true)
11679 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11680 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11681 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11682 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11683 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11684                     "Scalar Evolution Analysis", false, true)
11685 
11686 char ScalarEvolutionWrapperPass::ID = 0;
11687 
11688 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11689   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11690 }
11691 
11692 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11693   SE.reset(new ScalarEvolution(
11694       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11695       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11696       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11697       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11698   return false;
11699 }
11700 
11701 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11702 
11703 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11704   SE->print(OS);
11705 }
11706 
11707 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11708   if (!VerifySCEV)
11709     return;
11710 
11711   SE->verify();
11712 }
11713 
11714 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11715   AU.setPreservesAll();
11716   AU.addRequiredTransitive<AssumptionCacheTracker>();
11717   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11718   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11719   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11720 }
11721 
11722 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11723                                                         const SCEV *RHS) {
11724   FoldingSetNodeID ID;
11725   assert(LHS->getType() == RHS->getType() &&
11726          "Type mismatch between LHS and RHS");
11727   // Unique this node based on the arguments
11728   ID.AddInteger(SCEVPredicate::P_Equal);
11729   ID.AddPointer(LHS);
11730   ID.AddPointer(RHS);
11731   void *IP = nullptr;
11732   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11733     return S;
11734   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11735       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11736   UniquePreds.InsertNode(Eq, IP);
11737   return Eq;
11738 }
11739 
11740 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11741     const SCEVAddRecExpr *AR,
11742     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11743   FoldingSetNodeID ID;
11744   // Unique this node based on the arguments
11745   ID.AddInteger(SCEVPredicate::P_Wrap);
11746   ID.AddPointer(AR);
11747   ID.AddInteger(AddedFlags);
11748   void *IP = nullptr;
11749   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11750     return S;
11751   auto *OF = new (SCEVAllocator)
11752       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11753   UniquePreds.InsertNode(OF, IP);
11754   return OF;
11755 }
11756 
11757 namespace {
11758 
11759 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11760 public:
11761 
11762   /// Rewrites \p S in the context of a loop L and the SCEV predication
11763   /// infrastructure.
11764   ///
11765   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11766   /// equivalences present in \p Pred.
11767   ///
11768   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11769   /// \p NewPreds such that the result will be an AddRecExpr.
11770   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11771                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11772                              SCEVUnionPredicate *Pred) {
11773     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11774     return Rewriter.visit(S);
11775   }
11776 
11777   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11778     if (Pred) {
11779       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11780       for (auto *Pred : ExprPreds)
11781         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11782           if (IPred->getLHS() == Expr)
11783             return IPred->getRHS();
11784     }
11785     return convertToAddRecWithPreds(Expr);
11786   }
11787 
11788   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11789     const SCEV *Operand = visit(Expr->getOperand());
11790     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11791     if (AR && AR->getLoop() == L && AR->isAffine()) {
11792       // This couldn't be folded because the operand didn't have the nuw
11793       // flag. Add the nusw flag as an assumption that we could make.
11794       const SCEV *Step = AR->getStepRecurrence(SE);
11795       Type *Ty = Expr->getType();
11796       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11797         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11798                                 SE.getSignExtendExpr(Step, Ty), L,
11799                                 AR->getNoWrapFlags());
11800     }
11801     return SE.getZeroExtendExpr(Operand, Expr->getType());
11802   }
11803 
11804   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11805     const SCEV *Operand = visit(Expr->getOperand());
11806     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11807     if (AR && AR->getLoop() == L && AR->isAffine()) {
11808       // This couldn't be folded because the operand didn't have the nsw
11809       // flag. Add the nssw flag as an assumption that we could make.
11810       const SCEV *Step = AR->getStepRecurrence(SE);
11811       Type *Ty = Expr->getType();
11812       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11813         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11814                                 SE.getSignExtendExpr(Step, Ty), L,
11815                                 AR->getNoWrapFlags());
11816     }
11817     return SE.getSignExtendExpr(Operand, Expr->getType());
11818   }
11819 
11820 private:
11821   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11822                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11823                         SCEVUnionPredicate *Pred)
11824       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11825 
11826   bool addOverflowAssumption(const SCEVPredicate *P) {
11827     if (!NewPreds) {
11828       // Check if we've already made this assumption.
11829       return Pred && Pred->implies(P);
11830     }
11831     NewPreds->insert(P);
11832     return true;
11833   }
11834 
11835   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11836                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11837     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11838     return addOverflowAssumption(A);
11839   }
11840 
11841   // If \p Expr represents a PHINode, we try to see if it can be represented
11842   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11843   // to add this predicate as a runtime overflow check, we return the AddRec.
11844   // If \p Expr does not meet these conditions (is not a PHI node, or we
11845   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11846   // return \p Expr.
11847   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11848     if (!isa<PHINode>(Expr->getValue()))
11849       return Expr;
11850     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11851     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11852     if (!PredicatedRewrite)
11853       return Expr;
11854     for (auto *P : PredicatedRewrite->second){
11855       // Wrap predicates from outer loops are not supported.
11856       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
11857         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
11858         if (L != AR->getLoop())
11859           return Expr;
11860       }
11861       if (!addOverflowAssumption(P))
11862         return Expr;
11863     }
11864     return PredicatedRewrite->first;
11865   }
11866 
11867   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11868   SCEVUnionPredicate *Pred;
11869   const Loop *L;
11870 };
11871 
11872 } // end anonymous namespace
11873 
11874 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11875                                                    SCEVUnionPredicate &Preds) {
11876   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11877 }
11878 
11879 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11880     const SCEV *S, const Loop *L,
11881     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11882   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11883   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11884   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11885 
11886   if (!AddRec)
11887     return nullptr;
11888 
11889   // Since the transformation was successful, we can now transfer the SCEV
11890   // predicates.
11891   for (auto *P : TransformPreds)
11892     Preds.insert(P);
11893 
11894   return AddRec;
11895 }
11896 
11897 /// SCEV predicates
11898 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11899                              SCEVPredicateKind Kind)
11900     : FastID(ID), Kind(Kind) {}
11901 
11902 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11903                                        const SCEV *LHS, const SCEV *RHS)
11904     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11905   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11906   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11907 }
11908 
11909 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11910   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11911 
11912   if (!Op)
11913     return false;
11914 
11915   return Op->LHS == LHS && Op->RHS == RHS;
11916 }
11917 
11918 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11919 
11920 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11921 
11922 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11923   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11924 }
11925 
11926 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11927                                      const SCEVAddRecExpr *AR,
11928                                      IncrementWrapFlags Flags)
11929     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11930 
11931 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11932 
11933 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11934   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11935 
11936   return Op && Op->AR == AR && (Flags | Op->Flags) == Flags;
11937 }
11938 
11939 bool SCEVWrapPredicate::isAlwaysTrue() const {
11940   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11941   IncrementWrapFlags IFlags = Flags;
11942 
11943   if ((ScevFlags | SCEV::FlagNSW) == ScevFlags)
11944     IFlags &= ~IncrementNSSW;
11945 
11946   return IFlags == IncrementAnyWrap;
11947 }
11948 
11949 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11950   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11951   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11952     OS << "<nusw>";
11953   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11954     OS << "<nssw>";
11955   OS << "\n";
11956 }
11957 
11958 SCEVWrapPredicate::IncrementWrapFlags
11959 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11960                                    ScalarEvolution &SE) {
11961   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11962   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11963 
11964   // We can safely transfer the NSW flag as NSSW.
11965   if ((StaticFlags | SCEV::FlagNSW) == StaticFlags)
11966     ImpliedFlags = IncrementNSSW;
11967 
11968   if ((StaticFlags | SCEV::FlagNUW) == StaticFlags) {
11969     // If the increment is positive, the SCEV NUW flag will also imply the
11970     // WrapPredicate NUSW flag.
11971     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11972       if (Step->getValue()->getValue().isNonNegative())
11973         ImpliedFlags |= IncrementNUSW;
11974   }
11975 
11976   return ImpliedFlags;
11977 }
11978 
11979 /// Union predicates don't get cached so create a dummy set ID for it.
11980 SCEVUnionPredicate::SCEVUnionPredicate()
11981     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11982 
11983 bool SCEVUnionPredicate::isAlwaysTrue() const {
11984   return all_of(Preds,
11985                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11986 }
11987 
11988 ArrayRef<const SCEVPredicate *>
11989 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11990   auto I = SCEVToPreds.find(Expr);
11991   if (I == SCEVToPreds.end())
11992     return ArrayRef<const SCEVPredicate *>();
11993   return I->second;
11994 }
11995 
11996 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11997   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11998     return all_of(Set->Preds,
11999                   [this](const SCEVPredicate *I) { return this->implies(I); });
12000 
12001   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12002   if (ScevPredsIt == SCEVToPreds.end())
12003     return false;
12004   auto &SCEVPreds = ScevPredsIt->second;
12005 
12006   return any_of(SCEVPreds,
12007                 [N](const SCEVPredicate *I) { return I->implies(N); });
12008 }
12009 
12010 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12011 
12012 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12013   for (auto Pred : Preds)
12014     Pred->print(OS, Depth);
12015 }
12016 
12017 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12018   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12019     for (auto Pred : Set->Preds)
12020       add(Pred);
12021     return;
12022   }
12023 
12024   if (implies(N))
12025     return;
12026 
12027   const SCEV *Key = N->getExpr();
12028   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12029                 " associated expression!");
12030 
12031   SCEVToPreds[Key].push_back(N);
12032   Preds.push_back(N);
12033 }
12034 
12035 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12036                                                      Loop &L)
12037     : SE(SE), L(L) {}
12038 
12039 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12040   const SCEV *Expr = SE.getSCEV(V);
12041   RewriteEntry &Entry = RewriteMap[Expr];
12042 
12043   // If we already have an entry and the version matches, return it.
12044   if (Entry.second && Generation == Entry.first)
12045     return Entry.second;
12046 
12047   // We found an entry but it's stale. Rewrite the stale entry
12048   // according to the current predicate.
12049   if (Entry.second)
12050     Expr = Entry.second;
12051 
12052   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12053   Entry = {Generation, NewSCEV};
12054 
12055   return NewSCEV;
12056 }
12057 
12058 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12059   if (!BackedgeCount) {
12060     SCEVUnionPredicate BackedgePred;
12061     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12062     addPredicate(BackedgePred);
12063   }
12064   return BackedgeCount;
12065 }
12066 
12067 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12068   if (Preds.implies(&Pred))
12069     return;
12070   Preds.add(&Pred);
12071   updateGeneration();
12072 }
12073 
12074 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12075   return Preds;
12076 }
12077 
12078 void PredicatedScalarEvolution::updateGeneration() {
12079   // If the generation number wrapped recompute everything.
12080   if (++Generation == 0) {
12081     for (auto &II : RewriteMap) {
12082       const SCEV *Rewritten = II.second.second;
12083       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12084     }
12085   }
12086 }
12087 
12088 void PredicatedScalarEvolution::setNoOverflow(
12089     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12090   const SCEV *Expr = getSCEV(V);
12091   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12092 
12093   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12094 
12095   // Clear the statically implied flags.
12096   Flags &= ~ImpliedFlags;
12097   addPredicate(*SE.getWrapPredicate(AR, Flags));
12098 
12099   auto II = FlagsMap.insert({V, Flags});
12100   if (!II.second)
12101     II.first->second |= Flags;
12102 }
12103 
12104 bool PredicatedScalarEvolution::hasNoOverflow(
12105     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12106   const SCEV *Expr = getSCEV(V);
12107   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12108 
12109   Flags &= ~SCEVWrapPredicate::getImpliedFlags(AR, SE);
12110 
12111   auto II = FlagsMap.find(V);
12112 
12113   if (II != FlagsMap.end())
12114     Flags &= ~II->second;
12115 
12116   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12117 }
12118 
12119 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12120   const SCEV *Expr = this->getSCEV(V);
12121   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12122   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12123 
12124   if (!New)
12125     return nullptr;
12126 
12127   for (auto *P : NewPreds)
12128     Preds.add(P);
12129 
12130   updateGeneration();
12131   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12132   return New;
12133 }
12134 
12135 PredicatedScalarEvolution::PredicatedScalarEvolution(
12136     const PredicatedScalarEvolution &Init)
12137     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12138       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12139   for (const auto &I : Init.FlagsMap)
12140     FlagsMap.insert(I);
12141 }
12142 
12143 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12144   // For each block.
12145   for (auto *BB : L.getBlocks())
12146     for (auto &I : *BB) {
12147       if (!SE.isSCEVable(I.getType()))
12148         continue;
12149 
12150       auto *Expr = SE.getSCEV(&I);
12151       auto II = RewriteMap.find(Expr);
12152 
12153       if (II == RewriteMap.end())
12154         continue;
12155 
12156       // Don't print things that are not interesting.
12157       if (II->second.second == Expr)
12158         continue;
12159 
12160       OS.indent(Depth) << "[PSE]" << I << ":\n";
12161       OS.indent(Depth + 2) << *Expr << "\n";
12162       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12163     }
12164 }
12165