xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 05da2fe52162c80dfa18aedf70cf73cb11201811)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/Config/llvm-config.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/InitializePasses.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/KnownBits.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <climits>
128 #include <cstddef>
129 #include <cstdint>
130 #include <cstdlib>
131 #include <map>
132 #include <memory>
133 #include <tuple>
134 #include <utility>
135 #include <vector>
136 
137 using namespace llvm;
138 
139 #define DEBUG_TYPE "scalar-evolution"
140 
141 STATISTIC(NumArrayLenItCounts,
142           "Number of trip counts computed with array length");
143 STATISTIC(NumTripCountsComputed,
144           "Number of loops with predictable loop counts");
145 STATISTIC(NumTripCountsNotComputed,
146           "Number of loops without predictable loop counts");
147 STATISTIC(NumBruteForceTripCountsComputed,
148           "Number of loops with trip counts computed by force");
149 
150 static cl::opt<unsigned>
151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
152                         cl::ZeroOrMore,
153                         cl::desc("Maximum number of iterations SCEV will "
154                                  "symbolically execute a constant "
155                                  "derived loop"),
156                         cl::init(100));
157 
158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
159 static cl::opt<bool> VerifySCEV(
160     "verify-scev", cl::Hidden,
161     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163     "verify-scev-strict", cl::Hidden,
164     cl::desc("Enable stricter verification with -verify-scev is passed"));
165 static cl::opt<bool>
166     VerifySCEVMap("verify-scev-maps", cl::Hidden,
167                   cl::desc("Verify no dangling value in ScalarEvolution's "
168                            "ExprValueMap (slow)"));
169 
170 static cl::opt<bool> VerifyIR(
171     "scev-verify-ir", cl::Hidden,
172     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
173     cl::init(false));
174 
175 static cl::opt<unsigned> MulOpsInlineThreshold(
176     "scev-mulops-inline-threshold", cl::Hidden,
177     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> AddOpsInlineThreshold(
181     "scev-addops-inline-threshold", cl::Hidden,
182     cl::desc("Threshold for inlining addition operands into a SCEV"),
183     cl::init(500));
184 
185 static cl::opt<unsigned> MaxSCEVCompareDepth(
186     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
188     cl::init(32));
189 
190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
191     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
192     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
193     cl::init(2));
194 
195 static cl::opt<unsigned> MaxValueCompareDepth(
196     "scalar-evolution-max-value-compare-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive value complexity comparisons"),
198     cl::init(2));
199 
200 static cl::opt<unsigned>
201     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
202                   cl::desc("Maximum depth of recursive arithmetics"),
203                   cl::init(32));
204 
205 static cl::opt<unsigned> MaxConstantEvolvingDepth(
206     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
207     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208 
209 static cl::opt<unsigned>
210     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
211                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
212                  cl::init(8));
213 
214 static cl::opt<unsigned>
215     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
216                   cl::desc("Max coefficients in AddRec during evolving"),
217                   cl::init(8));
218 
219 static cl::opt<unsigned>
220     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
221                   cl::desc("Size of the expression which is considered huge"),
222                   cl::init(4096));
223 
224 //===----------------------------------------------------------------------===//
225 //                           SCEV class definitions
226 //===----------------------------------------------------------------------===//
227 
228 //===----------------------------------------------------------------------===//
229 // Implementation of the SCEV class.
230 //
231 
232 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
233 LLVM_DUMP_METHOD void SCEV::dump() const {
234   print(dbgs());
235   dbgs() << '\n';
236 }
237 #endif
238 
239 void SCEV::print(raw_ostream &OS) const {
240   switch (static_cast<SCEVTypes>(getSCEVType())) {
241   case scConstant:
242     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
243     return;
244   case scTruncate: {
245     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
246     const SCEV *Op = Trunc->getOperand();
247     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
248        << *Trunc->getType() << ")";
249     return;
250   }
251   case scZeroExtend: {
252     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
253     const SCEV *Op = ZExt->getOperand();
254     OS << "(zext " << *Op->getType() << " " << *Op << " to "
255        << *ZExt->getType() << ")";
256     return;
257   }
258   case scSignExtend: {
259     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
260     const SCEV *Op = SExt->getOperand();
261     OS << "(sext " << *Op->getType() << " " << *Op << " to "
262        << *SExt->getType() << ")";
263     return;
264   }
265   case scAddRecExpr: {
266     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
267     OS << "{" << *AR->getOperand(0);
268     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
269       OS << ",+," << *AR->getOperand(i);
270     OS << "}<";
271     if (AR->hasNoUnsignedWrap())
272       OS << "nuw><";
273     if (AR->hasNoSignedWrap())
274       OS << "nsw><";
275     if (AR->hasNoSelfWrap() &&
276         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
277       OS << "nw><";
278     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
279     OS << ">";
280     return;
281   }
282   case scAddExpr:
283   case scMulExpr:
284   case scUMaxExpr:
285   case scSMaxExpr:
286   case scUMinExpr:
287   case scSMinExpr: {
288     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
289     const char *OpStr = nullptr;
290     switch (NAry->getSCEVType()) {
291     case scAddExpr: OpStr = " + "; break;
292     case scMulExpr: OpStr = " * "; break;
293     case scUMaxExpr: OpStr = " umax "; break;
294     case scSMaxExpr: OpStr = " smax "; break;
295     case scUMinExpr:
296       OpStr = " umin ";
297       break;
298     case scSMinExpr:
299       OpStr = " smin ";
300       break;
301     }
302     OS << "(";
303     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
304          I != E; ++I) {
305       OS << **I;
306       if (std::next(I) != E)
307         OS << OpStr;
308     }
309     OS << ")";
310     switch (NAry->getSCEVType()) {
311     case scAddExpr:
312     case scMulExpr:
313       if (NAry->hasNoUnsignedWrap())
314         OS << "<nuw>";
315       if (NAry->hasNoSignedWrap())
316         OS << "<nsw>";
317     }
318     return;
319   }
320   case scUDivExpr: {
321     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
322     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
323     return;
324   }
325   case scUnknown: {
326     const SCEVUnknown *U = cast<SCEVUnknown>(this);
327     Type *AllocTy;
328     if (U->isSizeOf(AllocTy)) {
329       OS << "sizeof(" << *AllocTy << ")";
330       return;
331     }
332     if (U->isAlignOf(AllocTy)) {
333       OS << "alignof(" << *AllocTy << ")";
334       return;
335     }
336 
337     Type *CTy;
338     Constant *FieldNo;
339     if (U->isOffsetOf(CTy, FieldNo)) {
340       OS << "offsetof(" << *CTy << ", ";
341       FieldNo->printAsOperand(OS, false);
342       OS << ")";
343       return;
344     }
345 
346     // Otherwise just print it normally.
347     U->getValue()->printAsOperand(OS, false);
348     return;
349   }
350   case scCouldNotCompute:
351     OS << "***COULDNOTCOMPUTE***";
352     return;
353   }
354   llvm_unreachable("Unknown SCEV kind!");
355 }
356 
357 Type *SCEV::getType() const {
358   switch (static_cast<SCEVTypes>(getSCEVType())) {
359   case scConstant:
360     return cast<SCEVConstant>(this)->getType();
361   case scTruncate:
362   case scZeroExtend:
363   case scSignExtend:
364     return cast<SCEVCastExpr>(this)->getType();
365   case scAddRecExpr:
366   case scMulExpr:
367   case scUMaxExpr:
368   case scSMaxExpr:
369   case scUMinExpr:
370   case scSMinExpr:
371     return cast<SCEVNAryExpr>(this)->getType();
372   case scAddExpr:
373     return cast<SCEVAddExpr>(this)->getType();
374   case scUDivExpr:
375     return cast<SCEVUDivExpr>(this)->getType();
376   case scUnknown:
377     return cast<SCEVUnknown>(this)->getType();
378   case scCouldNotCompute:
379     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
380   }
381   llvm_unreachable("Unknown SCEV kind!");
382 }
383 
384 bool SCEV::isZero() const {
385   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
386     return SC->getValue()->isZero();
387   return false;
388 }
389 
390 bool SCEV::isOne() const {
391   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
392     return SC->getValue()->isOne();
393   return false;
394 }
395 
396 bool SCEV::isAllOnesValue() const {
397   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
398     return SC->getValue()->isMinusOne();
399   return false;
400 }
401 
402 bool SCEV::isNonConstantNegative() const {
403   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
404   if (!Mul) return false;
405 
406   // If there is a constant factor, it will be first.
407   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
408   if (!SC) return false;
409 
410   // Return true if the value is negative, this matches things like (-42 * V).
411   return SC->getAPInt().isNegative();
412 }
413 
414 SCEVCouldNotCompute::SCEVCouldNotCompute() :
415   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
416 
417 bool SCEVCouldNotCompute::classof(const SCEV *S) {
418   return S->getSCEVType() == scCouldNotCompute;
419 }
420 
421 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
422   FoldingSetNodeID ID;
423   ID.AddInteger(scConstant);
424   ID.AddPointer(V);
425   void *IP = nullptr;
426   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
427   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
428   UniqueSCEVs.InsertNode(S, IP);
429   return S;
430 }
431 
432 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
433   return getConstant(ConstantInt::get(getContext(), Val));
434 }
435 
436 const SCEV *
437 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
438   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
439   return getConstant(ConstantInt::get(ITy, V, isSigned));
440 }
441 
442 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
443                            unsigned SCEVTy, const SCEV *op, Type *ty)
444   : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
445 
446 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
447                                    const SCEV *op, Type *ty)
448   : SCEVCastExpr(ID, scTruncate, op, ty) {
449   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
450          "Cannot truncate non-integer value!");
451 }
452 
453 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
454                                        const SCEV *op, Type *ty)
455   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
456   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
457          "Cannot zero extend non-integer value!");
458 }
459 
460 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
461                                        const SCEV *op, Type *ty)
462   : SCEVCastExpr(ID, scSignExtend, op, ty) {
463   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
464          "Cannot sign extend non-integer value!");
465 }
466 
467 void SCEVUnknown::deleted() {
468   // Clear this SCEVUnknown from various maps.
469   SE->forgetMemoizedResults(this);
470 
471   // Remove this SCEVUnknown from the uniquing map.
472   SE->UniqueSCEVs.RemoveNode(this);
473 
474   // Release the value.
475   setValPtr(nullptr);
476 }
477 
478 void SCEVUnknown::allUsesReplacedWith(Value *New) {
479   // Remove this SCEVUnknown from the uniquing map.
480   SE->UniqueSCEVs.RemoveNode(this);
481 
482   // Update this SCEVUnknown to point to the new value. This is needed
483   // because there may still be outstanding SCEVs which still point to
484   // this SCEVUnknown.
485   setValPtr(New);
486 }
487 
488 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
489   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
490     if (VCE->getOpcode() == Instruction::PtrToInt)
491       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
492         if (CE->getOpcode() == Instruction::GetElementPtr &&
493             CE->getOperand(0)->isNullValue() &&
494             CE->getNumOperands() == 2)
495           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
496             if (CI->isOne()) {
497               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
498                                  ->getElementType();
499               return true;
500             }
501 
502   return false;
503 }
504 
505 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
506   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
507     if (VCE->getOpcode() == Instruction::PtrToInt)
508       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
509         if (CE->getOpcode() == Instruction::GetElementPtr &&
510             CE->getOperand(0)->isNullValue()) {
511           Type *Ty =
512             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
513           if (StructType *STy = dyn_cast<StructType>(Ty))
514             if (!STy->isPacked() &&
515                 CE->getNumOperands() == 3 &&
516                 CE->getOperand(1)->isNullValue()) {
517               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
518                 if (CI->isOne() &&
519                     STy->getNumElements() == 2 &&
520                     STy->getElementType(0)->isIntegerTy(1)) {
521                   AllocTy = STy->getElementType(1);
522                   return true;
523                 }
524             }
525         }
526 
527   return false;
528 }
529 
530 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
531   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
532     if (VCE->getOpcode() == Instruction::PtrToInt)
533       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
534         if (CE->getOpcode() == Instruction::GetElementPtr &&
535             CE->getNumOperands() == 3 &&
536             CE->getOperand(0)->isNullValue() &&
537             CE->getOperand(1)->isNullValue()) {
538           Type *Ty =
539             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
540           // Ignore vector types here so that ScalarEvolutionExpander doesn't
541           // emit getelementptrs that index into vectors.
542           if (Ty->isStructTy() || Ty->isArrayTy()) {
543             CTy = Ty;
544             FieldNo = CE->getOperand(2);
545             return true;
546           }
547         }
548 
549   return false;
550 }
551 
552 //===----------------------------------------------------------------------===//
553 //                               SCEV Utilities
554 //===----------------------------------------------------------------------===//
555 
556 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
557 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
558 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
559 /// have been previously deemed to be "equally complex" by this routine.  It is
560 /// intended to avoid exponential time complexity in cases like:
561 ///
562 ///   %a = f(%x, %y)
563 ///   %b = f(%a, %a)
564 ///   %c = f(%b, %b)
565 ///
566 ///   %d = f(%x, %y)
567 ///   %e = f(%d, %d)
568 ///   %f = f(%e, %e)
569 ///
570 ///   CompareValueComplexity(%f, %c)
571 ///
572 /// Since we do not continue running this routine on expression trees once we
573 /// have seen unequal values, there is no need to track them in the cache.
574 static int
575 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
576                        const LoopInfo *const LI, Value *LV, Value *RV,
577                        unsigned Depth) {
578   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
579     return 0;
580 
581   // Order pointer values after integer values. This helps SCEVExpander form
582   // GEPs.
583   bool LIsPointer = LV->getType()->isPointerTy(),
584        RIsPointer = RV->getType()->isPointerTy();
585   if (LIsPointer != RIsPointer)
586     return (int)LIsPointer - (int)RIsPointer;
587 
588   // Compare getValueID values.
589   unsigned LID = LV->getValueID(), RID = RV->getValueID();
590   if (LID != RID)
591     return (int)LID - (int)RID;
592 
593   // Sort arguments by their position.
594   if (const auto *LA = dyn_cast<Argument>(LV)) {
595     const auto *RA = cast<Argument>(RV);
596     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
597     return (int)LArgNo - (int)RArgNo;
598   }
599 
600   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
601     const auto *RGV = cast<GlobalValue>(RV);
602 
603     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
604       auto LT = GV->getLinkage();
605       return !(GlobalValue::isPrivateLinkage(LT) ||
606                GlobalValue::isInternalLinkage(LT));
607     };
608 
609     // Use the names to distinguish the two values, but only if the
610     // names are semantically important.
611     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
612       return LGV->getName().compare(RGV->getName());
613   }
614 
615   // For instructions, compare their loop depth, and their operand count.  This
616   // is pretty loose.
617   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
618     const auto *RInst = cast<Instruction>(RV);
619 
620     // Compare loop depths.
621     const BasicBlock *LParent = LInst->getParent(),
622                      *RParent = RInst->getParent();
623     if (LParent != RParent) {
624       unsigned LDepth = LI->getLoopDepth(LParent),
625                RDepth = LI->getLoopDepth(RParent);
626       if (LDepth != RDepth)
627         return (int)LDepth - (int)RDepth;
628     }
629 
630     // Compare the number of operands.
631     unsigned LNumOps = LInst->getNumOperands(),
632              RNumOps = RInst->getNumOperands();
633     if (LNumOps != RNumOps)
634       return (int)LNumOps - (int)RNumOps;
635 
636     for (unsigned Idx : seq(0u, LNumOps)) {
637       int Result =
638           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
639                                  RInst->getOperand(Idx), Depth + 1);
640       if (Result != 0)
641         return Result;
642     }
643   }
644 
645   EqCacheValue.unionSets(LV, RV);
646   return 0;
647 }
648 
649 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
650 // than RHS, respectively. A three-way result allows recursive comparisons to be
651 // more efficient.
652 static int CompareSCEVComplexity(
653     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
654     EquivalenceClasses<const Value *> &EqCacheValue,
655     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
656     DominatorTree &DT, unsigned Depth = 0) {
657   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
658   if (LHS == RHS)
659     return 0;
660 
661   // Primarily, sort the SCEVs by their getSCEVType().
662   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
663   if (LType != RType)
664     return (int)LType - (int)RType;
665 
666   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
667     return 0;
668   // Aside from the getSCEVType() ordering, the particular ordering
669   // isn't very important except that it's beneficial to be consistent,
670   // so that (a + b) and (b + a) don't end up as different expressions.
671   switch (static_cast<SCEVTypes>(LType)) {
672   case scUnknown: {
673     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
674     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
675 
676     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
677                                    RU->getValue(), Depth + 1);
678     if (X == 0)
679       EqCacheSCEV.unionSets(LHS, RHS);
680     return X;
681   }
682 
683   case scConstant: {
684     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
685     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
686 
687     // Compare constant values.
688     const APInt &LA = LC->getAPInt();
689     const APInt &RA = RC->getAPInt();
690     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
691     if (LBitWidth != RBitWidth)
692       return (int)LBitWidth - (int)RBitWidth;
693     return LA.ult(RA) ? -1 : 1;
694   }
695 
696   case scAddRecExpr: {
697     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
698     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
699 
700     // There is always a dominance between two recs that are used by one SCEV,
701     // so we can safely sort recs by loop header dominance. We require such
702     // order in getAddExpr.
703     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
704     if (LLoop != RLoop) {
705       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
706       assert(LHead != RHead && "Two loops share the same header?");
707       if (DT.dominates(LHead, RHead))
708         return 1;
709       else
710         assert(DT.dominates(RHead, LHead) &&
711                "No dominance between recurrences used by one SCEV?");
712       return -1;
713     }
714 
715     // Addrec complexity grows with operand count.
716     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
717     if (LNumOps != RNumOps)
718       return (int)LNumOps - (int)RNumOps;
719 
720     // Lexicographically compare.
721     for (unsigned i = 0; i != LNumOps; ++i) {
722       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
723                                     LA->getOperand(i), RA->getOperand(i), DT,
724                                     Depth + 1);
725       if (X != 0)
726         return X;
727     }
728     EqCacheSCEV.unionSets(LHS, RHS);
729     return 0;
730   }
731 
732   case scAddExpr:
733   case scMulExpr:
734   case scSMaxExpr:
735   case scUMaxExpr:
736   case scSMinExpr:
737   case scUMinExpr: {
738     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
739     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
740 
741     // Lexicographically compare n-ary expressions.
742     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
743     if (LNumOps != RNumOps)
744       return (int)LNumOps - (int)RNumOps;
745 
746     for (unsigned i = 0; i != LNumOps; ++i) {
747       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
748                                     LC->getOperand(i), RC->getOperand(i), DT,
749                                     Depth + 1);
750       if (X != 0)
751         return X;
752     }
753     EqCacheSCEV.unionSets(LHS, RHS);
754     return 0;
755   }
756 
757   case scUDivExpr: {
758     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
759     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
760 
761     // Lexicographically compare udiv expressions.
762     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
763                                   RC->getLHS(), DT, Depth + 1);
764     if (X != 0)
765       return X;
766     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
767                               RC->getRHS(), DT, Depth + 1);
768     if (X == 0)
769       EqCacheSCEV.unionSets(LHS, RHS);
770     return X;
771   }
772 
773   case scTruncate:
774   case scZeroExtend:
775   case scSignExtend: {
776     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
777     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
778 
779     // Compare cast expressions by operand.
780     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
781                                   LC->getOperand(), RC->getOperand(), DT,
782                                   Depth + 1);
783     if (X == 0)
784       EqCacheSCEV.unionSets(LHS, RHS);
785     return X;
786   }
787 
788   case scCouldNotCompute:
789     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
790   }
791   llvm_unreachable("Unknown SCEV kind!");
792 }
793 
794 /// Given a list of SCEV objects, order them by their complexity, and group
795 /// objects of the same complexity together by value.  When this routine is
796 /// finished, we know that any duplicates in the vector are consecutive and that
797 /// complexity is monotonically increasing.
798 ///
799 /// Note that we go take special precautions to ensure that we get deterministic
800 /// results from this routine.  In other words, we don't want the results of
801 /// this to depend on where the addresses of various SCEV objects happened to
802 /// land in memory.
803 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
804                               LoopInfo *LI, DominatorTree &DT) {
805   if (Ops.size() < 2) return;  // Noop
806 
807   EquivalenceClasses<const SCEV *> EqCacheSCEV;
808   EquivalenceClasses<const Value *> EqCacheValue;
809   if (Ops.size() == 2) {
810     // This is the common case, which also happens to be trivially simple.
811     // Special case it.
812     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
813     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
814       std::swap(LHS, RHS);
815     return;
816   }
817 
818   // Do the rough sort by complexity.
819   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
820     return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
821            0;
822   });
823 
824   // Now that we are sorted by complexity, group elements of the same
825   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
826   // be extremely short in practice.  Note that we take this approach because we
827   // do not want to depend on the addresses of the objects we are grouping.
828   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
829     const SCEV *S = Ops[i];
830     unsigned Complexity = S->getSCEVType();
831 
832     // If there are any objects of the same complexity and same value as this
833     // one, group them.
834     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
835       if (Ops[j] == S) { // Found a duplicate.
836         // Move it to immediately after i'th element.
837         std::swap(Ops[i+1], Ops[j]);
838         ++i;   // no need to rescan it.
839         if (i == e-2) return;  // Done!
840       }
841     }
842   }
843 }
844 
845 // Returns the size of the SCEV S.
846 static inline int sizeOfSCEV(const SCEV *S) {
847   struct FindSCEVSize {
848     int Size = 0;
849 
850     FindSCEVSize() = default;
851 
852     bool follow(const SCEV *S) {
853       ++Size;
854       // Keep looking at all operands of S.
855       return true;
856     }
857 
858     bool isDone() const {
859       return false;
860     }
861   };
862 
863   FindSCEVSize F;
864   SCEVTraversal<FindSCEVSize> ST(F);
865   ST.visitAll(S);
866   return F.Size;
867 }
868 
869 /// Returns true if the subtree of \p S contains at least HugeExprThreshold
870 /// nodes.
871 static bool isHugeExpression(const SCEV *S) {
872   return S->getExpressionSize() >= HugeExprThreshold;
873 }
874 
875 /// Returns true of \p Ops contains a huge SCEV (see definition above).
876 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
877   return any_of(Ops, isHugeExpression);
878 }
879 
880 namespace {
881 
882 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
883 public:
884   // Computes the Quotient and Remainder of the division of Numerator by
885   // Denominator.
886   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
887                      const SCEV *Denominator, const SCEV **Quotient,
888                      const SCEV **Remainder) {
889     assert(Numerator && Denominator && "Uninitialized SCEV");
890 
891     SCEVDivision D(SE, Numerator, Denominator);
892 
893     // Check for the trivial case here to avoid having to check for it in the
894     // rest of the code.
895     if (Numerator == Denominator) {
896       *Quotient = D.One;
897       *Remainder = D.Zero;
898       return;
899     }
900 
901     if (Numerator->isZero()) {
902       *Quotient = D.Zero;
903       *Remainder = D.Zero;
904       return;
905     }
906 
907     // A simple case when N/1. The quotient is N.
908     if (Denominator->isOne()) {
909       *Quotient = Numerator;
910       *Remainder = D.Zero;
911       return;
912     }
913 
914     // Split the Denominator when it is a product.
915     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
916       const SCEV *Q, *R;
917       *Quotient = Numerator;
918       for (const SCEV *Op : T->operands()) {
919         divide(SE, *Quotient, Op, &Q, &R);
920         *Quotient = Q;
921 
922         // Bail out when the Numerator is not divisible by one of the terms of
923         // the Denominator.
924         if (!R->isZero()) {
925           *Quotient = D.Zero;
926           *Remainder = Numerator;
927           return;
928         }
929       }
930       *Remainder = D.Zero;
931       return;
932     }
933 
934     D.visit(Numerator);
935     *Quotient = D.Quotient;
936     *Remainder = D.Remainder;
937   }
938 
939   // Except in the trivial case described above, we do not know how to divide
940   // Expr by Denominator for the following functions with empty implementation.
941   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
942   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
943   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
944   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
945   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
946   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
947   void visitSMinExpr(const SCEVSMinExpr *Numerator) {}
948   void visitUMinExpr(const SCEVUMinExpr *Numerator) {}
949   void visitUnknown(const SCEVUnknown *Numerator) {}
950   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
951 
952   void visitConstant(const SCEVConstant *Numerator) {
953     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
954       APInt NumeratorVal = Numerator->getAPInt();
955       APInt DenominatorVal = D->getAPInt();
956       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
957       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
958 
959       if (NumeratorBW > DenominatorBW)
960         DenominatorVal = DenominatorVal.sext(NumeratorBW);
961       else if (NumeratorBW < DenominatorBW)
962         NumeratorVal = NumeratorVal.sext(DenominatorBW);
963 
964       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
965       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
966       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
967       Quotient = SE.getConstant(QuotientVal);
968       Remainder = SE.getConstant(RemainderVal);
969       return;
970     }
971   }
972 
973   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
974     const SCEV *StartQ, *StartR, *StepQ, *StepR;
975     if (!Numerator->isAffine())
976       return cannotDivide(Numerator);
977     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
978     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
979     // Bail out if the types do not match.
980     Type *Ty = Denominator->getType();
981     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
982         Ty != StepQ->getType() || Ty != StepR->getType())
983       return cannotDivide(Numerator);
984     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
985                                 Numerator->getNoWrapFlags());
986     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
987                                  Numerator->getNoWrapFlags());
988   }
989 
990   void visitAddExpr(const SCEVAddExpr *Numerator) {
991     SmallVector<const SCEV *, 2> Qs, Rs;
992     Type *Ty = Denominator->getType();
993 
994     for (const SCEV *Op : Numerator->operands()) {
995       const SCEV *Q, *R;
996       divide(SE, Op, Denominator, &Q, &R);
997 
998       // Bail out if types do not match.
999       if (Ty != Q->getType() || Ty != R->getType())
1000         return cannotDivide(Numerator);
1001 
1002       Qs.push_back(Q);
1003       Rs.push_back(R);
1004     }
1005 
1006     if (Qs.size() == 1) {
1007       Quotient = Qs[0];
1008       Remainder = Rs[0];
1009       return;
1010     }
1011 
1012     Quotient = SE.getAddExpr(Qs);
1013     Remainder = SE.getAddExpr(Rs);
1014   }
1015 
1016   void visitMulExpr(const SCEVMulExpr *Numerator) {
1017     SmallVector<const SCEV *, 2> Qs;
1018     Type *Ty = Denominator->getType();
1019 
1020     bool FoundDenominatorTerm = false;
1021     for (const SCEV *Op : Numerator->operands()) {
1022       // Bail out if types do not match.
1023       if (Ty != Op->getType())
1024         return cannotDivide(Numerator);
1025 
1026       if (FoundDenominatorTerm) {
1027         Qs.push_back(Op);
1028         continue;
1029       }
1030 
1031       // Check whether Denominator divides one of the product operands.
1032       const SCEV *Q, *R;
1033       divide(SE, Op, Denominator, &Q, &R);
1034       if (!R->isZero()) {
1035         Qs.push_back(Op);
1036         continue;
1037       }
1038 
1039       // Bail out if types do not match.
1040       if (Ty != Q->getType())
1041         return cannotDivide(Numerator);
1042 
1043       FoundDenominatorTerm = true;
1044       Qs.push_back(Q);
1045     }
1046 
1047     if (FoundDenominatorTerm) {
1048       Remainder = Zero;
1049       if (Qs.size() == 1)
1050         Quotient = Qs[0];
1051       else
1052         Quotient = SE.getMulExpr(Qs);
1053       return;
1054     }
1055 
1056     if (!isa<SCEVUnknown>(Denominator))
1057       return cannotDivide(Numerator);
1058 
1059     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1060     ValueToValueMap RewriteMap;
1061     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1062         cast<SCEVConstant>(Zero)->getValue();
1063     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1064 
1065     if (Remainder->isZero()) {
1066       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1067       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1068           cast<SCEVConstant>(One)->getValue();
1069       Quotient =
1070           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1071       return;
1072     }
1073 
1074     // Quotient is (Numerator - Remainder) divided by Denominator.
1075     const SCEV *Q, *R;
1076     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1077     // This SCEV does not seem to simplify: fail the division here.
1078     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1079       return cannotDivide(Numerator);
1080     divide(SE, Diff, Denominator, &Q, &R);
1081     if (R != Zero)
1082       return cannotDivide(Numerator);
1083     Quotient = Q;
1084   }
1085 
1086 private:
1087   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1088                const SCEV *Denominator)
1089       : SE(S), Denominator(Denominator) {
1090     Zero = SE.getZero(Denominator->getType());
1091     One = SE.getOne(Denominator->getType());
1092 
1093     // We generally do not know how to divide Expr by Denominator. We
1094     // initialize the division to a "cannot divide" state to simplify the rest
1095     // of the code.
1096     cannotDivide(Numerator);
1097   }
1098 
1099   // Convenience function for giving up on the division. We set the quotient to
1100   // be equal to zero and the remainder to be equal to the numerator.
1101   void cannotDivide(const SCEV *Numerator) {
1102     Quotient = Zero;
1103     Remainder = Numerator;
1104   }
1105 
1106   ScalarEvolution &SE;
1107   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1108 };
1109 
1110 } // end anonymous namespace
1111 
1112 //===----------------------------------------------------------------------===//
1113 //                      Simple SCEV method implementations
1114 //===----------------------------------------------------------------------===//
1115 
1116 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1117 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1118                                        ScalarEvolution &SE,
1119                                        Type *ResultTy) {
1120   // Handle the simplest case efficiently.
1121   if (K == 1)
1122     return SE.getTruncateOrZeroExtend(It, ResultTy);
1123 
1124   // We are using the following formula for BC(It, K):
1125   //
1126   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1127   //
1128   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1129   // overflow.  Hence, we must assure that the result of our computation is
1130   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1131   // safe in modular arithmetic.
1132   //
1133   // However, this code doesn't use exactly that formula; the formula it uses
1134   // is something like the following, where T is the number of factors of 2 in
1135   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1136   // exponentiation:
1137   //
1138   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1139   //
1140   // This formula is trivially equivalent to the previous formula.  However,
1141   // this formula can be implemented much more efficiently.  The trick is that
1142   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1143   // arithmetic.  To do exact division in modular arithmetic, all we have
1144   // to do is multiply by the inverse.  Therefore, this step can be done at
1145   // width W.
1146   //
1147   // The next issue is how to safely do the division by 2^T.  The way this
1148   // is done is by doing the multiplication step at a width of at least W + T
1149   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1150   // when we perform the division by 2^T (which is equivalent to a right shift
1151   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1152   // truncated out after the division by 2^T.
1153   //
1154   // In comparison to just directly using the first formula, this technique
1155   // is much more efficient; using the first formula requires W * K bits,
1156   // but this formula less than W + K bits. Also, the first formula requires
1157   // a division step, whereas this formula only requires multiplies and shifts.
1158   //
1159   // It doesn't matter whether the subtraction step is done in the calculation
1160   // width or the input iteration count's width; if the subtraction overflows,
1161   // the result must be zero anyway.  We prefer here to do it in the width of
1162   // the induction variable because it helps a lot for certain cases; CodeGen
1163   // isn't smart enough to ignore the overflow, which leads to much less
1164   // efficient code if the width of the subtraction is wider than the native
1165   // register width.
1166   //
1167   // (It's possible to not widen at all by pulling out factors of 2 before
1168   // the multiplication; for example, K=2 can be calculated as
1169   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1170   // extra arithmetic, so it's not an obvious win, and it gets
1171   // much more complicated for K > 3.)
1172 
1173   // Protection from insane SCEVs; this bound is conservative,
1174   // but it probably doesn't matter.
1175   if (K > 1000)
1176     return SE.getCouldNotCompute();
1177 
1178   unsigned W = SE.getTypeSizeInBits(ResultTy);
1179 
1180   // Calculate K! / 2^T and T; we divide out the factors of two before
1181   // multiplying for calculating K! / 2^T to avoid overflow.
1182   // Other overflow doesn't matter because we only care about the bottom
1183   // W bits of the result.
1184   APInt OddFactorial(W, 1);
1185   unsigned T = 1;
1186   for (unsigned i = 3; i <= K; ++i) {
1187     APInt Mult(W, i);
1188     unsigned TwoFactors = Mult.countTrailingZeros();
1189     T += TwoFactors;
1190     Mult.lshrInPlace(TwoFactors);
1191     OddFactorial *= Mult;
1192   }
1193 
1194   // We need at least W + T bits for the multiplication step
1195   unsigned CalculationBits = W + T;
1196 
1197   // Calculate 2^T, at width T+W.
1198   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1199 
1200   // Calculate the multiplicative inverse of K! / 2^T;
1201   // this multiplication factor will perform the exact division by
1202   // K! / 2^T.
1203   APInt Mod = APInt::getSignedMinValue(W+1);
1204   APInt MultiplyFactor = OddFactorial.zext(W+1);
1205   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1206   MultiplyFactor = MultiplyFactor.trunc(W);
1207 
1208   // Calculate the product, at width T+W
1209   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1210                                                       CalculationBits);
1211   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1212   for (unsigned i = 1; i != K; ++i) {
1213     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1214     Dividend = SE.getMulExpr(Dividend,
1215                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1216   }
1217 
1218   // Divide by 2^T
1219   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1220 
1221   // Truncate the result, and divide by K! / 2^T.
1222 
1223   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1224                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1225 }
1226 
1227 /// Return the value of this chain of recurrences at the specified iteration
1228 /// number.  We can evaluate this recurrence by multiplying each element in the
1229 /// chain by the binomial coefficient corresponding to it.  In other words, we
1230 /// can evaluate {A,+,B,+,C,+,D} as:
1231 ///
1232 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1233 ///
1234 /// where BC(It, k) stands for binomial coefficient.
1235 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1236                                                 ScalarEvolution &SE) const {
1237   const SCEV *Result = getStart();
1238   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1239     // The computation is correct in the face of overflow provided that the
1240     // multiplication is performed _after_ the evaluation of the binomial
1241     // coefficient.
1242     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1243     if (isa<SCEVCouldNotCompute>(Coeff))
1244       return Coeff;
1245 
1246     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1247   }
1248   return Result;
1249 }
1250 
1251 //===----------------------------------------------------------------------===//
1252 //                    SCEV Expression folder implementations
1253 //===----------------------------------------------------------------------===//
1254 
1255 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1256                                              unsigned Depth) {
1257   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1258          "This is not a truncating conversion!");
1259   assert(isSCEVable(Ty) &&
1260          "This is not a conversion to a SCEVable type!");
1261   Ty = getEffectiveSCEVType(Ty);
1262 
1263   FoldingSetNodeID ID;
1264   ID.AddInteger(scTruncate);
1265   ID.AddPointer(Op);
1266   ID.AddPointer(Ty);
1267   void *IP = nullptr;
1268   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1269 
1270   // Fold if the operand is constant.
1271   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1272     return getConstant(
1273       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1274 
1275   // trunc(trunc(x)) --> trunc(x)
1276   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1277     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1278 
1279   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1280   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1281     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1282 
1283   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1284   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1285     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1286 
1287   if (Depth > MaxCastDepth) {
1288     SCEV *S =
1289         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1290     UniqueSCEVs.InsertNode(S, IP);
1291     addToLoopUseLists(S);
1292     return S;
1293   }
1294 
1295   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1296   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1297   // if after transforming we have at most one truncate, not counting truncates
1298   // that replace other casts.
1299   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1300     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1301     SmallVector<const SCEV *, 4> Operands;
1302     unsigned numTruncs = 0;
1303     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1304          ++i) {
1305       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1306       if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1307         numTruncs++;
1308       Operands.push_back(S);
1309     }
1310     if (numTruncs < 2) {
1311       if (isa<SCEVAddExpr>(Op))
1312         return getAddExpr(Operands);
1313       else if (isa<SCEVMulExpr>(Op))
1314         return getMulExpr(Operands);
1315       else
1316         llvm_unreachable("Unexpected SCEV type for Op.");
1317     }
1318     // Although we checked in the beginning that ID is not in the cache, it is
1319     // possible that during recursion and different modification ID was inserted
1320     // into the cache. So if we find it, just return it.
1321     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1322       return S;
1323   }
1324 
1325   // If the input value is a chrec scev, truncate the chrec's operands.
1326   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1327     SmallVector<const SCEV *, 4> Operands;
1328     for (const SCEV *Op : AddRec->operands())
1329       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1330     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1331   }
1332 
1333   // The cast wasn't folded; create an explicit cast node. We can reuse
1334   // the existing insert position since if we get here, we won't have
1335   // made any changes which would invalidate it.
1336   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1337                                                  Op, Ty);
1338   UniqueSCEVs.InsertNode(S, IP);
1339   addToLoopUseLists(S);
1340   return S;
1341 }
1342 
1343 // Get the limit of a recurrence such that incrementing by Step cannot cause
1344 // signed overflow as long as the value of the recurrence within the
1345 // loop does not exceed this limit before incrementing.
1346 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1347                                                  ICmpInst::Predicate *Pred,
1348                                                  ScalarEvolution *SE) {
1349   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1350   if (SE->isKnownPositive(Step)) {
1351     *Pred = ICmpInst::ICMP_SLT;
1352     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1353                            SE->getSignedRangeMax(Step));
1354   }
1355   if (SE->isKnownNegative(Step)) {
1356     *Pred = ICmpInst::ICMP_SGT;
1357     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1358                            SE->getSignedRangeMin(Step));
1359   }
1360   return nullptr;
1361 }
1362 
1363 // Get the limit of a recurrence such that incrementing by Step cannot cause
1364 // unsigned overflow as long as the value of the recurrence within the loop does
1365 // not exceed this limit before incrementing.
1366 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1367                                                    ICmpInst::Predicate *Pred,
1368                                                    ScalarEvolution *SE) {
1369   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1370   *Pred = ICmpInst::ICMP_ULT;
1371 
1372   return SE->getConstant(APInt::getMinValue(BitWidth) -
1373                          SE->getUnsignedRangeMax(Step));
1374 }
1375 
1376 namespace {
1377 
1378 struct ExtendOpTraitsBase {
1379   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1380                                                           unsigned);
1381 };
1382 
1383 // Used to make code generic over signed and unsigned overflow.
1384 template <typename ExtendOp> struct ExtendOpTraits {
1385   // Members present:
1386   //
1387   // static const SCEV::NoWrapFlags WrapType;
1388   //
1389   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1390   //
1391   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1392   //                                           ICmpInst::Predicate *Pred,
1393   //                                           ScalarEvolution *SE);
1394 };
1395 
1396 template <>
1397 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1398   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1399 
1400   static const GetExtendExprTy GetExtendExpr;
1401 
1402   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1403                                              ICmpInst::Predicate *Pred,
1404                                              ScalarEvolution *SE) {
1405     return getSignedOverflowLimitForStep(Step, Pred, SE);
1406   }
1407 };
1408 
1409 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1410     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1411 
1412 template <>
1413 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1414   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1415 
1416   static const GetExtendExprTy GetExtendExpr;
1417 
1418   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1419                                              ICmpInst::Predicate *Pred,
1420                                              ScalarEvolution *SE) {
1421     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1422   }
1423 };
1424 
1425 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1426     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1427 
1428 } // end anonymous namespace
1429 
1430 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1431 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1432 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1433 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1434 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1435 // expression "Step + sext/zext(PreIncAR)" is congruent with
1436 // "sext/zext(PostIncAR)"
1437 template <typename ExtendOpTy>
1438 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1439                                         ScalarEvolution *SE, unsigned Depth) {
1440   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1441   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1442 
1443   const Loop *L = AR->getLoop();
1444   const SCEV *Start = AR->getStart();
1445   const SCEV *Step = AR->getStepRecurrence(*SE);
1446 
1447   // Check for a simple looking step prior to loop entry.
1448   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1449   if (!SA)
1450     return nullptr;
1451 
1452   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1453   // subtraction is expensive. For this purpose, perform a quick and dirty
1454   // difference, by checking for Step in the operand list.
1455   SmallVector<const SCEV *, 4> DiffOps;
1456   for (const SCEV *Op : SA->operands())
1457     if (Op != Step)
1458       DiffOps.push_back(Op);
1459 
1460   if (DiffOps.size() == SA->getNumOperands())
1461     return nullptr;
1462 
1463   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1464   // `Step`:
1465 
1466   // 1. NSW/NUW flags on the step increment.
1467   auto PreStartFlags =
1468     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1469   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1470   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1471       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1472 
1473   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1474   // "S+X does not sign/unsign-overflow".
1475   //
1476 
1477   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1478   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1479       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1480     return PreStart;
1481 
1482   // 2. Direct overflow check on the step operation's expression.
1483   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1484   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1485   const SCEV *OperandExtendedStart =
1486       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1487                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1488   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1489     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1490       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1491       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1492       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1493       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1494     }
1495     return PreStart;
1496   }
1497 
1498   // 3. Loop precondition.
1499   ICmpInst::Predicate Pred;
1500   const SCEV *OverflowLimit =
1501       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1502 
1503   if (OverflowLimit &&
1504       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1505     return PreStart;
1506 
1507   return nullptr;
1508 }
1509 
1510 // Get the normalized zero or sign extended expression for this AddRec's Start.
1511 template <typename ExtendOpTy>
1512 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1513                                         ScalarEvolution *SE,
1514                                         unsigned Depth) {
1515   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1516 
1517   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1518   if (!PreStart)
1519     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1520 
1521   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1522                                              Depth),
1523                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1524 }
1525 
1526 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1527 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1528 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1529 //
1530 // Formally:
1531 //
1532 //     {S,+,X} == {S-T,+,X} + T
1533 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1534 //
1535 // If ({S-T,+,X} + T) does not overflow  ... (1)
1536 //
1537 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1538 //
1539 // If {S-T,+,X} does not overflow  ... (2)
1540 //
1541 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1542 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1543 //
1544 // If (S-T)+T does not overflow  ... (3)
1545 //
1546 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1547 //      == {Ext(S),+,Ext(X)} == LHS
1548 //
1549 // Thus, if (1), (2) and (3) are true for some T, then
1550 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1551 //
1552 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1553 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1554 // to check for (1) and (2).
1555 //
1556 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1557 // is `Delta` (defined below).
1558 template <typename ExtendOpTy>
1559 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1560                                                 const SCEV *Step,
1561                                                 const Loop *L) {
1562   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1563 
1564   // We restrict `Start` to a constant to prevent SCEV from spending too much
1565   // time here.  It is correct (but more expensive) to continue with a
1566   // non-constant `Start` and do a general SCEV subtraction to compute
1567   // `PreStart` below.
1568   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1569   if (!StartC)
1570     return false;
1571 
1572   APInt StartAI = StartC->getAPInt();
1573 
1574   for (unsigned Delta : {-2, -1, 1, 2}) {
1575     const SCEV *PreStart = getConstant(StartAI - Delta);
1576 
1577     FoldingSetNodeID ID;
1578     ID.AddInteger(scAddRecExpr);
1579     ID.AddPointer(PreStart);
1580     ID.AddPointer(Step);
1581     ID.AddPointer(L);
1582     void *IP = nullptr;
1583     const auto *PreAR =
1584       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1585 
1586     // Give up if we don't already have the add recurrence we need because
1587     // actually constructing an add recurrence is relatively expensive.
1588     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1589       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1590       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1591       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1592           DeltaS, &Pred, this);
1593       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1594         return true;
1595     }
1596   }
1597 
1598   return false;
1599 }
1600 
1601 // Finds an integer D for an expression (C + x + y + ...) such that the top
1602 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1603 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1604 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1605 // the (C + x + y + ...) expression is \p WholeAddExpr.
1606 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1607                                             const SCEVConstant *ConstantTerm,
1608                                             const SCEVAddExpr *WholeAddExpr) {
1609   const APInt C = ConstantTerm->getAPInt();
1610   const unsigned BitWidth = C.getBitWidth();
1611   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1612   uint32_t TZ = BitWidth;
1613   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1614     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1615   if (TZ) {
1616     // Set D to be as many least significant bits of C as possible while still
1617     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1618     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1619   }
1620   return APInt(BitWidth, 0);
1621 }
1622 
1623 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1624 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1625 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1626 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1627 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1628                                             const APInt &ConstantStart,
1629                                             const SCEV *Step) {
1630   const unsigned BitWidth = ConstantStart.getBitWidth();
1631   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1632   if (TZ)
1633     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1634                          : ConstantStart;
1635   return APInt(BitWidth, 0);
1636 }
1637 
1638 const SCEV *
1639 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1640   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1641          "This is not an extending conversion!");
1642   assert(isSCEVable(Ty) &&
1643          "This is not a conversion to a SCEVable type!");
1644   Ty = getEffectiveSCEVType(Ty);
1645 
1646   // Fold if the operand is constant.
1647   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1648     return getConstant(
1649       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1650 
1651   // zext(zext(x)) --> zext(x)
1652   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1653     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1654 
1655   // Before doing any expensive analysis, check to see if we've already
1656   // computed a SCEV for this Op and Ty.
1657   FoldingSetNodeID ID;
1658   ID.AddInteger(scZeroExtend);
1659   ID.AddPointer(Op);
1660   ID.AddPointer(Ty);
1661   void *IP = nullptr;
1662   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1663   if (Depth > MaxCastDepth) {
1664     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1665                                                      Op, Ty);
1666     UniqueSCEVs.InsertNode(S, IP);
1667     addToLoopUseLists(S);
1668     return S;
1669   }
1670 
1671   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1672   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1673     // It's possible the bits taken off by the truncate were all zero bits. If
1674     // so, we should be able to simplify this further.
1675     const SCEV *X = ST->getOperand();
1676     ConstantRange CR = getUnsignedRange(X);
1677     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1678     unsigned NewBits = getTypeSizeInBits(Ty);
1679     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1680             CR.zextOrTrunc(NewBits)))
1681       return getTruncateOrZeroExtend(X, Ty, Depth);
1682   }
1683 
1684   // If the input value is a chrec scev, and we can prove that the value
1685   // did not overflow the old, smaller, value, we can zero extend all of the
1686   // operands (often constants).  This allows analysis of something like
1687   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1688   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1689     if (AR->isAffine()) {
1690       const SCEV *Start = AR->getStart();
1691       const SCEV *Step = AR->getStepRecurrence(*this);
1692       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1693       const Loop *L = AR->getLoop();
1694 
1695       if (!AR->hasNoUnsignedWrap()) {
1696         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1697         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1698       }
1699 
1700       // If we have special knowledge that this addrec won't overflow,
1701       // we don't need to do any further analysis.
1702       if (AR->hasNoUnsignedWrap())
1703         return getAddRecExpr(
1704             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1705             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1706 
1707       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1708       // Note that this serves two purposes: It filters out loops that are
1709       // simply not analyzable, and it covers the case where this code is
1710       // being called from within backedge-taken count analysis, such that
1711       // attempting to ask for the backedge-taken count would likely result
1712       // in infinite recursion. In the later case, the analysis code will
1713       // cope with a conservative value, and it will take care to purge
1714       // that value once it has finished.
1715       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1716       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1717         // Manually compute the final value for AR, checking for
1718         // overflow.
1719 
1720         // Check whether the backedge-taken count can be losslessly casted to
1721         // the addrec's type. The count is always unsigned.
1722         const SCEV *CastedMaxBECount =
1723             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1724         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1725             CastedMaxBECount, MaxBECount->getType(), Depth);
1726         if (MaxBECount == RecastedMaxBECount) {
1727           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1728           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1729           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1730                                         SCEV::FlagAnyWrap, Depth + 1);
1731           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1732                                                           SCEV::FlagAnyWrap,
1733                                                           Depth + 1),
1734                                                WideTy, Depth + 1);
1735           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1736           const SCEV *WideMaxBECount =
1737             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1738           const SCEV *OperandExtendedAdd =
1739             getAddExpr(WideStart,
1740                        getMulExpr(WideMaxBECount,
1741                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1742                                   SCEV::FlagAnyWrap, Depth + 1),
1743                        SCEV::FlagAnyWrap, Depth + 1);
1744           if (ZAdd == OperandExtendedAdd) {
1745             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1746             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1747             // Return the expression with the addrec on the outside.
1748             return getAddRecExpr(
1749                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1750                                                          Depth + 1),
1751                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1752                 AR->getNoWrapFlags());
1753           }
1754           // Similar to above, only this time treat the step value as signed.
1755           // This covers loops that count down.
1756           OperandExtendedAdd =
1757             getAddExpr(WideStart,
1758                        getMulExpr(WideMaxBECount,
1759                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1760                                   SCEV::FlagAnyWrap, Depth + 1),
1761                        SCEV::FlagAnyWrap, Depth + 1);
1762           if (ZAdd == OperandExtendedAdd) {
1763             // Cache knowledge of AR NW, which is propagated to this AddRec.
1764             // Negative step causes unsigned wrap, but it still can't self-wrap.
1765             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1766             // Return the expression with the addrec on the outside.
1767             return getAddRecExpr(
1768                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1769                                                          Depth + 1),
1770                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1771                 AR->getNoWrapFlags());
1772           }
1773         }
1774       }
1775 
1776       // Normally, in the cases we can prove no-overflow via a
1777       // backedge guarding condition, we can also compute a backedge
1778       // taken count for the loop.  The exceptions are assumptions and
1779       // guards present in the loop -- SCEV is not great at exploiting
1780       // these to compute max backedge taken counts, but can still use
1781       // these to prove lack of overflow.  Use this fact to avoid
1782       // doing extra work that may not pay off.
1783       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1784           !AC.assumptions().empty()) {
1785         // If the backedge is guarded by a comparison with the pre-inc
1786         // value the addrec is safe. Also, if the entry is guarded by
1787         // a comparison with the start value and the backedge is
1788         // guarded by a comparison with the post-inc value, the addrec
1789         // is safe.
1790         if (isKnownPositive(Step)) {
1791           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1792                                       getUnsignedRangeMax(Step));
1793           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1794               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1795             // Cache knowledge of AR NUW, which is propagated to this
1796             // AddRec.
1797             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1798             // Return the expression with the addrec on the outside.
1799             return getAddRecExpr(
1800                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1801                                                          Depth + 1),
1802                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1803                 AR->getNoWrapFlags());
1804           }
1805         } else if (isKnownNegative(Step)) {
1806           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1807                                       getSignedRangeMin(Step));
1808           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1809               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1810             // Cache knowledge of AR NW, which is propagated to this
1811             // AddRec.  Negative step causes unsigned wrap, but it
1812             // still can't self-wrap.
1813             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1814             // Return the expression with the addrec on the outside.
1815             return getAddRecExpr(
1816                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1817                                                          Depth + 1),
1818                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1819                 AR->getNoWrapFlags());
1820           }
1821         }
1822       }
1823 
1824       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1825       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1826       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1827       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1828         const APInt &C = SC->getAPInt();
1829         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1830         if (D != 0) {
1831           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1832           const SCEV *SResidual =
1833               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1834           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1835           return getAddExpr(SZExtD, SZExtR,
1836                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1837                             Depth + 1);
1838         }
1839       }
1840 
1841       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1842         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1843         return getAddRecExpr(
1844             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1845             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1846       }
1847     }
1848 
1849   // zext(A % B) --> zext(A) % zext(B)
1850   {
1851     const SCEV *LHS;
1852     const SCEV *RHS;
1853     if (matchURem(Op, LHS, RHS))
1854       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1855                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1856   }
1857 
1858   // zext(A / B) --> zext(A) / zext(B).
1859   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1860     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1861                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1862 
1863   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1864     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1865     if (SA->hasNoUnsignedWrap()) {
1866       // If the addition does not unsign overflow then we can, by definition,
1867       // commute the zero extension with the addition operation.
1868       SmallVector<const SCEV *, 4> Ops;
1869       for (const auto *Op : SA->operands())
1870         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1871       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1872     }
1873 
1874     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1875     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1876     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1877     //
1878     // Often address arithmetics contain expressions like
1879     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1880     // This transformation is useful while proving that such expressions are
1881     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1882     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1883       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1884       if (D != 0) {
1885         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1886         const SCEV *SResidual =
1887             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1888         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1889         return getAddExpr(SZExtD, SZExtR,
1890                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1891                           Depth + 1);
1892       }
1893     }
1894   }
1895 
1896   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1897     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1898     if (SM->hasNoUnsignedWrap()) {
1899       // If the multiply does not unsign overflow then we can, by definition,
1900       // commute the zero extension with the multiply operation.
1901       SmallVector<const SCEV *, 4> Ops;
1902       for (const auto *Op : SM->operands())
1903         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1904       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1905     }
1906 
1907     // zext(2^K * (trunc X to iN)) to iM ->
1908     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1909     //
1910     // Proof:
1911     //
1912     //     zext(2^K * (trunc X to iN)) to iM
1913     //   = zext((trunc X to iN) << K) to iM
1914     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1915     //     (because shl removes the top K bits)
1916     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1917     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1918     //
1919     if (SM->getNumOperands() == 2)
1920       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1921         if (MulLHS->getAPInt().isPowerOf2())
1922           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1923             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1924                                MulLHS->getAPInt().logBase2();
1925             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1926             return getMulExpr(
1927                 getZeroExtendExpr(MulLHS, Ty),
1928                 getZeroExtendExpr(
1929                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1930                 SCEV::FlagNUW, Depth + 1);
1931           }
1932   }
1933 
1934   // The cast wasn't folded; create an explicit cast node.
1935   // Recompute the insert position, as it may have been invalidated.
1936   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1937   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1938                                                    Op, Ty);
1939   UniqueSCEVs.InsertNode(S, IP);
1940   addToLoopUseLists(S);
1941   return S;
1942 }
1943 
1944 const SCEV *
1945 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1946   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1947          "This is not an extending conversion!");
1948   assert(isSCEVable(Ty) &&
1949          "This is not a conversion to a SCEVable type!");
1950   Ty = getEffectiveSCEVType(Ty);
1951 
1952   // Fold if the operand is constant.
1953   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1954     return getConstant(
1955       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1956 
1957   // sext(sext(x)) --> sext(x)
1958   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1959     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1960 
1961   // sext(zext(x)) --> zext(x)
1962   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1963     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1964 
1965   // Before doing any expensive analysis, check to see if we've already
1966   // computed a SCEV for this Op and Ty.
1967   FoldingSetNodeID ID;
1968   ID.AddInteger(scSignExtend);
1969   ID.AddPointer(Op);
1970   ID.AddPointer(Ty);
1971   void *IP = nullptr;
1972   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1973   // Limit recursion depth.
1974   if (Depth > MaxCastDepth) {
1975     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1976                                                      Op, Ty);
1977     UniqueSCEVs.InsertNode(S, IP);
1978     addToLoopUseLists(S);
1979     return S;
1980   }
1981 
1982   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1983   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1984     // It's possible the bits taken off by the truncate were all sign bits. If
1985     // so, we should be able to simplify this further.
1986     const SCEV *X = ST->getOperand();
1987     ConstantRange CR = getSignedRange(X);
1988     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1989     unsigned NewBits = getTypeSizeInBits(Ty);
1990     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1991             CR.sextOrTrunc(NewBits)))
1992       return getTruncateOrSignExtend(X, Ty, Depth);
1993   }
1994 
1995   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1996     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1997     if (SA->hasNoSignedWrap()) {
1998       // If the addition does not sign overflow then we can, by definition,
1999       // commute the sign extension with the addition operation.
2000       SmallVector<const SCEV *, 4> Ops;
2001       for (const auto *Op : SA->operands())
2002         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2003       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2004     }
2005 
2006     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2007     // if D + (C - D + x + y + ...) could be proven to not signed wrap
2008     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2009     //
2010     // For instance, this will bring two seemingly different expressions:
2011     //     1 + sext(5 + 20 * %x + 24 * %y)  and
2012     //         sext(6 + 20 * %x + 24 * %y)
2013     // to the same form:
2014     //     2 + sext(4 + 20 * %x + 24 * %y)
2015     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2016       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2017       if (D != 0) {
2018         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2019         const SCEV *SResidual =
2020             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
2021         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2022         return getAddExpr(SSExtD, SSExtR,
2023                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2024                           Depth + 1);
2025       }
2026     }
2027   }
2028   // If the input value is a chrec scev, and we can prove that the value
2029   // did not overflow the old, smaller, value, we can sign extend all of the
2030   // operands (often constants).  This allows analysis of something like
2031   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
2032   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2033     if (AR->isAffine()) {
2034       const SCEV *Start = AR->getStart();
2035       const SCEV *Step = AR->getStepRecurrence(*this);
2036       unsigned BitWidth = getTypeSizeInBits(AR->getType());
2037       const Loop *L = AR->getLoop();
2038 
2039       if (!AR->hasNoSignedWrap()) {
2040         auto NewFlags = proveNoWrapViaConstantRanges(AR);
2041         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
2042       }
2043 
2044       // If we have special knowledge that this addrec won't overflow,
2045       // we don't need to do any further analysis.
2046       if (AR->hasNoSignedWrap())
2047         return getAddRecExpr(
2048             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2049             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2050 
2051       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2052       // Note that this serves two purposes: It filters out loops that are
2053       // simply not analyzable, and it covers the case where this code is
2054       // being called from within backedge-taken count analysis, such that
2055       // attempting to ask for the backedge-taken count would likely result
2056       // in infinite recursion. In the later case, the analysis code will
2057       // cope with a conservative value, and it will take care to purge
2058       // that value once it has finished.
2059       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2060       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2061         // Manually compute the final value for AR, checking for
2062         // overflow.
2063 
2064         // Check whether the backedge-taken count can be losslessly casted to
2065         // the addrec's type. The count is always unsigned.
2066         const SCEV *CastedMaxBECount =
2067             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2068         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2069             CastedMaxBECount, MaxBECount->getType(), Depth);
2070         if (MaxBECount == RecastedMaxBECount) {
2071           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2072           // Check whether Start+Step*MaxBECount has no signed overflow.
2073           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2074                                         SCEV::FlagAnyWrap, Depth + 1);
2075           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2076                                                           SCEV::FlagAnyWrap,
2077                                                           Depth + 1),
2078                                                WideTy, Depth + 1);
2079           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2080           const SCEV *WideMaxBECount =
2081             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2082           const SCEV *OperandExtendedAdd =
2083             getAddExpr(WideStart,
2084                        getMulExpr(WideMaxBECount,
2085                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2086                                   SCEV::FlagAnyWrap, Depth + 1),
2087                        SCEV::FlagAnyWrap, Depth + 1);
2088           if (SAdd == OperandExtendedAdd) {
2089             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2090             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2091             // Return the expression with the addrec on the outside.
2092             return getAddRecExpr(
2093                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2094                                                          Depth + 1),
2095                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2096                 AR->getNoWrapFlags());
2097           }
2098           // Similar to above, only this time treat the step value as unsigned.
2099           // This covers loops that count up with an unsigned step.
2100           OperandExtendedAdd =
2101             getAddExpr(WideStart,
2102                        getMulExpr(WideMaxBECount,
2103                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2104                                   SCEV::FlagAnyWrap, Depth + 1),
2105                        SCEV::FlagAnyWrap, Depth + 1);
2106           if (SAdd == OperandExtendedAdd) {
2107             // If AR wraps around then
2108             //
2109             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2110             // => SAdd != OperandExtendedAdd
2111             //
2112             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2113             // (SAdd == OperandExtendedAdd => AR is NW)
2114 
2115             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2116 
2117             // Return the expression with the addrec on the outside.
2118             return getAddRecExpr(
2119                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2120                                                          Depth + 1),
2121                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2122                 AR->getNoWrapFlags());
2123           }
2124         }
2125       }
2126 
2127       // Normally, in the cases we can prove no-overflow via a
2128       // backedge guarding condition, we can also compute a backedge
2129       // taken count for the loop.  The exceptions are assumptions and
2130       // guards present in the loop -- SCEV is not great at exploiting
2131       // these to compute max backedge taken counts, but can still use
2132       // these to prove lack of overflow.  Use this fact to avoid
2133       // doing extra work that may not pay off.
2134 
2135       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2136           !AC.assumptions().empty()) {
2137         // If the backedge is guarded by a comparison with the pre-inc
2138         // value the addrec is safe. Also, if the entry is guarded by
2139         // a comparison with the start value and the backedge is
2140         // guarded by a comparison with the post-inc value, the addrec
2141         // is safe.
2142         ICmpInst::Predicate Pred;
2143         const SCEV *OverflowLimit =
2144             getSignedOverflowLimitForStep(Step, &Pred, this);
2145         if (OverflowLimit &&
2146             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2147              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2148           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2149           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2150           return getAddRecExpr(
2151               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2152               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2153         }
2154       }
2155 
2156       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2157       // if D + (C - D + Step * n) could be proven to not signed wrap
2158       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2159       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2160         const APInt &C = SC->getAPInt();
2161         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2162         if (D != 0) {
2163           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2164           const SCEV *SResidual =
2165               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2166           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2167           return getAddExpr(SSExtD, SSExtR,
2168                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2169                             Depth + 1);
2170         }
2171       }
2172 
2173       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2174         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2175         return getAddRecExpr(
2176             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2177             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2178       }
2179     }
2180 
2181   // If the input value is provably positive and we could not simplify
2182   // away the sext build a zext instead.
2183   if (isKnownNonNegative(Op))
2184     return getZeroExtendExpr(Op, Ty, Depth + 1);
2185 
2186   // The cast wasn't folded; create an explicit cast node.
2187   // Recompute the insert position, as it may have been invalidated.
2188   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2189   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2190                                                    Op, Ty);
2191   UniqueSCEVs.InsertNode(S, IP);
2192   addToLoopUseLists(S);
2193   return S;
2194 }
2195 
2196 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2197 /// unspecified bits out to the given type.
2198 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2199                                               Type *Ty) {
2200   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2201          "This is not an extending conversion!");
2202   assert(isSCEVable(Ty) &&
2203          "This is not a conversion to a SCEVable type!");
2204   Ty = getEffectiveSCEVType(Ty);
2205 
2206   // Sign-extend negative constants.
2207   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2208     if (SC->getAPInt().isNegative())
2209       return getSignExtendExpr(Op, Ty);
2210 
2211   // Peel off a truncate cast.
2212   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2213     const SCEV *NewOp = T->getOperand();
2214     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2215       return getAnyExtendExpr(NewOp, Ty);
2216     return getTruncateOrNoop(NewOp, Ty);
2217   }
2218 
2219   // Next try a zext cast. If the cast is folded, use it.
2220   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2221   if (!isa<SCEVZeroExtendExpr>(ZExt))
2222     return ZExt;
2223 
2224   // Next try a sext cast. If the cast is folded, use it.
2225   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2226   if (!isa<SCEVSignExtendExpr>(SExt))
2227     return SExt;
2228 
2229   // Force the cast to be folded into the operands of an addrec.
2230   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2231     SmallVector<const SCEV *, 4> Ops;
2232     for (const SCEV *Op : AR->operands())
2233       Ops.push_back(getAnyExtendExpr(Op, Ty));
2234     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2235   }
2236 
2237   // If the expression is obviously signed, use the sext cast value.
2238   if (isa<SCEVSMaxExpr>(Op))
2239     return SExt;
2240 
2241   // Absent any other information, use the zext cast value.
2242   return ZExt;
2243 }
2244 
2245 /// Process the given Ops list, which is a list of operands to be added under
2246 /// the given scale, update the given map. This is a helper function for
2247 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2248 /// that would form an add expression like this:
2249 ///
2250 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2251 ///
2252 /// where A and B are constants, update the map with these values:
2253 ///
2254 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2255 ///
2256 /// and add 13 + A*B*29 to AccumulatedConstant.
2257 /// This will allow getAddRecExpr to produce this:
2258 ///
2259 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2260 ///
2261 /// This form often exposes folding opportunities that are hidden in
2262 /// the original operand list.
2263 ///
2264 /// Return true iff it appears that any interesting folding opportunities
2265 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2266 /// the common case where no interesting opportunities are present, and
2267 /// is also used as a check to avoid infinite recursion.
2268 static bool
2269 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2270                              SmallVectorImpl<const SCEV *> &NewOps,
2271                              APInt &AccumulatedConstant,
2272                              const SCEV *const *Ops, size_t NumOperands,
2273                              const APInt &Scale,
2274                              ScalarEvolution &SE) {
2275   bool Interesting = false;
2276 
2277   // Iterate over the add operands. They are sorted, with constants first.
2278   unsigned i = 0;
2279   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2280     ++i;
2281     // Pull a buried constant out to the outside.
2282     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2283       Interesting = true;
2284     AccumulatedConstant += Scale * C->getAPInt();
2285   }
2286 
2287   // Next comes everything else. We're especially interested in multiplies
2288   // here, but they're in the middle, so just visit the rest with one loop.
2289   for (; i != NumOperands; ++i) {
2290     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2291     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2292       APInt NewScale =
2293           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2294       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2295         // A multiplication of a constant with another add; recurse.
2296         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2297         Interesting |=
2298           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2299                                        Add->op_begin(), Add->getNumOperands(),
2300                                        NewScale, SE);
2301       } else {
2302         // A multiplication of a constant with some other value. Update
2303         // the map.
2304         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2305         const SCEV *Key = SE.getMulExpr(MulOps);
2306         auto Pair = M.insert({Key, NewScale});
2307         if (Pair.second) {
2308           NewOps.push_back(Pair.first->first);
2309         } else {
2310           Pair.first->second += NewScale;
2311           // The map already had an entry for this value, which may indicate
2312           // a folding opportunity.
2313           Interesting = true;
2314         }
2315       }
2316     } else {
2317       // An ordinary operand. Update the map.
2318       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2319           M.insert({Ops[i], Scale});
2320       if (Pair.second) {
2321         NewOps.push_back(Pair.first->first);
2322       } else {
2323         Pair.first->second += Scale;
2324         // The map already had an entry for this value, which may indicate
2325         // a folding opportunity.
2326         Interesting = true;
2327       }
2328     }
2329   }
2330 
2331   return Interesting;
2332 }
2333 
2334 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2335 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2336 // can't-overflow flags for the operation if possible.
2337 static SCEV::NoWrapFlags
2338 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2339                       const ArrayRef<const SCEV *> Ops,
2340                       SCEV::NoWrapFlags Flags) {
2341   using namespace std::placeholders;
2342 
2343   using OBO = OverflowingBinaryOperator;
2344 
2345   bool CanAnalyze =
2346       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2347   (void)CanAnalyze;
2348   assert(CanAnalyze && "don't call from other places!");
2349 
2350   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2351   SCEV::NoWrapFlags SignOrUnsignWrap =
2352       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2353 
2354   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2355   auto IsKnownNonNegative = [&](const SCEV *S) {
2356     return SE->isKnownNonNegative(S);
2357   };
2358 
2359   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2360     Flags =
2361         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2362 
2363   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2364 
2365   if (SignOrUnsignWrap != SignOrUnsignMask &&
2366       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2367       isa<SCEVConstant>(Ops[0])) {
2368 
2369     auto Opcode = [&] {
2370       switch (Type) {
2371       case scAddExpr:
2372         return Instruction::Add;
2373       case scMulExpr:
2374         return Instruction::Mul;
2375       default:
2376         llvm_unreachable("Unexpected SCEV op.");
2377       }
2378     }();
2379 
2380     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2381 
2382     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2383     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2384       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2385           Opcode, C, OBO::NoSignedWrap);
2386       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2387         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2388     }
2389 
2390     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2391     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2392       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2393           Opcode, C, OBO::NoUnsignedWrap);
2394       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2395         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2396     }
2397   }
2398 
2399   return Flags;
2400 }
2401 
2402 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2403   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2404 }
2405 
2406 /// Get a canonical add expression, or something simpler if possible.
2407 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2408                                         SCEV::NoWrapFlags Flags,
2409                                         unsigned Depth) {
2410   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2411          "only nuw or nsw allowed");
2412   assert(!Ops.empty() && "Cannot get empty add!");
2413   if (Ops.size() == 1) return Ops[0];
2414 #ifndef NDEBUG
2415   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2416   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2417     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2418            "SCEVAddExpr operand types don't match!");
2419 #endif
2420 
2421   // Sort by complexity, this groups all similar expression types together.
2422   GroupByComplexity(Ops, &LI, DT);
2423 
2424   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2425 
2426   // If there are any constants, fold them together.
2427   unsigned Idx = 0;
2428   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2429     ++Idx;
2430     assert(Idx < Ops.size());
2431     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2432       // We found two constants, fold them together!
2433       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2434       if (Ops.size() == 2) return Ops[0];
2435       Ops.erase(Ops.begin()+1);  // Erase the folded element
2436       LHSC = cast<SCEVConstant>(Ops[0]);
2437     }
2438 
2439     // If we are left with a constant zero being added, strip it off.
2440     if (LHSC->getValue()->isZero()) {
2441       Ops.erase(Ops.begin());
2442       --Idx;
2443     }
2444 
2445     if (Ops.size() == 1) return Ops[0];
2446   }
2447 
2448   // Limit recursion calls depth.
2449   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2450     return getOrCreateAddExpr(Ops, Flags);
2451 
2452   // Okay, check to see if the same value occurs in the operand list more than
2453   // once.  If so, merge them together into an multiply expression.  Since we
2454   // sorted the list, these values are required to be adjacent.
2455   Type *Ty = Ops[0]->getType();
2456   bool FoundMatch = false;
2457   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2458     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2459       // Scan ahead to count how many equal operands there are.
2460       unsigned Count = 2;
2461       while (i+Count != e && Ops[i+Count] == Ops[i])
2462         ++Count;
2463       // Merge the values into a multiply.
2464       const SCEV *Scale = getConstant(Ty, Count);
2465       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2466       if (Ops.size() == Count)
2467         return Mul;
2468       Ops[i] = Mul;
2469       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2470       --i; e -= Count - 1;
2471       FoundMatch = true;
2472     }
2473   if (FoundMatch)
2474     return getAddExpr(Ops, Flags, Depth + 1);
2475 
2476   // Check for truncates. If all the operands are truncated from the same
2477   // type, see if factoring out the truncate would permit the result to be
2478   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2479   // if the contents of the resulting outer trunc fold to something simple.
2480   auto FindTruncSrcType = [&]() -> Type * {
2481     // We're ultimately looking to fold an addrec of truncs and muls of only
2482     // constants and truncs, so if we find any other types of SCEV
2483     // as operands of the addrec then we bail and return nullptr here.
2484     // Otherwise, we return the type of the operand of a trunc that we find.
2485     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2486       return T->getOperand()->getType();
2487     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2488       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2489       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2490         return T->getOperand()->getType();
2491     }
2492     return nullptr;
2493   };
2494   if (auto *SrcType = FindTruncSrcType()) {
2495     SmallVector<const SCEV *, 8> LargeOps;
2496     bool Ok = true;
2497     // Check all the operands to see if they can be represented in the
2498     // source type of the truncate.
2499     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2500       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2501         if (T->getOperand()->getType() != SrcType) {
2502           Ok = false;
2503           break;
2504         }
2505         LargeOps.push_back(T->getOperand());
2506       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2507         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2508       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2509         SmallVector<const SCEV *, 8> LargeMulOps;
2510         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2511           if (const SCEVTruncateExpr *T =
2512                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2513             if (T->getOperand()->getType() != SrcType) {
2514               Ok = false;
2515               break;
2516             }
2517             LargeMulOps.push_back(T->getOperand());
2518           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2519             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2520           } else {
2521             Ok = false;
2522             break;
2523           }
2524         }
2525         if (Ok)
2526           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2527       } else {
2528         Ok = false;
2529         break;
2530       }
2531     }
2532     if (Ok) {
2533       // Evaluate the expression in the larger type.
2534       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2535       // If it folds to something simple, use it. Otherwise, don't.
2536       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2537         return getTruncateExpr(Fold, Ty);
2538     }
2539   }
2540 
2541   // Skip past any other cast SCEVs.
2542   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2543     ++Idx;
2544 
2545   // If there are add operands they would be next.
2546   if (Idx < Ops.size()) {
2547     bool DeletedAdd = false;
2548     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2549       if (Ops.size() > AddOpsInlineThreshold ||
2550           Add->getNumOperands() > AddOpsInlineThreshold)
2551         break;
2552       // If we have an add, expand the add operands onto the end of the operands
2553       // list.
2554       Ops.erase(Ops.begin()+Idx);
2555       Ops.append(Add->op_begin(), Add->op_end());
2556       DeletedAdd = true;
2557     }
2558 
2559     // If we deleted at least one add, we added operands to the end of the list,
2560     // and they are not necessarily sorted.  Recurse to resort and resimplify
2561     // any operands we just acquired.
2562     if (DeletedAdd)
2563       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2564   }
2565 
2566   // Skip over the add expression until we get to a multiply.
2567   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2568     ++Idx;
2569 
2570   // Check to see if there are any folding opportunities present with
2571   // operands multiplied by constant values.
2572   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2573     uint64_t BitWidth = getTypeSizeInBits(Ty);
2574     DenseMap<const SCEV *, APInt> M;
2575     SmallVector<const SCEV *, 8> NewOps;
2576     APInt AccumulatedConstant(BitWidth, 0);
2577     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2578                                      Ops.data(), Ops.size(),
2579                                      APInt(BitWidth, 1), *this)) {
2580       struct APIntCompare {
2581         bool operator()(const APInt &LHS, const APInt &RHS) const {
2582           return LHS.ult(RHS);
2583         }
2584       };
2585 
2586       // Some interesting folding opportunity is present, so its worthwhile to
2587       // re-generate the operands list. Group the operands by constant scale,
2588       // to avoid multiplying by the same constant scale multiple times.
2589       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2590       for (const SCEV *NewOp : NewOps)
2591         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2592       // Re-generate the operands list.
2593       Ops.clear();
2594       if (AccumulatedConstant != 0)
2595         Ops.push_back(getConstant(AccumulatedConstant));
2596       for (auto &MulOp : MulOpLists)
2597         if (MulOp.first != 0)
2598           Ops.push_back(getMulExpr(
2599               getConstant(MulOp.first),
2600               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2601               SCEV::FlagAnyWrap, Depth + 1));
2602       if (Ops.empty())
2603         return getZero(Ty);
2604       if (Ops.size() == 1)
2605         return Ops[0];
2606       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2607     }
2608   }
2609 
2610   // If we are adding something to a multiply expression, make sure the
2611   // something is not already an operand of the multiply.  If so, merge it into
2612   // the multiply.
2613   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2614     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2615     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2616       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2617       if (isa<SCEVConstant>(MulOpSCEV))
2618         continue;
2619       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2620         if (MulOpSCEV == Ops[AddOp]) {
2621           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2622           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2623           if (Mul->getNumOperands() != 2) {
2624             // If the multiply has more than two operands, we must get the
2625             // Y*Z term.
2626             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2627                                                 Mul->op_begin()+MulOp);
2628             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2629             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2630           }
2631           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2632           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2633           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2634                                             SCEV::FlagAnyWrap, Depth + 1);
2635           if (Ops.size() == 2) return OuterMul;
2636           if (AddOp < Idx) {
2637             Ops.erase(Ops.begin()+AddOp);
2638             Ops.erase(Ops.begin()+Idx-1);
2639           } else {
2640             Ops.erase(Ops.begin()+Idx);
2641             Ops.erase(Ops.begin()+AddOp-1);
2642           }
2643           Ops.push_back(OuterMul);
2644           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2645         }
2646 
2647       // Check this multiply against other multiplies being added together.
2648       for (unsigned OtherMulIdx = Idx+1;
2649            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2650            ++OtherMulIdx) {
2651         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2652         // If MulOp occurs in OtherMul, we can fold the two multiplies
2653         // together.
2654         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2655              OMulOp != e; ++OMulOp)
2656           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2657             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2658             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2659             if (Mul->getNumOperands() != 2) {
2660               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2661                                                   Mul->op_begin()+MulOp);
2662               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2663               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2664             }
2665             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2666             if (OtherMul->getNumOperands() != 2) {
2667               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2668                                                   OtherMul->op_begin()+OMulOp);
2669               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2670               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2671             }
2672             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2673             const SCEV *InnerMulSum =
2674                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2675             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2676                                               SCEV::FlagAnyWrap, Depth + 1);
2677             if (Ops.size() == 2) return OuterMul;
2678             Ops.erase(Ops.begin()+Idx);
2679             Ops.erase(Ops.begin()+OtherMulIdx-1);
2680             Ops.push_back(OuterMul);
2681             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2682           }
2683       }
2684     }
2685   }
2686 
2687   // If there are any add recurrences in the operands list, see if any other
2688   // added values are loop invariant.  If so, we can fold them into the
2689   // recurrence.
2690   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2691     ++Idx;
2692 
2693   // Scan over all recurrences, trying to fold loop invariants into them.
2694   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2695     // Scan all of the other operands to this add and add them to the vector if
2696     // they are loop invariant w.r.t. the recurrence.
2697     SmallVector<const SCEV *, 8> LIOps;
2698     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2699     const Loop *AddRecLoop = AddRec->getLoop();
2700     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2701       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2702         LIOps.push_back(Ops[i]);
2703         Ops.erase(Ops.begin()+i);
2704         --i; --e;
2705       }
2706 
2707     // If we found some loop invariants, fold them into the recurrence.
2708     if (!LIOps.empty()) {
2709       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2710       LIOps.push_back(AddRec->getStart());
2711 
2712       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2713                                              AddRec->op_end());
2714       // This follows from the fact that the no-wrap flags on the outer add
2715       // expression are applicable on the 0th iteration, when the add recurrence
2716       // will be equal to its start value.
2717       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2718 
2719       // Build the new addrec. Propagate the NUW and NSW flags if both the
2720       // outer add and the inner addrec are guaranteed to have no overflow.
2721       // Always propagate NW.
2722       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2723       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2724 
2725       // If all of the other operands were loop invariant, we are done.
2726       if (Ops.size() == 1) return NewRec;
2727 
2728       // Otherwise, add the folded AddRec by the non-invariant parts.
2729       for (unsigned i = 0;; ++i)
2730         if (Ops[i] == AddRec) {
2731           Ops[i] = NewRec;
2732           break;
2733         }
2734       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2735     }
2736 
2737     // Okay, if there weren't any loop invariants to be folded, check to see if
2738     // there are multiple AddRec's with the same loop induction variable being
2739     // added together.  If so, we can fold them.
2740     for (unsigned OtherIdx = Idx+1;
2741          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2742          ++OtherIdx) {
2743       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2744       // so that the 1st found AddRecExpr is dominated by all others.
2745       assert(DT.dominates(
2746            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2747            AddRec->getLoop()->getHeader()) &&
2748         "AddRecExprs are not sorted in reverse dominance order?");
2749       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2750         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2751         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2752                                                AddRec->op_end());
2753         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2754              ++OtherIdx) {
2755           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2756           if (OtherAddRec->getLoop() == AddRecLoop) {
2757             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2758                  i != e; ++i) {
2759               if (i >= AddRecOps.size()) {
2760                 AddRecOps.append(OtherAddRec->op_begin()+i,
2761                                  OtherAddRec->op_end());
2762                 break;
2763               }
2764               SmallVector<const SCEV *, 2> TwoOps = {
2765                   AddRecOps[i], OtherAddRec->getOperand(i)};
2766               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2767             }
2768             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2769           }
2770         }
2771         // Step size has changed, so we cannot guarantee no self-wraparound.
2772         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2773         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2774       }
2775     }
2776 
2777     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2778     // next one.
2779   }
2780 
2781   // Okay, it looks like we really DO need an add expr.  Check to see if we
2782   // already have one, otherwise create a new one.
2783   return getOrCreateAddExpr(Ops, Flags);
2784 }
2785 
2786 const SCEV *
2787 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2788                                     SCEV::NoWrapFlags Flags) {
2789   FoldingSetNodeID ID;
2790   ID.AddInteger(scAddExpr);
2791   for (const SCEV *Op : Ops)
2792     ID.AddPointer(Op);
2793   void *IP = nullptr;
2794   SCEVAddExpr *S =
2795       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2796   if (!S) {
2797     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2798     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2799     S = new (SCEVAllocator)
2800         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2801     UniqueSCEVs.InsertNode(S, IP);
2802     addToLoopUseLists(S);
2803   }
2804   S->setNoWrapFlags(Flags);
2805   return S;
2806 }
2807 
2808 const SCEV *
2809 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2810                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2811   FoldingSetNodeID ID;
2812   ID.AddInteger(scAddRecExpr);
2813   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2814     ID.AddPointer(Ops[i]);
2815   ID.AddPointer(L);
2816   void *IP = nullptr;
2817   SCEVAddRecExpr *S =
2818       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2819   if (!S) {
2820     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2821     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2822     S = new (SCEVAllocator)
2823         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2824     UniqueSCEVs.InsertNode(S, IP);
2825     addToLoopUseLists(S);
2826   }
2827   S->setNoWrapFlags(Flags);
2828   return S;
2829 }
2830 
2831 const SCEV *
2832 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2833                                     SCEV::NoWrapFlags Flags) {
2834   FoldingSetNodeID ID;
2835   ID.AddInteger(scMulExpr);
2836   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2837     ID.AddPointer(Ops[i]);
2838   void *IP = nullptr;
2839   SCEVMulExpr *S =
2840     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2841   if (!S) {
2842     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2843     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2844     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2845                                         O, Ops.size());
2846     UniqueSCEVs.InsertNode(S, IP);
2847     addToLoopUseLists(S);
2848   }
2849   S->setNoWrapFlags(Flags);
2850   return S;
2851 }
2852 
2853 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2854   uint64_t k = i*j;
2855   if (j > 1 && k / j != i) Overflow = true;
2856   return k;
2857 }
2858 
2859 /// Compute the result of "n choose k", the binomial coefficient.  If an
2860 /// intermediate computation overflows, Overflow will be set and the return will
2861 /// be garbage. Overflow is not cleared on absence of overflow.
2862 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2863   // We use the multiplicative formula:
2864   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2865   // At each iteration, we take the n-th term of the numeral and divide by the
2866   // (k-n)th term of the denominator.  This division will always produce an
2867   // integral result, and helps reduce the chance of overflow in the
2868   // intermediate computations. However, we can still overflow even when the
2869   // final result would fit.
2870 
2871   if (n == 0 || n == k) return 1;
2872   if (k > n) return 0;
2873 
2874   if (k > n/2)
2875     k = n-k;
2876 
2877   uint64_t r = 1;
2878   for (uint64_t i = 1; i <= k; ++i) {
2879     r = umul_ov(r, n-(i-1), Overflow);
2880     r /= i;
2881   }
2882   return r;
2883 }
2884 
2885 /// Determine if any of the operands in this SCEV are a constant or if
2886 /// any of the add or multiply expressions in this SCEV contain a constant.
2887 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2888   struct FindConstantInAddMulChain {
2889     bool FoundConstant = false;
2890 
2891     bool follow(const SCEV *S) {
2892       FoundConstant |= isa<SCEVConstant>(S);
2893       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2894     }
2895 
2896     bool isDone() const {
2897       return FoundConstant;
2898     }
2899   };
2900 
2901   FindConstantInAddMulChain F;
2902   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2903   ST.visitAll(StartExpr);
2904   return F.FoundConstant;
2905 }
2906 
2907 /// Get a canonical multiply expression, or something simpler if possible.
2908 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2909                                         SCEV::NoWrapFlags Flags,
2910                                         unsigned Depth) {
2911   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2912          "only nuw or nsw allowed");
2913   assert(!Ops.empty() && "Cannot get empty mul!");
2914   if (Ops.size() == 1) return Ops[0];
2915 #ifndef NDEBUG
2916   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2917   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2918     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2919            "SCEVMulExpr operand types don't match!");
2920 #endif
2921 
2922   // Sort by complexity, this groups all similar expression types together.
2923   GroupByComplexity(Ops, &LI, DT);
2924 
2925   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2926 
2927   // Limit recursion calls depth.
2928   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2929     return getOrCreateMulExpr(Ops, Flags);
2930 
2931   // If there are any constants, fold them together.
2932   unsigned Idx = 0;
2933   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2934 
2935     if (Ops.size() == 2)
2936       // C1*(C2+V) -> C1*C2 + C1*V
2937       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2938         // If any of Add's ops are Adds or Muls with a constant, apply this
2939         // transformation as well.
2940         //
2941         // TODO: There are some cases where this transformation is not
2942         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2943         // this transformation should be narrowed down.
2944         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2945           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2946                                        SCEV::FlagAnyWrap, Depth + 1),
2947                             getMulExpr(LHSC, Add->getOperand(1),
2948                                        SCEV::FlagAnyWrap, Depth + 1),
2949                             SCEV::FlagAnyWrap, Depth + 1);
2950 
2951     ++Idx;
2952     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2953       // We found two constants, fold them together!
2954       ConstantInt *Fold =
2955           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2956       Ops[0] = getConstant(Fold);
2957       Ops.erase(Ops.begin()+1);  // Erase the folded element
2958       if (Ops.size() == 1) return Ops[0];
2959       LHSC = cast<SCEVConstant>(Ops[0]);
2960     }
2961 
2962     // If we are left with a constant one being multiplied, strip it off.
2963     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2964       Ops.erase(Ops.begin());
2965       --Idx;
2966     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2967       // If we have a multiply of zero, it will always be zero.
2968       return Ops[0];
2969     } else if (Ops[0]->isAllOnesValue()) {
2970       // If we have a mul by -1 of an add, try distributing the -1 among the
2971       // add operands.
2972       if (Ops.size() == 2) {
2973         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2974           SmallVector<const SCEV *, 4> NewOps;
2975           bool AnyFolded = false;
2976           for (const SCEV *AddOp : Add->operands()) {
2977             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2978                                          Depth + 1);
2979             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2980             NewOps.push_back(Mul);
2981           }
2982           if (AnyFolded)
2983             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2984         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2985           // Negation preserves a recurrence's no self-wrap property.
2986           SmallVector<const SCEV *, 4> Operands;
2987           for (const SCEV *AddRecOp : AddRec->operands())
2988             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2989                                           Depth + 1));
2990 
2991           return getAddRecExpr(Operands, AddRec->getLoop(),
2992                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2993         }
2994       }
2995     }
2996 
2997     if (Ops.size() == 1)
2998       return Ops[0];
2999   }
3000 
3001   // Skip over the add expression until we get to a multiply.
3002   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3003     ++Idx;
3004 
3005   // If there are mul operands inline them all into this expression.
3006   if (Idx < Ops.size()) {
3007     bool DeletedMul = false;
3008     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3009       if (Ops.size() > MulOpsInlineThreshold)
3010         break;
3011       // If we have an mul, expand the mul operands onto the end of the
3012       // operands list.
3013       Ops.erase(Ops.begin()+Idx);
3014       Ops.append(Mul->op_begin(), Mul->op_end());
3015       DeletedMul = true;
3016     }
3017 
3018     // If we deleted at least one mul, we added operands to the end of the
3019     // list, and they are not necessarily sorted.  Recurse to resort and
3020     // resimplify any operands we just acquired.
3021     if (DeletedMul)
3022       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3023   }
3024 
3025   // If there are any add recurrences in the operands list, see if any other
3026   // added values are loop invariant.  If so, we can fold them into the
3027   // recurrence.
3028   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3029     ++Idx;
3030 
3031   // Scan over all recurrences, trying to fold loop invariants into them.
3032   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3033     // Scan all of the other operands to this mul and add them to the vector
3034     // if they are loop invariant w.r.t. the recurrence.
3035     SmallVector<const SCEV *, 8> LIOps;
3036     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3037     const Loop *AddRecLoop = AddRec->getLoop();
3038     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3039       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3040         LIOps.push_back(Ops[i]);
3041         Ops.erase(Ops.begin()+i);
3042         --i; --e;
3043       }
3044 
3045     // If we found some loop invariants, fold them into the recurrence.
3046     if (!LIOps.empty()) {
3047       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3048       SmallVector<const SCEV *, 4> NewOps;
3049       NewOps.reserve(AddRec->getNumOperands());
3050       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3051       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3052         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3053                                     SCEV::FlagAnyWrap, Depth + 1));
3054 
3055       // Build the new addrec. Propagate the NUW and NSW flags if both the
3056       // outer mul and the inner addrec are guaranteed to have no overflow.
3057       //
3058       // No self-wrap cannot be guaranteed after changing the step size, but
3059       // will be inferred if either NUW or NSW is true.
3060       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3061       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3062 
3063       // If all of the other operands were loop invariant, we are done.
3064       if (Ops.size() == 1) return NewRec;
3065 
3066       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3067       for (unsigned i = 0;; ++i)
3068         if (Ops[i] == AddRec) {
3069           Ops[i] = NewRec;
3070           break;
3071         }
3072       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3073     }
3074 
3075     // Okay, if there weren't any loop invariants to be folded, check to see
3076     // if there are multiple AddRec's with the same loop induction variable
3077     // being multiplied together.  If so, we can fold them.
3078 
3079     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3080     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3081     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3082     //   ]]],+,...up to x=2n}.
3083     // Note that the arguments to choose() are always integers with values
3084     // known at compile time, never SCEV objects.
3085     //
3086     // The implementation avoids pointless extra computations when the two
3087     // addrec's are of different length (mathematically, it's equivalent to
3088     // an infinite stream of zeros on the right).
3089     bool OpsModified = false;
3090     for (unsigned OtherIdx = Idx+1;
3091          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3092          ++OtherIdx) {
3093       const SCEVAddRecExpr *OtherAddRec =
3094         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3095       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3096         continue;
3097 
3098       // Limit max number of arguments to avoid creation of unreasonably big
3099       // SCEVAddRecs with very complex operands.
3100       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3101           MaxAddRecSize || isHugeExpression(AddRec) ||
3102           isHugeExpression(OtherAddRec))
3103         continue;
3104 
3105       bool Overflow = false;
3106       Type *Ty = AddRec->getType();
3107       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3108       SmallVector<const SCEV*, 7> AddRecOps;
3109       for (int x = 0, xe = AddRec->getNumOperands() +
3110              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3111         SmallVector <const SCEV *, 7> SumOps;
3112         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3113           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3114           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3115                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3116                z < ze && !Overflow; ++z) {
3117             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3118             uint64_t Coeff;
3119             if (LargerThan64Bits)
3120               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3121             else
3122               Coeff = Coeff1*Coeff2;
3123             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3124             const SCEV *Term1 = AddRec->getOperand(y-z);
3125             const SCEV *Term2 = OtherAddRec->getOperand(z);
3126             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3127                                         SCEV::FlagAnyWrap, Depth + 1));
3128           }
3129         }
3130         if (SumOps.empty())
3131           SumOps.push_back(getZero(Ty));
3132         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3133       }
3134       if (!Overflow) {
3135         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3136                                               SCEV::FlagAnyWrap);
3137         if (Ops.size() == 2) return NewAddRec;
3138         Ops[Idx] = NewAddRec;
3139         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3140         OpsModified = true;
3141         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3142         if (!AddRec)
3143           break;
3144       }
3145     }
3146     if (OpsModified)
3147       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3148 
3149     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3150     // next one.
3151   }
3152 
3153   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3154   // already have one, otherwise create a new one.
3155   return getOrCreateMulExpr(Ops, Flags);
3156 }
3157 
3158 /// Represents an unsigned remainder expression based on unsigned division.
3159 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3160                                          const SCEV *RHS) {
3161   assert(getEffectiveSCEVType(LHS->getType()) ==
3162          getEffectiveSCEVType(RHS->getType()) &&
3163          "SCEVURemExpr operand types don't match!");
3164 
3165   // Short-circuit easy cases
3166   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3167     // If constant is one, the result is trivial
3168     if (RHSC->getValue()->isOne())
3169       return getZero(LHS->getType()); // X urem 1 --> 0
3170 
3171     // If constant is a power of two, fold into a zext(trunc(LHS)).
3172     if (RHSC->getAPInt().isPowerOf2()) {
3173       Type *FullTy = LHS->getType();
3174       Type *TruncTy =
3175           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3176       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3177     }
3178   }
3179 
3180   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3181   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3182   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3183   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3184 }
3185 
3186 /// Get a canonical unsigned division expression, or something simpler if
3187 /// possible.
3188 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3189                                          const SCEV *RHS) {
3190   assert(getEffectiveSCEVType(LHS->getType()) ==
3191          getEffectiveSCEVType(RHS->getType()) &&
3192          "SCEVUDivExpr operand types don't match!");
3193 
3194   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3195     if (RHSC->getValue()->isOne())
3196       return LHS;                               // X udiv 1 --> x
3197     // If the denominator is zero, the result of the udiv is undefined. Don't
3198     // try to analyze it, because the resolution chosen here may differ from
3199     // the resolution chosen in other parts of the compiler.
3200     if (!RHSC->getValue()->isZero()) {
3201       // Determine if the division can be folded into the operands of
3202       // its operands.
3203       // TODO: Generalize this to non-constants by using known-bits information.
3204       Type *Ty = LHS->getType();
3205       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3206       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3207       // For non-power-of-two values, effectively round the value up to the
3208       // nearest power of two.
3209       if (!RHSC->getAPInt().isPowerOf2())
3210         ++MaxShiftAmt;
3211       IntegerType *ExtTy =
3212         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3213       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3214         if (const SCEVConstant *Step =
3215             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3216           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3217           const APInt &StepInt = Step->getAPInt();
3218           const APInt &DivInt = RHSC->getAPInt();
3219           if (!StepInt.urem(DivInt) &&
3220               getZeroExtendExpr(AR, ExtTy) ==
3221               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3222                             getZeroExtendExpr(Step, ExtTy),
3223                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3224             SmallVector<const SCEV *, 4> Operands;
3225             for (const SCEV *Op : AR->operands())
3226               Operands.push_back(getUDivExpr(Op, RHS));
3227             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3228           }
3229           /// Get a canonical UDivExpr for a recurrence.
3230           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3231           // We can currently only fold X%N if X is constant.
3232           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3233           if (StartC && !DivInt.urem(StepInt) &&
3234               getZeroExtendExpr(AR, ExtTy) ==
3235               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3236                             getZeroExtendExpr(Step, ExtTy),
3237                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3238             const APInt &StartInt = StartC->getAPInt();
3239             const APInt &StartRem = StartInt.urem(StepInt);
3240             if (StartRem != 0)
3241               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3242                                   AR->getLoop(), SCEV::FlagNW);
3243           }
3244         }
3245       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3246       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3247         SmallVector<const SCEV *, 4> Operands;
3248         for (const SCEV *Op : M->operands())
3249           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3250         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3251           // Find an operand that's safely divisible.
3252           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3253             const SCEV *Op = M->getOperand(i);
3254             const SCEV *Div = getUDivExpr(Op, RHSC);
3255             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3256               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3257                                                       M->op_end());
3258               Operands[i] = Div;
3259               return getMulExpr(Operands);
3260             }
3261           }
3262       }
3263 
3264       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3265       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3266         if (auto *DivisorConstant =
3267                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3268           bool Overflow = false;
3269           APInt NewRHS =
3270               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3271           if (Overflow) {
3272             return getConstant(RHSC->getType(), 0, false);
3273           }
3274           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3275         }
3276       }
3277 
3278       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3279       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3280         SmallVector<const SCEV *, 4> Operands;
3281         for (const SCEV *Op : A->operands())
3282           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3283         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3284           Operands.clear();
3285           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3286             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3287             if (isa<SCEVUDivExpr>(Op) ||
3288                 getMulExpr(Op, RHS) != A->getOperand(i))
3289               break;
3290             Operands.push_back(Op);
3291           }
3292           if (Operands.size() == A->getNumOperands())
3293             return getAddExpr(Operands);
3294         }
3295       }
3296 
3297       // Fold if both operands are constant.
3298       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3299         Constant *LHSCV = LHSC->getValue();
3300         Constant *RHSCV = RHSC->getValue();
3301         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3302                                                                    RHSCV)));
3303       }
3304     }
3305   }
3306 
3307   FoldingSetNodeID ID;
3308   ID.AddInteger(scUDivExpr);
3309   ID.AddPointer(LHS);
3310   ID.AddPointer(RHS);
3311   void *IP = nullptr;
3312   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3313   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3314                                              LHS, RHS);
3315   UniqueSCEVs.InsertNode(S, IP);
3316   addToLoopUseLists(S);
3317   return S;
3318 }
3319 
3320 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3321   APInt A = C1->getAPInt().abs();
3322   APInt B = C2->getAPInt().abs();
3323   uint32_t ABW = A.getBitWidth();
3324   uint32_t BBW = B.getBitWidth();
3325 
3326   if (ABW > BBW)
3327     B = B.zext(ABW);
3328   else if (ABW < BBW)
3329     A = A.zext(BBW);
3330 
3331   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3332 }
3333 
3334 /// Get a canonical unsigned division expression, or something simpler if
3335 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3336 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3337 /// it's not exact because the udiv may be clearing bits.
3338 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3339                                               const SCEV *RHS) {
3340   // TODO: we could try to find factors in all sorts of things, but for now we
3341   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3342   // end of this file for inspiration.
3343 
3344   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3345   if (!Mul || !Mul->hasNoUnsignedWrap())
3346     return getUDivExpr(LHS, RHS);
3347 
3348   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3349     // If the mulexpr multiplies by a constant, then that constant must be the
3350     // first element of the mulexpr.
3351     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3352       if (LHSCst == RHSCst) {
3353         SmallVector<const SCEV *, 2> Operands;
3354         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3355         return getMulExpr(Operands);
3356       }
3357 
3358       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3359       // that there's a factor provided by one of the other terms. We need to
3360       // check.
3361       APInt Factor = gcd(LHSCst, RHSCst);
3362       if (!Factor.isIntN(1)) {
3363         LHSCst =
3364             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3365         RHSCst =
3366             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3367         SmallVector<const SCEV *, 2> Operands;
3368         Operands.push_back(LHSCst);
3369         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3370         LHS = getMulExpr(Operands);
3371         RHS = RHSCst;
3372         Mul = dyn_cast<SCEVMulExpr>(LHS);
3373         if (!Mul)
3374           return getUDivExactExpr(LHS, RHS);
3375       }
3376     }
3377   }
3378 
3379   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3380     if (Mul->getOperand(i) == RHS) {
3381       SmallVector<const SCEV *, 2> Operands;
3382       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3383       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3384       return getMulExpr(Operands);
3385     }
3386   }
3387 
3388   return getUDivExpr(LHS, RHS);
3389 }
3390 
3391 /// Get an add recurrence expression for the specified loop.  Simplify the
3392 /// expression as much as possible.
3393 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3394                                            const Loop *L,
3395                                            SCEV::NoWrapFlags Flags) {
3396   SmallVector<const SCEV *, 4> Operands;
3397   Operands.push_back(Start);
3398   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3399     if (StepChrec->getLoop() == L) {
3400       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3401       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3402     }
3403 
3404   Operands.push_back(Step);
3405   return getAddRecExpr(Operands, L, Flags);
3406 }
3407 
3408 /// Get an add recurrence expression for the specified loop.  Simplify the
3409 /// expression as much as possible.
3410 const SCEV *
3411 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3412                                const Loop *L, SCEV::NoWrapFlags Flags) {
3413   if (Operands.size() == 1) return Operands[0];
3414 #ifndef NDEBUG
3415   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3416   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3417     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3418            "SCEVAddRecExpr operand types don't match!");
3419   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3420     assert(isLoopInvariant(Operands[i], L) &&
3421            "SCEVAddRecExpr operand is not loop-invariant!");
3422 #endif
3423 
3424   if (Operands.back()->isZero()) {
3425     Operands.pop_back();
3426     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3427   }
3428 
3429   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3430   // use that information to infer NUW and NSW flags. However, computing a
3431   // BE count requires calling getAddRecExpr, so we may not yet have a
3432   // meaningful BE count at this point (and if we don't, we'd be stuck
3433   // with a SCEVCouldNotCompute as the cached BE count).
3434 
3435   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3436 
3437   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3438   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3439     const Loop *NestedLoop = NestedAR->getLoop();
3440     if (L->contains(NestedLoop)
3441             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3442             : (!NestedLoop->contains(L) &&
3443                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3444       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3445                                                   NestedAR->op_end());
3446       Operands[0] = NestedAR->getStart();
3447       // AddRecs require their operands be loop-invariant with respect to their
3448       // loops. Don't perform this transformation if it would break this
3449       // requirement.
3450       bool AllInvariant = all_of(
3451           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3452 
3453       if (AllInvariant) {
3454         // Create a recurrence for the outer loop with the same step size.
3455         //
3456         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3457         // inner recurrence has the same property.
3458         SCEV::NoWrapFlags OuterFlags =
3459           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3460 
3461         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3462         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3463           return isLoopInvariant(Op, NestedLoop);
3464         });
3465 
3466         if (AllInvariant) {
3467           // Ok, both add recurrences are valid after the transformation.
3468           //
3469           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3470           // the outer recurrence has the same property.
3471           SCEV::NoWrapFlags InnerFlags =
3472             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3473           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3474         }
3475       }
3476       // Reset Operands to its original state.
3477       Operands[0] = NestedAR;
3478     }
3479   }
3480 
3481   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3482   // already have one, otherwise create a new one.
3483   return getOrCreateAddRecExpr(Operands, L, Flags);
3484 }
3485 
3486 const SCEV *
3487 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3488                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3489   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3490   // getSCEV(Base)->getType() has the same address space as Base->getType()
3491   // because SCEV::getType() preserves the address space.
3492   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3493   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3494   // instruction to its SCEV, because the Instruction may be guarded by control
3495   // flow and the no-overflow bits may not be valid for the expression in any
3496   // context. This can be fixed similarly to how these flags are handled for
3497   // adds.
3498   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3499                                              : SCEV::FlagAnyWrap;
3500 
3501   const SCEV *TotalOffset = getZero(IntPtrTy);
3502   // The array size is unimportant. The first thing we do on CurTy is getting
3503   // its element type.
3504   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3505   for (const SCEV *IndexExpr : IndexExprs) {
3506     // Compute the (potentially symbolic) offset in bytes for this index.
3507     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3508       // For a struct, add the member offset.
3509       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3510       unsigned FieldNo = Index->getZExtValue();
3511       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3512 
3513       // Add the field offset to the running total offset.
3514       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3515 
3516       // Update CurTy to the type of the field at Index.
3517       CurTy = STy->getTypeAtIndex(Index);
3518     } else {
3519       // Update CurTy to its element type.
3520       CurTy = cast<SequentialType>(CurTy)->getElementType();
3521       // For an array, add the element offset, explicitly scaled.
3522       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3523       // Getelementptr indices are signed.
3524       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3525 
3526       // Multiply the index by the element size to compute the element offset.
3527       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3528 
3529       // Add the element offset to the running total offset.
3530       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3531     }
3532   }
3533 
3534   // Add the total offset from all the GEP indices to the base.
3535   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3536 }
3537 
3538 std::tuple<const SCEV *, FoldingSetNodeID, void *>
3539 ScalarEvolution::findExistingSCEVInCache(int SCEVType,
3540                                          ArrayRef<const SCEV *> Ops) {
3541   FoldingSetNodeID ID;
3542   void *IP = nullptr;
3543   ID.AddInteger(SCEVType);
3544   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3545     ID.AddPointer(Ops[i]);
3546   return std::tuple<const SCEV *, FoldingSetNodeID, void *>(
3547       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3548 }
3549 
3550 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind,
3551                                            SmallVectorImpl<const SCEV *> &Ops) {
3552   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3553   if (Ops.size() == 1) return Ops[0];
3554 #ifndef NDEBUG
3555   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3556   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3557     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3558            "Operand types don't match!");
3559 #endif
3560 
3561   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3562   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3563 
3564   // Sort by complexity, this groups all similar expression types together.
3565   GroupByComplexity(Ops, &LI, DT);
3566 
3567   // Check if we have created the same expression before.
3568   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3569     return S;
3570   }
3571 
3572   // If there are any constants, fold them together.
3573   unsigned Idx = 0;
3574   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3575     ++Idx;
3576     assert(Idx < Ops.size());
3577     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3578       if (Kind == scSMaxExpr)
3579         return APIntOps::smax(LHS, RHS);
3580       else if (Kind == scSMinExpr)
3581         return APIntOps::smin(LHS, RHS);
3582       else if (Kind == scUMaxExpr)
3583         return APIntOps::umax(LHS, RHS);
3584       else if (Kind == scUMinExpr)
3585         return APIntOps::umin(LHS, RHS);
3586       llvm_unreachable("Unknown SCEV min/max opcode");
3587     };
3588 
3589     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3590       // We found two constants, fold them together!
3591       ConstantInt *Fold = ConstantInt::get(
3592           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3593       Ops[0] = getConstant(Fold);
3594       Ops.erase(Ops.begin()+1);  // Erase the folded element
3595       if (Ops.size() == 1) return Ops[0];
3596       LHSC = cast<SCEVConstant>(Ops[0]);
3597     }
3598 
3599     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3600     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3601 
3602     if (IsMax ? IsMinV : IsMaxV) {
3603       // If we are left with a constant minimum(/maximum)-int, strip it off.
3604       Ops.erase(Ops.begin());
3605       --Idx;
3606     } else if (IsMax ? IsMaxV : IsMinV) {
3607       // If we have a max(/min) with a constant maximum(/minimum)-int,
3608       // it will always be the extremum.
3609       return LHSC;
3610     }
3611 
3612     if (Ops.size() == 1) return Ops[0];
3613   }
3614 
3615   // Find the first operation of the same kind
3616   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3617     ++Idx;
3618 
3619   // Check to see if one of the operands is of the same kind. If so, expand its
3620   // operands onto our operand list, and recurse to simplify.
3621   if (Idx < Ops.size()) {
3622     bool DeletedAny = false;
3623     while (Ops[Idx]->getSCEVType() == Kind) {
3624       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3625       Ops.erase(Ops.begin()+Idx);
3626       Ops.append(SMME->op_begin(), SMME->op_end());
3627       DeletedAny = true;
3628     }
3629 
3630     if (DeletedAny)
3631       return getMinMaxExpr(Kind, Ops);
3632   }
3633 
3634   // Okay, check to see if the same value occurs in the operand list twice.  If
3635   // so, delete one.  Since we sorted the list, these values are required to
3636   // be adjacent.
3637   llvm::CmpInst::Predicate GEPred =
3638       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3639   llvm::CmpInst::Predicate LEPred =
3640       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3641   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3642   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3643   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3644     if (Ops[i] == Ops[i + 1] ||
3645         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3646       //  X op Y op Y  -->  X op Y
3647       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3648       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3649       --i;
3650       --e;
3651     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3652                                                Ops[i + 1])) {
3653       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3654       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3655       --i;
3656       --e;
3657     }
3658   }
3659 
3660   if (Ops.size() == 1) return Ops[0];
3661 
3662   assert(!Ops.empty() && "Reduced smax down to nothing!");
3663 
3664   // Okay, it looks like we really DO need an expr.  Check to see if we
3665   // already have one, otherwise create a new one.
3666   const SCEV *ExistingSCEV;
3667   FoldingSetNodeID ID;
3668   void *IP;
3669   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3670   if (ExistingSCEV)
3671     return ExistingSCEV;
3672   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3673   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3674   SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr(
3675       ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size());
3676 
3677   UniqueSCEVs.InsertNode(S, IP);
3678   addToLoopUseLists(S);
3679   return S;
3680 }
3681 
3682 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3683   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3684   return getSMaxExpr(Ops);
3685 }
3686 
3687 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3688   return getMinMaxExpr(scSMaxExpr, Ops);
3689 }
3690 
3691 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3692   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3693   return getUMaxExpr(Ops);
3694 }
3695 
3696 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3697   return getMinMaxExpr(scUMaxExpr, Ops);
3698 }
3699 
3700 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3701                                          const SCEV *RHS) {
3702   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3703   return getSMinExpr(Ops);
3704 }
3705 
3706 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3707   return getMinMaxExpr(scSMinExpr, Ops);
3708 }
3709 
3710 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3711                                          const SCEV *RHS) {
3712   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3713   return getUMinExpr(Ops);
3714 }
3715 
3716 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3717   return getMinMaxExpr(scUMinExpr, Ops);
3718 }
3719 
3720 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3721   // We can bypass creating a target-independent
3722   // constant expression and then folding it back into a ConstantInt.
3723   // This is just a compile-time optimization.
3724   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3725 }
3726 
3727 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3728                                              StructType *STy,
3729                                              unsigned FieldNo) {
3730   // We can bypass creating a target-independent
3731   // constant expression and then folding it back into a ConstantInt.
3732   // This is just a compile-time optimization.
3733   return getConstant(
3734       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3735 }
3736 
3737 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3738   // Don't attempt to do anything other than create a SCEVUnknown object
3739   // here.  createSCEV only calls getUnknown after checking for all other
3740   // interesting possibilities, and any other code that calls getUnknown
3741   // is doing so in order to hide a value from SCEV canonicalization.
3742 
3743   FoldingSetNodeID ID;
3744   ID.AddInteger(scUnknown);
3745   ID.AddPointer(V);
3746   void *IP = nullptr;
3747   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3748     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3749            "Stale SCEVUnknown in uniquing map!");
3750     return S;
3751   }
3752   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3753                                             FirstUnknown);
3754   FirstUnknown = cast<SCEVUnknown>(S);
3755   UniqueSCEVs.InsertNode(S, IP);
3756   return S;
3757 }
3758 
3759 //===----------------------------------------------------------------------===//
3760 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3761 //
3762 
3763 /// Test if values of the given type are analyzable within the SCEV
3764 /// framework. This primarily includes integer types, and it can optionally
3765 /// include pointer types if the ScalarEvolution class has access to
3766 /// target-specific information.
3767 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3768   // Integers and pointers are always SCEVable.
3769   return Ty->isIntOrPtrTy();
3770 }
3771 
3772 /// Return the size in bits of the specified type, for which isSCEVable must
3773 /// return true.
3774 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3775   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3776   if (Ty->isPointerTy())
3777     return getDataLayout().getIndexTypeSizeInBits(Ty);
3778   return getDataLayout().getTypeSizeInBits(Ty);
3779 }
3780 
3781 /// Return a type with the same bitwidth as the given type and which represents
3782 /// how SCEV will treat the given type, for which isSCEVable must return
3783 /// true. For pointer types, this is the pointer-sized integer type.
3784 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3785   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3786 
3787   if (Ty->isIntegerTy())
3788     return Ty;
3789 
3790   // The only other support type is pointer.
3791   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3792   return getDataLayout().getIntPtrType(Ty);
3793 }
3794 
3795 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3796   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3797 }
3798 
3799 const SCEV *ScalarEvolution::getCouldNotCompute() {
3800   return CouldNotCompute.get();
3801 }
3802 
3803 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3804   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3805     auto *SU = dyn_cast<SCEVUnknown>(S);
3806     return SU && SU->getValue() == nullptr;
3807   });
3808 
3809   return !ContainsNulls;
3810 }
3811 
3812 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3813   HasRecMapType::iterator I = HasRecMap.find(S);
3814   if (I != HasRecMap.end())
3815     return I->second;
3816 
3817   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3818   HasRecMap.insert({S, FoundAddRec});
3819   return FoundAddRec;
3820 }
3821 
3822 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3823 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3824 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3825 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3826   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3827   if (!Add)
3828     return {S, nullptr};
3829 
3830   if (Add->getNumOperands() != 2)
3831     return {S, nullptr};
3832 
3833   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3834   if (!ConstOp)
3835     return {S, nullptr};
3836 
3837   return {Add->getOperand(1), ConstOp->getValue()};
3838 }
3839 
3840 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3841 /// by the value and offset from any ValueOffsetPair in the set.
3842 SetVector<ScalarEvolution::ValueOffsetPair> *
3843 ScalarEvolution::getSCEVValues(const SCEV *S) {
3844   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3845   if (SI == ExprValueMap.end())
3846     return nullptr;
3847 #ifndef NDEBUG
3848   if (VerifySCEVMap) {
3849     // Check there is no dangling Value in the set returned.
3850     for (const auto &VE : SI->second)
3851       assert(ValueExprMap.count(VE.first));
3852   }
3853 #endif
3854   return &SI->second;
3855 }
3856 
3857 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3858 /// cannot be used separately. eraseValueFromMap should be used to remove
3859 /// V from ValueExprMap and ExprValueMap at the same time.
3860 void ScalarEvolution::eraseValueFromMap(Value *V) {
3861   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3862   if (I != ValueExprMap.end()) {
3863     const SCEV *S = I->second;
3864     // Remove {V, 0} from the set of ExprValueMap[S]
3865     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3866       SV->remove({V, nullptr});
3867 
3868     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3869     const SCEV *Stripped;
3870     ConstantInt *Offset;
3871     std::tie(Stripped, Offset) = splitAddExpr(S);
3872     if (Offset != nullptr) {
3873       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3874         SV->remove({V, Offset});
3875     }
3876     ValueExprMap.erase(V);
3877   }
3878 }
3879 
3880 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3881 /// TODO: In reality it is better to check the poison recursively
3882 /// but this is better than nothing.
3883 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3884   if (auto *I = dyn_cast<Instruction>(V)) {
3885     if (isa<OverflowingBinaryOperator>(I)) {
3886       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3887         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3888           return true;
3889         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3890           return true;
3891       }
3892     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3893       return true;
3894   }
3895   return false;
3896 }
3897 
3898 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3899 /// create a new one.
3900 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3901   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3902 
3903   const SCEV *S = getExistingSCEV(V);
3904   if (S == nullptr) {
3905     S = createSCEV(V);
3906     // During PHI resolution, it is possible to create two SCEVs for the same
3907     // V, so it is needed to double check whether V->S is inserted into
3908     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3909     std::pair<ValueExprMapType::iterator, bool> Pair =
3910         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3911     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3912       ExprValueMap[S].insert({V, nullptr});
3913 
3914       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3915       // ExprValueMap.
3916       const SCEV *Stripped = S;
3917       ConstantInt *Offset = nullptr;
3918       std::tie(Stripped, Offset) = splitAddExpr(S);
3919       // If stripped is SCEVUnknown, don't bother to save
3920       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3921       // increase the complexity of the expansion code.
3922       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3923       // because it may generate add/sub instead of GEP in SCEV expansion.
3924       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3925           !isa<GetElementPtrInst>(V))
3926         ExprValueMap[Stripped].insert({V, Offset});
3927     }
3928   }
3929   return S;
3930 }
3931 
3932 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3933   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3934 
3935   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3936   if (I != ValueExprMap.end()) {
3937     const SCEV *S = I->second;
3938     if (checkValidity(S))
3939       return S;
3940     eraseValueFromMap(V);
3941     forgetMemoizedResults(S);
3942   }
3943   return nullptr;
3944 }
3945 
3946 /// Return a SCEV corresponding to -V = -1*V
3947 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3948                                              SCEV::NoWrapFlags Flags) {
3949   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3950     return getConstant(
3951                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3952 
3953   Type *Ty = V->getType();
3954   Ty = getEffectiveSCEVType(Ty);
3955   return getMulExpr(
3956       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3957 }
3958 
3959 /// If Expr computes ~A, return A else return nullptr
3960 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3961   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3962   if (!Add || Add->getNumOperands() != 2 ||
3963       !Add->getOperand(0)->isAllOnesValue())
3964     return nullptr;
3965 
3966   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3967   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3968       !AddRHS->getOperand(0)->isAllOnesValue())
3969     return nullptr;
3970 
3971   return AddRHS->getOperand(1);
3972 }
3973 
3974 /// Return a SCEV corresponding to ~V = -1-V
3975 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3976   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3977     return getConstant(
3978                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3979 
3980   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3981   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3982     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3983       SmallVector<const SCEV *, 2> MatchedOperands;
3984       for (const SCEV *Operand : MME->operands()) {
3985         const SCEV *Matched = MatchNotExpr(Operand);
3986         if (!Matched)
3987           return (const SCEV *)nullptr;
3988         MatchedOperands.push_back(Matched);
3989       }
3990       return getMinMaxExpr(
3991           SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())),
3992           MatchedOperands);
3993     };
3994     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3995       return Replaced;
3996   }
3997 
3998   Type *Ty = V->getType();
3999   Ty = getEffectiveSCEVType(Ty);
4000   const SCEV *AllOnes =
4001                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
4002   return getMinusSCEV(AllOnes, V);
4003 }
4004 
4005 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4006                                           SCEV::NoWrapFlags Flags,
4007                                           unsigned Depth) {
4008   // Fast path: X - X --> 0.
4009   if (LHS == RHS)
4010     return getZero(LHS->getType());
4011 
4012   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4013   // makes it so that we cannot make much use of NUW.
4014   auto AddFlags = SCEV::FlagAnyWrap;
4015   const bool RHSIsNotMinSigned =
4016       !getSignedRangeMin(RHS).isMinSignedValue();
4017   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4018     // Let M be the minimum representable signed value. Then (-1)*RHS
4019     // signed-wraps if and only if RHS is M. That can happen even for
4020     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4021     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4022     // (-1)*RHS, we need to prove that RHS != M.
4023     //
4024     // If LHS is non-negative and we know that LHS - RHS does not
4025     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4026     // either by proving that RHS > M or that LHS >= 0.
4027     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4028       AddFlags = SCEV::FlagNSW;
4029     }
4030   }
4031 
4032   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4033   // RHS is NSW and LHS >= 0.
4034   //
4035   // The difficulty here is that the NSW flag may have been proven
4036   // relative to a loop that is to be found in a recurrence in LHS and
4037   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4038   // larger scope than intended.
4039   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4040 
4041   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4042 }
4043 
4044 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4045                                                      unsigned Depth) {
4046   Type *SrcTy = V->getType();
4047   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4048          "Cannot truncate or zero extend with non-integer arguments!");
4049   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4050     return V;  // No conversion
4051   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4052     return getTruncateExpr(V, Ty, Depth);
4053   return getZeroExtendExpr(V, Ty, Depth);
4054 }
4055 
4056 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4057                                                      unsigned Depth) {
4058   Type *SrcTy = V->getType();
4059   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4060          "Cannot truncate or zero extend with non-integer arguments!");
4061   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4062     return V;  // No conversion
4063   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4064     return getTruncateExpr(V, Ty, Depth);
4065   return getSignExtendExpr(V, Ty, Depth);
4066 }
4067 
4068 const SCEV *
4069 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4070   Type *SrcTy = V->getType();
4071   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4072          "Cannot noop or zero extend with non-integer arguments!");
4073   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4074          "getNoopOrZeroExtend cannot truncate!");
4075   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4076     return V;  // No conversion
4077   return getZeroExtendExpr(V, Ty);
4078 }
4079 
4080 const SCEV *
4081 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4082   Type *SrcTy = V->getType();
4083   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4084          "Cannot noop or sign extend with non-integer arguments!");
4085   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4086          "getNoopOrSignExtend cannot truncate!");
4087   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4088     return V;  // No conversion
4089   return getSignExtendExpr(V, Ty);
4090 }
4091 
4092 const SCEV *
4093 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4094   Type *SrcTy = V->getType();
4095   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4096          "Cannot noop or any extend with non-integer arguments!");
4097   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4098          "getNoopOrAnyExtend cannot truncate!");
4099   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4100     return V;  // No conversion
4101   return getAnyExtendExpr(V, Ty);
4102 }
4103 
4104 const SCEV *
4105 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4106   Type *SrcTy = V->getType();
4107   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4108          "Cannot truncate or noop with non-integer arguments!");
4109   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4110          "getTruncateOrNoop cannot extend!");
4111   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4112     return V;  // No conversion
4113   return getTruncateExpr(V, Ty);
4114 }
4115 
4116 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4117                                                         const SCEV *RHS) {
4118   const SCEV *PromotedLHS = LHS;
4119   const SCEV *PromotedRHS = RHS;
4120 
4121   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4122     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4123   else
4124     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4125 
4126   return getUMaxExpr(PromotedLHS, PromotedRHS);
4127 }
4128 
4129 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4130                                                         const SCEV *RHS) {
4131   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4132   return getUMinFromMismatchedTypes(Ops);
4133 }
4134 
4135 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4136     SmallVectorImpl<const SCEV *> &Ops) {
4137   assert(!Ops.empty() && "At least one operand must be!");
4138   // Trivial case.
4139   if (Ops.size() == 1)
4140     return Ops[0];
4141 
4142   // Find the max type first.
4143   Type *MaxType = nullptr;
4144   for (auto *S : Ops)
4145     if (MaxType)
4146       MaxType = getWiderType(MaxType, S->getType());
4147     else
4148       MaxType = S->getType();
4149 
4150   // Extend all ops to max type.
4151   SmallVector<const SCEV *, 2> PromotedOps;
4152   for (auto *S : Ops)
4153     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4154 
4155   // Generate umin.
4156   return getUMinExpr(PromotedOps);
4157 }
4158 
4159 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4160   // A pointer operand may evaluate to a nonpointer expression, such as null.
4161   if (!V->getType()->isPointerTy())
4162     return V;
4163 
4164   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4165     return getPointerBase(Cast->getOperand());
4166   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4167     const SCEV *PtrOp = nullptr;
4168     for (const SCEV *NAryOp : NAry->operands()) {
4169       if (NAryOp->getType()->isPointerTy()) {
4170         // Cannot find the base of an expression with multiple pointer operands.
4171         if (PtrOp)
4172           return V;
4173         PtrOp = NAryOp;
4174       }
4175     }
4176     if (!PtrOp)
4177       return V;
4178     return getPointerBase(PtrOp);
4179   }
4180   return V;
4181 }
4182 
4183 /// Push users of the given Instruction onto the given Worklist.
4184 static void
4185 PushDefUseChildren(Instruction *I,
4186                    SmallVectorImpl<Instruction *> &Worklist) {
4187   // Push the def-use children onto the Worklist stack.
4188   for (User *U : I->users())
4189     Worklist.push_back(cast<Instruction>(U));
4190 }
4191 
4192 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4193   SmallVector<Instruction *, 16> Worklist;
4194   PushDefUseChildren(PN, Worklist);
4195 
4196   SmallPtrSet<Instruction *, 8> Visited;
4197   Visited.insert(PN);
4198   while (!Worklist.empty()) {
4199     Instruction *I = Worklist.pop_back_val();
4200     if (!Visited.insert(I).second)
4201       continue;
4202 
4203     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4204     if (It != ValueExprMap.end()) {
4205       const SCEV *Old = It->second;
4206 
4207       // Short-circuit the def-use traversal if the symbolic name
4208       // ceases to appear in expressions.
4209       if (Old != SymName && !hasOperand(Old, SymName))
4210         continue;
4211 
4212       // SCEVUnknown for a PHI either means that it has an unrecognized
4213       // structure, it's a PHI that's in the progress of being computed
4214       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4215       // additional loop trip count information isn't going to change anything.
4216       // In the second case, createNodeForPHI will perform the necessary
4217       // updates on its own when it gets to that point. In the third, we do
4218       // want to forget the SCEVUnknown.
4219       if (!isa<PHINode>(I) ||
4220           !isa<SCEVUnknown>(Old) ||
4221           (I != PN && Old == SymName)) {
4222         eraseValueFromMap(It->first);
4223         forgetMemoizedResults(Old);
4224       }
4225     }
4226 
4227     PushDefUseChildren(I, Worklist);
4228   }
4229 }
4230 
4231 namespace {
4232 
4233 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4234 /// expression in case its Loop is L. If it is not L then
4235 /// if IgnoreOtherLoops is true then use AddRec itself
4236 /// otherwise rewrite cannot be done.
4237 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4238 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4239 public:
4240   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4241                              bool IgnoreOtherLoops = true) {
4242     SCEVInitRewriter Rewriter(L, SE);
4243     const SCEV *Result = Rewriter.visit(S);
4244     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4245       return SE.getCouldNotCompute();
4246     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4247                ? SE.getCouldNotCompute()
4248                : Result;
4249   }
4250 
4251   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4252     if (!SE.isLoopInvariant(Expr, L))
4253       SeenLoopVariantSCEVUnknown = true;
4254     return Expr;
4255   }
4256 
4257   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4258     // Only re-write AddRecExprs for this loop.
4259     if (Expr->getLoop() == L)
4260       return Expr->getStart();
4261     SeenOtherLoops = true;
4262     return Expr;
4263   }
4264 
4265   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4266 
4267   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4268 
4269 private:
4270   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4271       : SCEVRewriteVisitor(SE), L(L) {}
4272 
4273   const Loop *L;
4274   bool SeenLoopVariantSCEVUnknown = false;
4275   bool SeenOtherLoops = false;
4276 };
4277 
4278 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4279 /// increment expression in case its Loop is L. If it is not L then
4280 /// use AddRec itself.
4281 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4282 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4283 public:
4284   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4285     SCEVPostIncRewriter Rewriter(L, SE);
4286     const SCEV *Result = Rewriter.visit(S);
4287     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4288         ? SE.getCouldNotCompute()
4289         : Result;
4290   }
4291 
4292   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4293     if (!SE.isLoopInvariant(Expr, L))
4294       SeenLoopVariantSCEVUnknown = true;
4295     return Expr;
4296   }
4297 
4298   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4299     // Only re-write AddRecExprs for this loop.
4300     if (Expr->getLoop() == L)
4301       return Expr->getPostIncExpr(SE);
4302     SeenOtherLoops = true;
4303     return Expr;
4304   }
4305 
4306   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4307 
4308   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4309 
4310 private:
4311   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4312       : SCEVRewriteVisitor(SE), L(L) {}
4313 
4314   const Loop *L;
4315   bool SeenLoopVariantSCEVUnknown = false;
4316   bool SeenOtherLoops = false;
4317 };
4318 
4319 /// This class evaluates the compare condition by matching it against the
4320 /// condition of loop latch. If there is a match we assume a true value
4321 /// for the condition while building SCEV nodes.
4322 class SCEVBackedgeConditionFolder
4323     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4324 public:
4325   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4326                              ScalarEvolution &SE) {
4327     bool IsPosBECond = false;
4328     Value *BECond = nullptr;
4329     if (BasicBlock *Latch = L->getLoopLatch()) {
4330       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4331       if (BI && BI->isConditional()) {
4332         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4333                "Both outgoing branches should not target same header!");
4334         BECond = BI->getCondition();
4335         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4336       } else {
4337         return S;
4338       }
4339     }
4340     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4341     return Rewriter.visit(S);
4342   }
4343 
4344   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4345     const SCEV *Result = Expr;
4346     bool InvariantF = SE.isLoopInvariant(Expr, L);
4347 
4348     if (!InvariantF) {
4349       Instruction *I = cast<Instruction>(Expr->getValue());
4350       switch (I->getOpcode()) {
4351       case Instruction::Select: {
4352         SelectInst *SI = cast<SelectInst>(I);
4353         Optional<const SCEV *> Res =
4354             compareWithBackedgeCondition(SI->getCondition());
4355         if (Res.hasValue()) {
4356           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4357           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4358         }
4359         break;
4360       }
4361       default: {
4362         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4363         if (Res.hasValue())
4364           Result = Res.getValue();
4365         break;
4366       }
4367       }
4368     }
4369     return Result;
4370   }
4371 
4372 private:
4373   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4374                                        bool IsPosBECond, ScalarEvolution &SE)
4375       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4376         IsPositiveBECond(IsPosBECond) {}
4377 
4378   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4379 
4380   const Loop *L;
4381   /// Loop back condition.
4382   Value *BackedgeCond = nullptr;
4383   /// Set to true if loop back is on positive branch condition.
4384   bool IsPositiveBECond;
4385 };
4386 
4387 Optional<const SCEV *>
4388 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4389 
4390   // If value matches the backedge condition for loop latch,
4391   // then return a constant evolution node based on loopback
4392   // branch taken.
4393   if (BackedgeCond == IC)
4394     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4395                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4396   return None;
4397 }
4398 
4399 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4400 public:
4401   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4402                              ScalarEvolution &SE) {
4403     SCEVShiftRewriter Rewriter(L, SE);
4404     const SCEV *Result = Rewriter.visit(S);
4405     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4406   }
4407 
4408   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4409     // Only allow AddRecExprs for this loop.
4410     if (!SE.isLoopInvariant(Expr, L))
4411       Valid = false;
4412     return Expr;
4413   }
4414 
4415   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4416     if (Expr->getLoop() == L && Expr->isAffine())
4417       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4418     Valid = false;
4419     return Expr;
4420   }
4421 
4422   bool isValid() { return Valid; }
4423 
4424 private:
4425   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4426       : SCEVRewriteVisitor(SE), L(L) {}
4427 
4428   const Loop *L;
4429   bool Valid = true;
4430 };
4431 
4432 } // end anonymous namespace
4433 
4434 SCEV::NoWrapFlags
4435 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4436   if (!AR->isAffine())
4437     return SCEV::FlagAnyWrap;
4438 
4439   using OBO = OverflowingBinaryOperator;
4440 
4441   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4442 
4443   if (!AR->hasNoSignedWrap()) {
4444     ConstantRange AddRecRange = getSignedRange(AR);
4445     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4446 
4447     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4448         Instruction::Add, IncRange, OBO::NoSignedWrap);
4449     if (NSWRegion.contains(AddRecRange))
4450       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4451   }
4452 
4453   if (!AR->hasNoUnsignedWrap()) {
4454     ConstantRange AddRecRange = getUnsignedRange(AR);
4455     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4456 
4457     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4458         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4459     if (NUWRegion.contains(AddRecRange))
4460       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4461   }
4462 
4463   return Result;
4464 }
4465 
4466 namespace {
4467 
4468 /// Represents an abstract binary operation.  This may exist as a
4469 /// normal instruction or constant expression, or may have been
4470 /// derived from an expression tree.
4471 struct BinaryOp {
4472   unsigned Opcode;
4473   Value *LHS;
4474   Value *RHS;
4475   bool IsNSW = false;
4476   bool IsNUW = false;
4477 
4478   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4479   /// constant expression.
4480   Operator *Op = nullptr;
4481 
4482   explicit BinaryOp(Operator *Op)
4483       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4484         Op(Op) {
4485     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4486       IsNSW = OBO->hasNoSignedWrap();
4487       IsNUW = OBO->hasNoUnsignedWrap();
4488     }
4489   }
4490 
4491   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4492                     bool IsNUW = false)
4493       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4494 };
4495 
4496 } // end anonymous namespace
4497 
4498 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4499 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4500   auto *Op = dyn_cast<Operator>(V);
4501   if (!Op)
4502     return None;
4503 
4504   // Implementation detail: all the cleverness here should happen without
4505   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4506   // SCEV expressions when possible, and we should not break that.
4507 
4508   switch (Op->getOpcode()) {
4509   case Instruction::Add:
4510   case Instruction::Sub:
4511   case Instruction::Mul:
4512   case Instruction::UDiv:
4513   case Instruction::URem:
4514   case Instruction::And:
4515   case Instruction::Or:
4516   case Instruction::AShr:
4517   case Instruction::Shl:
4518     return BinaryOp(Op);
4519 
4520   case Instruction::Xor:
4521     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4522       // If the RHS of the xor is a signmask, then this is just an add.
4523       // Instcombine turns add of signmask into xor as a strength reduction step.
4524       if (RHSC->getValue().isSignMask())
4525         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4526     return BinaryOp(Op);
4527 
4528   case Instruction::LShr:
4529     // Turn logical shift right of a constant into a unsigned divide.
4530     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4531       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4532 
4533       // If the shift count is not less than the bitwidth, the result of
4534       // the shift is undefined. Don't try to analyze it, because the
4535       // resolution chosen here may differ from the resolution chosen in
4536       // other parts of the compiler.
4537       if (SA->getValue().ult(BitWidth)) {
4538         Constant *X =
4539             ConstantInt::get(SA->getContext(),
4540                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4541         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4542       }
4543     }
4544     return BinaryOp(Op);
4545 
4546   case Instruction::ExtractValue: {
4547     auto *EVI = cast<ExtractValueInst>(Op);
4548     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4549       break;
4550 
4551     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4552     if (!WO)
4553       break;
4554 
4555     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4556     bool Signed = WO->isSigned();
4557     // TODO: Should add nuw/nsw flags for mul as well.
4558     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4559       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4560 
4561     // Now that we know that all uses of the arithmetic-result component of
4562     // CI are guarded by the overflow check, we can go ahead and pretend
4563     // that the arithmetic is non-overflowing.
4564     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4565                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4566   }
4567 
4568   default:
4569     break;
4570   }
4571 
4572   return None;
4573 }
4574 
4575 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4576 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4577 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4578 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4579 /// follows one of the following patterns:
4580 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4581 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4582 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4583 /// we return the type of the truncation operation, and indicate whether the
4584 /// truncated type should be treated as signed/unsigned by setting
4585 /// \p Signed to true/false, respectively.
4586 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4587                                bool &Signed, ScalarEvolution &SE) {
4588   // The case where Op == SymbolicPHI (that is, with no type conversions on
4589   // the way) is handled by the regular add recurrence creating logic and
4590   // would have already been triggered in createAddRecForPHI. Reaching it here
4591   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4592   // because one of the other operands of the SCEVAddExpr updating this PHI is
4593   // not invariant).
4594   //
4595   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4596   // this case predicates that allow us to prove that Op == SymbolicPHI will
4597   // be added.
4598   if (Op == SymbolicPHI)
4599     return nullptr;
4600 
4601   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4602   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4603   if (SourceBits != NewBits)
4604     return nullptr;
4605 
4606   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4607   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4608   if (!SExt && !ZExt)
4609     return nullptr;
4610   const SCEVTruncateExpr *Trunc =
4611       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4612            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4613   if (!Trunc)
4614     return nullptr;
4615   const SCEV *X = Trunc->getOperand();
4616   if (X != SymbolicPHI)
4617     return nullptr;
4618   Signed = SExt != nullptr;
4619   return Trunc->getType();
4620 }
4621 
4622 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4623   if (!PN->getType()->isIntegerTy())
4624     return nullptr;
4625   const Loop *L = LI.getLoopFor(PN->getParent());
4626   if (!L || L->getHeader() != PN->getParent())
4627     return nullptr;
4628   return L;
4629 }
4630 
4631 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4632 // computation that updates the phi follows the following pattern:
4633 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4634 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4635 // If so, try to see if it can be rewritten as an AddRecExpr under some
4636 // Predicates. If successful, return them as a pair. Also cache the results
4637 // of the analysis.
4638 //
4639 // Example usage scenario:
4640 //    Say the Rewriter is called for the following SCEV:
4641 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4642 //    where:
4643 //         %X = phi i64 (%Start, %BEValue)
4644 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4645 //    and call this function with %SymbolicPHI = %X.
4646 //
4647 //    The analysis will find that the value coming around the backedge has
4648 //    the following SCEV:
4649 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4650 //    Upon concluding that this matches the desired pattern, the function
4651 //    will return the pair {NewAddRec, SmallPredsVec} where:
4652 //         NewAddRec = {%Start,+,%Step}
4653 //         SmallPredsVec = {P1, P2, P3} as follows:
4654 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4655 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4656 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4657 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4658 //    under the predicates {P1,P2,P3}.
4659 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4660 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4661 //
4662 // TODO's:
4663 //
4664 // 1) Extend the Induction descriptor to also support inductions that involve
4665 //    casts: When needed (namely, when we are called in the context of the
4666 //    vectorizer induction analysis), a Set of cast instructions will be
4667 //    populated by this method, and provided back to isInductionPHI. This is
4668 //    needed to allow the vectorizer to properly record them to be ignored by
4669 //    the cost model and to avoid vectorizing them (otherwise these casts,
4670 //    which are redundant under the runtime overflow checks, will be
4671 //    vectorized, which can be costly).
4672 //
4673 // 2) Support additional induction/PHISCEV patterns: We also want to support
4674 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4675 //    after the induction update operation (the induction increment):
4676 //
4677 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4678 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4679 //
4680 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4681 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4682 //
4683 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4684 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4685 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4686   SmallVector<const SCEVPredicate *, 3> Predicates;
4687 
4688   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4689   // return an AddRec expression under some predicate.
4690 
4691   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4692   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4693   assert(L && "Expecting an integer loop header phi");
4694 
4695   // The loop may have multiple entrances or multiple exits; we can analyze
4696   // this phi as an addrec if it has a unique entry value and a unique
4697   // backedge value.
4698   Value *BEValueV = nullptr, *StartValueV = nullptr;
4699   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4700     Value *V = PN->getIncomingValue(i);
4701     if (L->contains(PN->getIncomingBlock(i))) {
4702       if (!BEValueV) {
4703         BEValueV = V;
4704       } else if (BEValueV != V) {
4705         BEValueV = nullptr;
4706         break;
4707       }
4708     } else if (!StartValueV) {
4709       StartValueV = V;
4710     } else if (StartValueV != V) {
4711       StartValueV = nullptr;
4712       break;
4713     }
4714   }
4715   if (!BEValueV || !StartValueV)
4716     return None;
4717 
4718   const SCEV *BEValue = getSCEV(BEValueV);
4719 
4720   // If the value coming around the backedge is an add with the symbolic
4721   // value we just inserted, possibly with casts that we can ignore under
4722   // an appropriate runtime guard, then we found a simple induction variable!
4723   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4724   if (!Add)
4725     return None;
4726 
4727   // If there is a single occurrence of the symbolic value, possibly
4728   // casted, replace it with a recurrence.
4729   unsigned FoundIndex = Add->getNumOperands();
4730   Type *TruncTy = nullptr;
4731   bool Signed;
4732   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4733     if ((TruncTy =
4734              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4735       if (FoundIndex == e) {
4736         FoundIndex = i;
4737         break;
4738       }
4739 
4740   if (FoundIndex == Add->getNumOperands())
4741     return None;
4742 
4743   // Create an add with everything but the specified operand.
4744   SmallVector<const SCEV *, 8> Ops;
4745   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4746     if (i != FoundIndex)
4747       Ops.push_back(Add->getOperand(i));
4748   const SCEV *Accum = getAddExpr(Ops);
4749 
4750   // The runtime checks will not be valid if the step amount is
4751   // varying inside the loop.
4752   if (!isLoopInvariant(Accum, L))
4753     return None;
4754 
4755   // *** Part2: Create the predicates
4756 
4757   // Analysis was successful: we have a phi-with-cast pattern for which we
4758   // can return an AddRec expression under the following predicates:
4759   //
4760   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4761   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4762   // P2: An Equal predicate that guarantees that
4763   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4764   // P3: An Equal predicate that guarantees that
4765   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4766   //
4767   // As we next prove, the above predicates guarantee that:
4768   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4769   //
4770   //
4771   // More formally, we want to prove that:
4772   //     Expr(i+1) = Start + (i+1) * Accum
4773   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4774   //
4775   // Given that:
4776   // 1) Expr(0) = Start
4777   // 2) Expr(1) = Start + Accum
4778   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4779   // 3) Induction hypothesis (step i):
4780   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4781   //
4782   // Proof:
4783   //  Expr(i+1) =
4784   //   = Start + (i+1)*Accum
4785   //   = (Start + i*Accum) + Accum
4786   //   = Expr(i) + Accum
4787   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4788   //                                                             :: from step i
4789   //
4790   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4791   //
4792   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4793   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4794   //     + Accum                                                     :: from P3
4795   //
4796   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4797   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4798   //
4799   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4800   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4801   //
4802   // By induction, the same applies to all iterations 1<=i<n:
4803   //
4804 
4805   // Create a truncated addrec for which we will add a no overflow check (P1).
4806   const SCEV *StartVal = getSCEV(StartValueV);
4807   const SCEV *PHISCEV =
4808       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4809                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4810 
4811   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4812   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4813   // will be constant.
4814   //
4815   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4816   // add P1.
4817   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4818     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4819         Signed ? SCEVWrapPredicate::IncrementNSSW
4820                : SCEVWrapPredicate::IncrementNUSW;
4821     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4822     Predicates.push_back(AddRecPred);
4823   }
4824 
4825   // Create the Equal Predicates P2,P3:
4826 
4827   // It is possible that the predicates P2 and/or P3 are computable at
4828   // compile time due to StartVal and/or Accum being constants.
4829   // If either one is, then we can check that now and escape if either P2
4830   // or P3 is false.
4831 
4832   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4833   // for each of StartVal and Accum
4834   auto getExtendedExpr = [&](const SCEV *Expr,
4835                              bool CreateSignExtend) -> const SCEV * {
4836     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4837     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4838     const SCEV *ExtendedExpr =
4839         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4840                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4841     return ExtendedExpr;
4842   };
4843 
4844   // Given:
4845   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4846   //               = getExtendedExpr(Expr)
4847   // Determine whether the predicate P: Expr == ExtendedExpr
4848   // is known to be false at compile time
4849   auto PredIsKnownFalse = [&](const SCEV *Expr,
4850                               const SCEV *ExtendedExpr) -> bool {
4851     return Expr != ExtendedExpr &&
4852            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4853   };
4854 
4855   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4856   if (PredIsKnownFalse(StartVal, StartExtended)) {
4857     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4858     return None;
4859   }
4860 
4861   // The Step is always Signed (because the overflow checks are either
4862   // NSSW or NUSW)
4863   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4864   if (PredIsKnownFalse(Accum, AccumExtended)) {
4865     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4866     return None;
4867   }
4868 
4869   auto AppendPredicate = [&](const SCEV *Expr,
4870                              const SCEV *ExtendedExpr) -> void {
4871     if (Expr != ExtendedExpr &&
4872         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4873       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4874       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4875       Predicates.push_back(Pred);
4876     }
4877   };
4878 
4879   AppendPredicate(StartVal, StartExtended);
4880   AppendPredicate(Accum, AccumExtended);
4881 
4882   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4883   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4884   // into NewAR if it will also add the runtime overflow checks specified in
4885   // Predicates.
4886   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4887 
4888   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4889       std::make_pair(NewAR, Predicates);
4890   // Remember the result of the analysis for this SCEV at this locayyytion.
4891   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4892   return PredRewrite;
4893 }
4894 
4895 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4896 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4897   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4898   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4899   if (!L)
4900     return None;
4901 
4902   // Check to see if we already analyzed this PHI.
4903   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4904   if (I != PredicatedSCEVRewrites.end()) {
4905     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4906         I->second;
4907     // Analysis was done before and failed to create an AddRec:
4908     if (Rewrite.first == SymbolicPHI)
4909       return None;
4910     // Analysis was done before and succeeded to create an AddRec under
4911     // a predicate:
4912     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4913     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4914     return Rewrite;
4915   }
4916 
4917   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4918     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4919 
4920   // Record in the cache that the analysis failed
4921   if (!Rewrite) {
4922     SmallVector<const SCEVPredicate *, 3> Predicates;
4923     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4924     return None;
4925   }
4926 
4927   return Rewrite;
4928 }
4929 
4930 // FIXME: This utility is currently required because the Rewriter currently
4931 // does not rewrite this expression:
4932 // {0, +, (sext ix (trunc iy to ix) to iy)}
4933 // into {0, +, %step},
4934 // even when the following Equal predicate exists:
4935 // "%step == (sext ix (trunc iy to ix) to iy)".
4936 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4937     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4938   if (AR1 == AR2)
4939     return true;
4940 
4941   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4942     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4943         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4944       return false;
4945     return true;
4946   };
4947 
4948   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4949       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4950     return false;
4951   return true;
4952 }
4953 
4954 /// A helper function for createAddRecFromPHI to handle simple cases.
4955 ///
4956 /// This function tries to find an AddRec expression for the simplest (yet most
4957 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4958 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4959 /// technique for finding the AddRec expression.
4960 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4961                                                       Value *BEValueV,
4962                                                       Value *StartValueV) {
4963   const Loop *L = LI.getLoopFor(PN->getParent());
4964   assert(L && L->getHeader() == PN->getParent());
4965   assert(BEValueV && StartValueV);
4966 
4967   auto BO = MatchBinaryOp(BEValueV, DT);
4968   if (!BO)
4969     return nullptr;
4970 
4971   if (BO->Opcode != Instruction::Add)
4972     return nullptr;
4973 
4974   const SCEV *Accum = nullptr;
4975   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4976     Accum = getSCEV(BO->RHS);
4977   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4978     Accum = getSCEV(BO->LHS);
4979 
4980   if (!Accum)
4981     return nullptr;
4982 
4983   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4984   if (BO->IsNUW)
4985     Flags = setFlags(Flags, SCEV::FlagNUW);
4986   if (BO->IsNSW)
4987     Flags = setFlags(Flags, SCEV::FlagNSW);
4988 
4989   const SCEV *StartVal = getSCEV(StartValueV);
4990   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4991 
4992   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4993 
4994   // We can add Flags to the post-inc expression only if we
4995   // know that it is *undefined behavior* for BEValueV to
4996   // overflow.
4997   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4998     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4999       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5000 
5001   return PHISCEV;
5002 }
5003 
5004 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5005   const Loop *L = LI.getLoopFor(PN->getParent());
5006   if (!L || L->getHeader() != PN->getParent())
5007     return nullptr;
5008 
5009   // The loop may have multiple entrances or multiple exits; we can analyze
5010   // this phi as an addrec if it has a unique entry value and a unique
5011   // backedge value.
5012   Value *BEValueV = nullptr, *StartValueV = nullptr;
5013   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5014     Value *V = PN->getIncomingValue(i);
5015     if (L->contains(PN->getIncomingBlock(i))) {
5016       if (!BEValueV) {
5017         BEValueV = V;
5018       } else if (BEValueV != V) {
5019         BEValueV = nullptr;
5020         break;
5021       }
5022     } else if (!StartValueV) {
5023       StartValueV = V;
5024     } else if (StartValueV != V) {
5025       StartValueV = nullptr;
5026       break;
5027     }
5028   }
5029   if (!BEValueV || !StartValueV)
5030     return nullptr;
5031 
5032   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5033          "PHI node already processed?");
5034 
5035   // First, try to find AddRec expression without creating a fictituos symbolic
5036   // value for PN.
5037   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5038     return S;
5039 
5040   // Handle PHI node value symbolically.
5041   const SCEV *SymbolicName = getUnknown(PN);
5042   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5043 
5044   // Using this symbolic name for the PHI, analyze the value coming around
5045   // the back-edge.
5046   const SCEV *BEValue = getSCEV(BEValueV);
5047 
5048   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5049   // has a special value for the first iteration of the loop.
5050 
5051   // If the value coming around the backedge is an add with the symbolic
5052   // value we just inserted, then we found a simple induction variable!
5053   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5054     // If there is a single occurrence of the symbolic value, replace it
5055     // with a recurrence.
5056     unsigned FoundIndex = Add->getNumOperands();
5057     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5058       if (Add->getOperand(i) == SymbolicName)
5059         if (FoundIndex == e) {
5060           FoundIndex = i;
5061           break;
5062         }
5063 
5064     if (FoundIndex != Add->getNumOperands()) {
5065       // Create an add with everything but the specified operand.
5066       SmallVector<const SCEV *, 8> Ops;
5067       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5068         if (i != FoundIndex)
5069           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5070                                                              L, *this));
5071       const SCEV *Accum = getAddExpr(Ops);
5072 
5073       // This is not a valid addrec if the step amount is varying each
5074       // loop iteration, but is not itself an addrec in this loop.
5075       if (isLoopInvariant(Accum, L) ||
5076           (isa<SCEVAddRecExpr>(Accum) &&
5077            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5078         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5079 
5080         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5081           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5082             if (BO->IsNUW)
5083               Flags = setFlags(Flags, SCEV::FlagNUW);
5084             if (BO->IsNSW)
5085               Flags = setFlags(Flags, SCEV::FlagNSW);
5086           }
5087         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5088           // If the increment is an inbounds GEP, then we know the address
5089           // space cannot be wrapped around. We cannot make any guarantee
5090           // about signed or unsigned overflow because pointers are
5091           // unsigned but we may have a negative index from the base
5092           // pointer. We can guarantee that no unsigned wrap occurs if the
5093           // indices form a positive value.
5094           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5095             Flags = setFlags(Flags, SCEV::FlagNW);
5096 
5097             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5098             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5099               Flags = setFlags(Flags, SCEV::FlagNUW);
5100           }
5101 
5102           // We cannot transfer nuw and nsw flags from subtraction
5103           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5104           // for instance.
5105         }
5106 
5107         const SCEV *StartVal = getSCEV(StartValueV);
5108         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5109 
5110         // Okay, for the entire analysis of this edge we assumed the PHI
5111         // to be symbolic.  We now need to go back and purge all of the
5112         // entries for the scalars that use the symbolic expression.
5113         forgetSymbolicName(PN, SymbolicName);
5114         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5115 
5116         // We can add Flags to the post-inc expression only if we
5117         // know that it is *undefined behavior* for BEValueV to
5118         // overflow.
5119         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5120           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5121             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5122 
5123         return PHISCEV;
5124       }
5125     }
5126   } else {
5127     // Otherwise, this could be a loop like this:
5128     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5129     // In this case, j = {1,+,1}  and BEValue is j.
5130     // Because the other in-value of i (0) fits the evolution of BEValue
5131     // i really is an addrec evolution.
5132     //
5133     // We can generalize this saying that i is the shifted value of BEValue
5134     // by one iteration:
5135     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5136     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5137     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5138     if (Shifted != getCouldNotCompute() &&
5139         Start != getCouldNotCompute()) {
5140       const SCEV *StartVal = getSCEV(StartValueV);
5141       if (Start == StartVal) {
5142         // Okay, for the entire analysis of this edge we assumed the PHI
5143         // to be symbolic.  We now need to go back and purge all of the
5144         // entries for the scalars that use the symbolic expression.
5145         forgetSymbolicName(PN, SymbolicName);
5146         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5147         return Shifted;
5148       }
5149     }
5150   }
5151 
5152   // Remove the temporary PHI node SCEV that has been inserted while intending
5153   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5154   // as it will prevent later (possibly simpler) SCEV expressions to be added
5155   // to the ValueExprMap.
5156   eraseValueFromMap(PN);
5157 
5158   return nullptr;
5159 }
5160 
5161 // Checks if the SCEV S is available at BB.  S is considered available at BB
5162 // if S can be materialized at BB without introducing a fault.
5163 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5164                                BasicBlock *BB) {
5165   struct CheckAvailable {
5166     bool TraversalDone = false;
5167     bool Available = true;
5168 
5169     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5170     BasicBlock *BB = nullptr;
5171     DominatorTree &DT;
5172 
5173     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5174       : L(L), BB(BB), DT(DT) {}
5175 
5176     bool setUnavailable() {
5177       TraversalDone = true;
5178       Available = false;
5179       return false;
5180     }
5181 
5182     bool follow(const SCEV *S) {
5183       switch (S->getSCEVType()) {
5184       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5185       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5186       case scUMinExpr:
5187       case scSMinExpr:
5188         // These expressions are available if their operand(s) is/are.
5189         return true;
5190 
5191       case scAddRecExpr: {
5192         // We allow add recurrences that are on the loop BB is in, or some
5193         // outer loop.  This guarantees availability because the value of the
5194         // add recurrence at BB is simply the "current" value of the induction
5195         // variable.  We can relax this in the future; for instance an add
5196         // recurrence on a sibling dominating loop is also available at BB.
5197         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5198         if (L && (ARLoop == L || ARLoop->contains(L)))
5199           return true;
5200 
5201         return setUnavailable();
5202       }
5203 
5204       case scUnknown: {
5205         // For SCEVUnknown, we check for simple dominance.
5206         const auto *SU = cast<SCEVUnknown>(S);
5207         Value *V = SU->getValue();
5208 
5209         if (isa<Argument>(V))
5210           return false;
5211 
5212         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5213           return false;
5214 
5215         return setUnavailable();
5216       }
5217 
5218       case scUDivExpr:
5219       case scCouldNotCompute:
5220         // We do not try to smart about these at all.
5221         return setUnavailable();
5222       }
5223       llvm_unreachable("switch should be fully covered!");
5224     }
5225 
5226     bool isDone() { return TraversalDone; }
5227   };
5228 
5229   CheckAvailable CA(L, BB, DT);
5230   SCEVTraversal<CheckAvailable> ST(CA);
5231 
5232   ST.visitAll(S);
5233   return CA.Available;
5234 }
5235 
5236 // Try to match a control flow sequence that branches out at BI and merges back
5237 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5238 // match.
5239 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5240                           Value *&C, Value *&LHS, Value *&RHS) {
5241   C = BI->getCondition();
5242 
5243   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5244   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5245 
5246   if (!LeftEdge.isSingleEdge())
5247     return false;
5248 
5249   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5250 
5251   Use &LeftUse = Merge->getOperandUse(0);
5252   Use &RightUse = Merge->getOperandUse(1);
5253 
5254   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5255     LHS = LeftUse;
5256     RHS = RightUse;
5257     return true;
5258   }
5259 
5260   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5261     LHS = RightUse;
5262     RHS = LeftUse;
5263     return true;
5264   }
5265 
5266   return false;
5267 }
5268 
5269 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5270   auto IsReachable =
5271       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5272   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5273     const Loop *L = LI.getLoopFor(PN->getParent());
5274 
5275     // We don't want to break LCSSA, even in a SCEV expression tree.
5276     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5277       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5278         return nullptr;
5279 
5280     // Try to match
5281     //
5282     //  br %cond, label %left, label %right
5283     // left:
5284     //  br label %merge
5285     // right:
5286     //  br label %merge
5287     // merge:
5288     //  V = phi [ %x, %left ], [ %y, %right ]
5289     //
5290     // as "select %cond, %x, %y"
5291 
5292     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5293     assert(IDom && "At least the entry block should dominate PN");
5294 
5295     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5296     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5297 
5298     if (BI && BI->isConditional() &&
5299         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5300         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5301         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5302       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5303   }
5304 
5305   return nullptr;
5306 }
5307 
5308 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5309   if (const SCEV *S = createAddRecFromPHI(PN))
5310     return S;
5311 
5312   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5313     return S;
5314 
5315   // If the PHI has a single incoming value, follow that value, unless the
5316   // PHI's incoming blocks are in a different loop, in which case doing so
5317   // risks breaking LCSSA form. Instcombine would normally zap these, but
5318   // it doesn't have DominatorTree information, so it may miss cases.
5319   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5320     if (LI.replacementPreservesLCSSAForm(PN, V))
5321       return getSCEV(V);
5322 
5323   // If it's not a loop phi, we can't handle it yet.
5324   return getUnknown(PN);
5325 }
5326 
5327 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5328                                                       Value *Cond,
5329                                                       Value *TrueVal,
5330                                                       Value *FalseVal) {
5331   // Handle "constant" branch or select. This can occur for instance when a
5332   // loop pass transforms an inner loop and moves on to process the outer loop.
5333   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5334     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5335 
5336   // Try to match some simple smax or umax patterns.
5337   auto *ICI = dyn_cast<ICmpInst>(Cond);
5338   if (!ICI)
5339     return getUnknown(I);
5340 
5341   Value *LHS = ICI->getOperand(0);
5342   Value *RHS = ICI->getOperand(1);
5343 
5344   switch (ICI->getPredicate()) {
5345   case ICmpInst::ICMP_SLT:
5346   case ICmpInst::ICMP_SLE:
5347     std::swap(LHS, RHS);
5348     LLVM_FALLTHROUGH;
5349   case ICmpInst::ICMP_SGT:
5350   case ICmpInst::ICMP_SGE:
5351     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5352     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5353     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5354       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5355       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5356       const SCEV *LA = getSCEV(TrueVal);
5357       const SCEV *RA = getSCEV(FalseVal);
5358       const SCEV *LDiff = getMinusSCEV(LA, LS);
5359       const SCEV *RDiff = getMinusSCEV(RA, RS);
5360       if (LDiff == RDiff)
5361         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5362       LDiff = getMinusSCEV(LA, RS);
5363       RDiff = getMinusSCEV(RA, LS);
5364       if (LDiff == RDiff)
5365         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5366     }
5367     break;
5368   case ICmpInst::ICMP_ULT:
5369   case ICmpInst::ICMP_ULE:
5370     std::swap(LHS, RHS);
5371     LLVM_FALLTHROUGH;
5372   case ICmpInst::ICMP_UGT:
5373   case ICmpInst::ICMP_UGE:
5374     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5375     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5376     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5377       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5378       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5379       const SCEV *LA = getSCEV(TrueVal);
5380       const SCEV *RA = getSCEV(FalseVal);
5381       const SCEV *LDiff = getMinusSCEV(LA, LS);
5382       const SCEV *RDiff = getMinusSCEV(RA, RS);
5383       if (LDiff == RDiff)
5384         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5385       LDiff = getMinusSCEV(LA, RS);
5386       RDiff = getMinusSCEV(RA, LS);
5387       if (LDiff == RDiff)
5388         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5389     }
5390     break;
5391   case ICmpInst::ICMP_NE:
5392     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5393     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5394         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5395       const SCEV *One = getOne(I->getType());
5396       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5397       const SCEV *LA = getSCEV(TrueVal);
5398       const SCEV *RA = getSCEV(FalseVal);
5399       const SCEV *LDiff = getMinusSCEV(LA, LS);
5400       const SCEV *RDiff = getMinusSCEV(RA, One);
5401       if (LDiff == RDiff)
5402         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5403     }
5404     break;
5405   case ICmpInst::ICMP_EQ:
5406     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5407     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5408         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5409       const SCEV *One = getOne(I->getType());
5410       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5411       const SCEV *LA = getSCEV(TrueVal);
5412       const SCEV *RA = getSCEV(FalseVal);
5413       const SCEV *LDiff = getMinusSCEV(LA, One);
5414       const SCEV *RDiff = getMinusSCEV(RA, LS);
5415       if (LDiff == RDiff)
5416         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5417     }
5418     break;
5419   default:
5420     break;
5421   }
5422 
5423   return getUnknown(I);
5424 }
5425 
5426 /// Expand GEP instructions into add and multiply operations. This allows them
5427 /// to be analyzed by regular SCEV code.
5428 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5429   // Don't attempt to analyze GEPs over unsized objects.
5430   if (!GEP->getSourceElementType()->isSized())
5431     return getUnknown(GEP);
5432 
5433   SmallVector<const SCEV *, 4> IndexExprs;
5434   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5435     IndexExprs.push_back(getSCEV(*Index));
5436   return getGEPExpr(GEP, IndexExprs);
5437 }
5438 
5439 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5440   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5441     return C->getAPInt().countTrailingZeros();
5442 
5443   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5444     return std::min(GetMinTrailingZeros(T->getOperand()),
5445                     (uint32_t)getTypeSizeInBits(T->getType()));
5446 
5447   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5448     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5449     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5450                ? getTypeSizeInBits(E->getType())
5451                : OpRes;
5452   }
5453 
5454   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5455     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5456     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5457                ? getTypeSizeInBits(E->getType())
5458                : OpRes;
5459   }
5460 
5461   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5462     // The result is the min of all operands results.
5463     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5464     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5465       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5466     return MinOpRes;
5467   }
5468 
5469   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5470     // The result is the sum of all operands results.
5471     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5472     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5473     for (unsigned i = 1, e = M->getNumOperands();
5474          SumOpRes != BitWidth && i != e; ++i)
5475       SumOpRes =
5476           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5477     return SumOpRes;
5478   }
5479 
5480   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5481     // The result is the min of all operands results.
5482     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5483     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5484       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5485     return MinOpRes;
5486   }
5487 
5488   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5489     // The result is the min of all operands results.
5490     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5491     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5492       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5493     return MinOpRes;
5494   }
5495 
5496   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5497     // The result is the min of all operands results.
5498     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5499     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5500       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5501     return MinOpRes;
5502   }
5503 
5504   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5505     // For a SCEVUnknown, ask ValueTracking.
5506     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5507     return Known.countMinTrailingZeros();
5508   }
5509 
5510   // SCEVUDivExpr
5511   return 0;
5512 }
5513 
5514 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5515   auto I = MinTrailingZerosCache.find(S);
5516   if (I != MinTrailingZerosCache.end())
5517     return I->second;
5518 
5519   uint32_t Result = GetMinTrailingZerosImpl(S);
5520   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5521   assert(InsertPair.second && "Should insert a new key");
5522   return InsertPair.first->second;
5523 }
5524 
5525 /// Helper method to assign a range to V from metadata present in the IR.
5526 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5527   if (Instruction *I = dyn_cast<Instruction>(V))
5528     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5529       return getConstantRangeFromMetadata(*MD);
5530 
5531   return None;
5532 }
5533 
5534 /// Determine the range for a particular SCEV.  If SignHint is
5535 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5536 /// with a "cleaner" unsigned (resp. signed) representation.
5537 const ConstantRange &
5538 ScalarEvolution::getRangeRef(const SCEV *S,
5539                              ScalarEvolution::RangeSignHint SignHint) {
5540   DenseMap<const SCEV *, ConstantRange> &Cache =
5541       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5542                                                        : SignedRanges;
5543   ConstantRange::PreferredRangeType RangeType =
5544       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5545           ? ConstantRange::Unsigned : ConstantRange::Signed;
5546 
5547   // See if we've computed this range already.
5548   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5549   if (I != Cache.end())
5550     return I->second;
5551 
5552   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5553     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5554 
5555   unsigned BitWidth = getTypeSizeInBits(S->getType());
5556   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5557 
5558   // If the value has known zeros, the maximum value will have those known zeros
5559   // as well.
5560   uint32_t TZ = GetMinTrailingZeros(S);
5561   if (TZ != 0) {
5562     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5563       ConservativeResult =
5564           ConstantRange(APInt::getMinValue(BitWidth),
5565                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5566     else
5567       ConservativeResult = ConstantRange(
5568           APInt::getSignedMinValue(BitWidth),
5569           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5570   }
5571 
5572   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5573     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5574     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5575       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5576     return setRange(Add, SignHint,
5577                     ConservativeResult.intersectWith(X, RangeType));
5578   }
5579 
5580   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5581     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5582     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5583       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5584     return setRange(Mul, SignHint,
5585                     ConservativeResult.intersectWith(X, RangeType));
5586   }
5587 
5588   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5589     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5590     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5591       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5592     return setRange(SMax, SignHint,
5593                     ConservativeResult.intersectWith(X, RangeType));
5594   }
5595 
5596   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5597     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5598     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5599       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5600     return setRange(UMax, SignHint,
5601                     ConservativeResult.intersectWith(X, RangeType));
5602   }
5603 
5604   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5605     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5606     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5607       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5608     return setRange(SMin, SignHint,
5609                     ConservativeResult.intersectWith(X, RangeType));
5610   }
5611 
5612   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5613     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5614     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5615       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5616     return setRange(UMin, SignHint,
5617                     ConservativeResult.intersectWith(X, RangeType));
5618   }
5619 
5620   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5621     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5622     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5623     return setRange(UDiv, SignHint,
5624                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5625   }
5626 
5627   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5628     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5629     return setRange(ZExt, SignHint,
5630                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5631                                                      RangeType));
5632   }
5633 
5634   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5635     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5636     return setRange(SExt, SignHint,
5637                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5638                                                      RangeType));
5639   }
5640 
5641   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5642     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5643     return setRange(Trunc, SignHint,
5644                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5645                                                      RangeType));
5646   }
5647 
5648   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5649     // If there's no unsigned wrap, the value will never be less than its
5650     // initial value.
5651     if (AddRec->hasNoUnsignedWrap())
5652       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5653         if (!C->getValue()->isZero())
5654           ConservativeResult = ConservativeResult.intersectWith(
5655               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType);
5656 
5657     // If there's no signed wrap, and all the operands have the same sign or
5658     // zero, the value won't ever change sign.
5659     if (AddRec->hasNoSignedWrap()) {
5660       bool AllNonNeg = true;
5661       bool AllNonPos = true;
5662       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5663         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5664         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5665       }
5666       if (AllNonNeg)
5667         ConservativeResult = ConservativeResult.intersectWith(
5668           ConstantRange(APInt(BitWidth, 0),
5669                         APInt::getSignedMinValue(BitWidth)), RangeType);
5670       else if (AllNonPos)
5671         ConservativeResult = ConservativeResult.intersectWith(
5672           ConstantRange(APInt::getSignedMinValue(BitWidth),
5673                         APInt(BitWidth, 1)), RangeType);
5674     }
5675 
5676     // TODO: non-affine addrec
5677     if (AddRec->isAffine()) {
5678       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5679       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5680           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5681         auto RangeFromAffine = getRangeForAffineAR(
5682             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5683             BitWidth);
5684         if (!RangeFromAffine.isFullSet())
5685           ConservativeResult =
5686               ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5687 
5688         auto RangeFromFactoring = getRangeViaFactoring(
5689             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5690             BitWidth);
5691         if (!RangeFromFactoring.isFullSet())
5692           ConservativeResult =
5693               ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5694       }
5695     }
5696 
5697     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5698   }
5699 
5700   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5701     // Check if the IR explicitly contains !range metadata.
5702     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5703     if (MDRange.hasValue())
5704       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5705                                                             RangeType);
5706 
5707     // Split here to avoid paying the compile-time cost of calling both
5708     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5709     // if needed.
5710     const DataLayout &DL = getDataLayout();
5711     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5712       // For a SCEVUnknown, ask ValueTracking.
5713       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5714       if (Known.One != ~Known.Zero + 1)
5715         ConservativeResult =
5716             ConservativeResult.intersectWith(
5717                 ConstantRange(Known.One, ~Known.Zero + 1), RangeType);
5718     } else {
5719       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5720              "generalize as needed!");
5721       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5722       if (NS > 1)
5723         ConservativeResult = ConservativeResult.intersectWith(
5724             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5725                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5726             RangeType);
5727     }
5728 
5729     // A range of Phi is a subset of union of all ranges of its input.
5730     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5731       // Make sure that we do not run over cycled Phis.
5732       if (PendingPhiRanges.insert(Phi).second) {
5733         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5734         for (auto &Op : Phi->operands()) {
5735           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5736           RangeFromOps = RangeFromOps.unionWith(OpRange);
5737           // No point to continue if we already have a full set.
5738           if (RangeFromOps.isFullSet())
5739             break;
5740         }
5741         ConservativeResult =
5742             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5743         bool Erased = PendingPhiRanges.erase(Phi);
5744         assert(Erased && "Failed to erase Phi properly?");
5745         (void) Erased;
5746       }
5747     }
5748 
5749     return setRange(U, SignHint, std::move(ConservativeResult));
5750   }
5751 
5752   return setRange(S, SignHint, std::move(ConservativeResult));
5753 }
5754 
5755 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5756 // values that the expression can take. Initially, the expression has a value
5757 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5758 // argument defines if we treat Step as signed or unsigned.
5759 static ConstantRange getRangeForAffineARHelper(APInt Step,
5760                                                const ConstantRange &StartRange,
5761                                                const APInt &MaxBECount,
5762                                                unsigned BitWidth, bool Signed) {
5763   // If either Step or MaxBECount is 0, then the expression won't change, and we
5764   // just need to return the initial range.
5765   if (Step == 0 || MaxBECount == 0)
5766     return StartRange;
5767 
5768   // If we don't know anything about the initial value (i.e. StartRange is
5769   // FullRange), then we don't know anything about the final range either.
5770   // Return FullRange.
5771   if (StartRange.isFullSet())
5772     return ConstantRange::getFull(BitWidth);
5773 
5774   // If Step is signed and negative, then we use its absolute value, but we also
5775   // note that we're moving in the opposite direction.
5776   bool Descending = Signed && Step.isNegative();
5777 
5778   if (Signed)
5779     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5780     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5781     // This equations hold true due to the well-defined wrap-around behavior of
5782     // APInt.
5783     Step = Step.abs();
5784 
5785   // Check if Offset is more than full span of BitWidth. If it is, the
5786   // expression is guaranteed to overflow.
5787   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5788     return ConstantRange::getFull(BitWidth);
5789 
5790   // Offset is by how much the expression can change. Checks above guarantee no
5791   // overflow here.
5792   APInt Offset = Step * MaxBECount;
5793 
5794   // Minimum value of the final range will match the minimal value of StartRange
5795   // if the expression is increasing and will be decreased by Offset otherwise.
5796   // Maximum value of the final range will match the maximal value of StartRange
5797   // if the expression is decreasing and will be increased by Offset otherwise.
5798   APInt StartLower = StartRange.getLower();
5799   APInt StartUpper = StartRange.getUpper() - 1;
5800   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5801                                    : (StartUpper + std::move(Offset));
5802 
5803   // It's possible that the new minimum/maximum value will fall into the initial
5804   // range (due to wrap around). This means that the expression can take any
5805   // value in this bitwidth, and we have to return full range.
5806   if (StartRange.contains(MovedBoundary))
5807     return ConstantRange::getFull(BitWidth);
5808 
5809   APInt NewLower =
5810       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5811   APInt NewUpper =
5812       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5813   NewUpper += 1;
5814 
5815   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5816   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5817 }
5818 
5819 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5820                                                    const SCEV *Step,
5821                                                    const SCEV *MaxBECount,
5822                                                    unsigned BitWidth) {
5823   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5824          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5825          "Precondition!");
5826 
5827   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5828   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5829 
5830   // First, consider step signed.
5831   ConstantRange StartSRange = getSignedRange(Start);
5832   ConstantRange StepSRange = getSignedRange(Step);
5833 
5834   // If Step can be both positive and negative, we need to find ranges for the
5835   // maximum absolute step values in both directions and union them.
5836   ConstantRange SR =
5837       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5838                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5839   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5840                                               StartSRange, MaxBECountValue,
5841                                               BitWidth, /* Signed = */ true));
5842 
5843   // Next, consider step unsigned.
5844   ConstantRange UR = getRangeForAffineARHelper(
5845       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5846       MaxBECountValue, BitWidth, /* Signed = */ false);
5847 
5848   // Finally, intersect signed and unsigned ranges.
5849   return SR.intersectWith(UR, ConstantRange::Smallest);
5850 }
5851 
5852 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5853                                                     const SCEV *Step,
5854                                                     const SCEV *MaxBECount,
5855                                                     unsigned BitWidth) {
5856   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5857   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5858 
5859   struct SelectPattern {
5860     Value *Condition = nullptr;
5861     APInt TrueValue;
5862     APInt FalseValue;
5863 
5864     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5865                            const SCEV *S) {
5866       Optional<unsigned> CastOp;
5867       APInt Offset(BitWidth, 0);
5868 
5869       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5870              "Should be!");
5871 
5872       // Peel off a constant offset:
5873       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5874         // In the future we could consider being smarter here and handle
5875         // {Start+Step,+,Step} too.
5876         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5877           return;
5878 
5879         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5880         S = SA->getOperand(1);
5881       }
5882 
5883       // Peel off a cast operation
5884       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5885         CastOp = SCast->getSCEVType();
5886         S = SCast->getOperand();
5887       }
5888 
5889       using namespace llvm::PatternMatch;
5890 
5891       auto *SU = dyn_cast<SCEVUnknown>(S);
5892       const APInt *TrueVal, *FalseVal;
5893       if (!SU ||
5894           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5895                                           m_APInt(FalseVal)))) {
5896         Condition = nullptr;
5897         return;
5898       }
5899 
5900       TrueValue = *TrueVal;
5901       FalseValue = *FalseVal;
5902 
5903       // Re-apply the cast we peeled off earlier
5904       if (CastOp.hasValue())
5905         switch (*CastOp) {
5906         default:
5907           llvm_unreachable("Unknown SCEV cast type!");
5908 
5909         case scTruncate:
5910           TrueValue = TrueValue.trunc(BitWidth);
5911           FalseValue = FalseValue.trunc(BitWidth);
5912           break;
5913         case scZeroExtend:
5914           TrueValue = TrueValue.zext(BitWidth);
5915           FalseValue = FalseValue.zext(BitWidth);
5916           break;
5917         case scSignExtend:
5918           TrueValue = TrueValue.sext(BitWidth);
5919           FalseValue = FalseValue.sext(BitWidth);
5920           break;
5921         }
5922 
5923       // Re-apply the constant offset we peeled off earlier
5924       TrueValue += Offset;
5925       FalseValue += Offset;
5926     }
5927 
5928     bool isRecognized() { return Condition != nullptr; }
5929   };
5930 
5931   SelectPattern StartPattern(*this, BitWidth, Start);
5932   if (!StartPattern.isRecognized())
5933     return ConstantRange::getFull(BitWidth);
5934 
5935   SelectPattern StepPattern(*this, BitWidth, Step);
5936   if (!StepPattern.isRecognized())
5937     return ConstantRange::getFull(BitWidth);
5938 
5939   if (StartPattern.Condition != StepPattern.Condition) {
5940     // We don't handle this case today; but we could, by considering four
5941     // possibilities below instead of two. I'm not sure if there are cases where
5942     // that will help over what getRange already does, though.
5943     return ConstantRange::getFull(BitWidth);
5944   }
5945 
5946   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5947   // construct arbitrary general SCEV expressions here.  This function is called
5948   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5949   // say) can end up caching a suboptimal value.
5950 
5951   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5952   // C2352 and C2512 (otherwise it isn't needed).
5953 
5954   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5955   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5956   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5957   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5958 
5959   ConstantRange TrueRange =
5960       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5961   ConstantRange FalseRange =
5962       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5963 
5964   return TrueRange.unionWith(FalseRange);
5965 }
5966 
5967 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5968   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5969   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5970 
5971   // Return early if there are no flags to propagate to the SCEV.
5972   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5973   if (BinOp->hasNoUnsignedWrap())
5974     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5975   if (BinOp->hasNoSignedWrap())
5976     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5977   if (Flags == SCEV::FlagAnyWrap)
5978     return SCEV::FlagAnyWrap;
5979 
5980   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5981 }
5982 
5983 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5984   // Here we check that I is in the header of the innermost loop containing I,
5985   // since we only deal with instructions in the loop header. The actual loop we
5986   // need to check later will come from an add recurrence, but getting that
5987   // requires computing the SCEV of the operands, which can be expensive. This
5988   // check we can do cheaply to rule out some cases early.
5989   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5990   if (InnermostContainingLoop == nullptr ||
5991       InnermostContainingLoop->getHeader() != I->getParent())
5992     return false;
5993 
5994   // Only proceed if we can prove that I does not yield poison.
5995   if (!programUndefinedIfFullPoison(I))
5996     return false;
5997 
5998   // At this point we know that if I is executed, then it does not wrap
5999   // according to at least one of NSW or NUW. If I is not executed, then we do
6000   // not know if the calculation that I represents would wrap. Multiple
6001   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6002   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6003   // derived from other instructions that map to the same SCEV. We cannot make
6004   // that guarantee for cases where I is not executed. So we need to find the
6005   // loop that I is considered in relation to and prove that I is executed for
6006   // every iteration of that loop. That implies that the value that I
6007   // calculates does not wrap anywhere in the loop, so then we can apply the
6008   // flags to the SCEV.
6009   //
6010   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6011   // from different loops, so that we know which loop to prove that I is
6012   // executed in.
6013   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6014     // I could be an extractvalue from a call to an overflow intrinsic.
6015     // TODO: We can do better here in some cases.
6016     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6017       return false;
6018     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6019     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6020       bool AllOtherOpsLoopInvariant = true;
6021       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6022            ++OtherOpIndex) {
6023         if (OtherOpIndex != OpIndex) {
6024           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6025           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6026             AllOtherOpsLoopInvariant = false;
6027             break;
6028           }
6029         }
6030       }
6031       if (AllOtherOpsLoopInvariant &&
6032           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6033         return true;
6034     }
6035   }
6036   return false;
6037 }
6038 
6039 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6040   // If we know that \c I can never be poison period, then that's enough.
6041   if (isSCEVExprNeverPoison(I))
6042     return true;
6043 
6044   // For an add recurrence specifically, we assume that infinite loops without
6045   // side effects are undefined behavior, and then reason as follows:
6046   //
6047   // If the add recurrence is poison in any iteration, it is poison on all
6048   // future iterations (since incrementing poison yields poison). If the result
6049   // of the add recurrence is fed into the loop latch condition and the loop
6050   // does not contain any throws or exiting blocks other than the latch, we now
6051   // have the ability to "choose" whether the backedge is taken or not (by
6052   // choosing a sufficiently evil value for the poison feeding into the branch)
6053   // for every iteration including and after the one in which \p I first became
6054   // poison.  There are two possibilities (let's call the iteration in which \p
6055   // I first became poison as K):
6056   //
6057   //  1. In the set of iterations including and after K, the loop body executes
6058   //     no side effects.  In this case executing the backege an infinte number
6059   //     of times will yield undefined behavior.
6060   //
6061   //  2. In the set of iterations including and after K, the loop body executes
6062   //     at least one side effect.  In this case, that specific instance of side
6063   //     effect is control dependent on poison, which also yields undefined
6064   //     behavior.
6065 
6066   auto *ExitingBB = L->getExitingBlock();
6067   auto *LatchBB = L->getLoopLatch();
6068   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6069     return false;
6070 
6071   SmallPtrSet<const Instruction *, 16> Pushed;
6072   SmallVector<const Instruction *, 8> PoisonStack;
6073 
6074   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6075   // things that are known to be fully poison under that assumption go on the
6076   // PoisonStack.
6077   Pushed.insert(I);
6078   PoisonStack.push_back(I);
6079 
6080   bool LatchControlDependentOnPoison = false;
6081   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6082     const Instruction *Poison = PoisonStack.pop_back_val();
6083 
6084     for (auto *PoisonUser : Poison->users()) {
6085       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
6086         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6087           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6088       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6089         assert(BI->isConditional() && "Only possibility!");
6090         if (BI->getParent() == LatchBB) {
6091           LatchControlDependentOnPoison = true;
6092           break;
6093         }
6094       }
6095     }
6096   }
6097 
6098   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6099 }
6100 
6101 ScalarEvolution::LoopProperties
6102 ScalarEvolution::getLoopProperties(const Loop *L) {
6103   using LoopProperties = ScalarEvolution::LoopProperties;
6104 
6105   auto Itr = LoopPropertiesCache.find(L);
6106   if (Itr == LoopPropertiesCache.end()) {
6107     auto HasSideEffects = [](Instruction *I) {
6108       if (auto *SI = dyn_cast<StoreInst>(I))
6109         return !SI->isSimple();
6110 
6111       return I->mayHaveSideEffects();
6112     };
6113 
6114     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6115                          /*HasNoSideEffects*/ true};
6116 
6117     for (auto *BB : L->getBlocks())
6118       for (auto &I : *BB) {
6119         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6120           LP.HasNoAbnormalExits = false;
6121         if (HasSideEffects(&I))
6122           LP.HasNoSideEffects = false;
6123         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6124           break; // We're already as pessimistic as we can get.
6125       }
6126 
6127     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6128     assert(InsertPair.second && "We just checked!");
6129     Itr = InsertPair.first;
6130   }
6131 
6132   return Itr->second;
6133 }
6134 
6135 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6136   if (!isSCEVable(V->getType()))
6137     return getUnknown(V);
6138 
6139   if (Instruction *I = dyn_cast<Instruction>(V)) {
6140     // Don't attempt to analyze instructions in blocks that aren't
6141     // reachable. Such instructions don't matter, and they aren't required
6142     // to obey basic rules for definitions dominating uses which this
6143     // analysis depends on.
6144     if (!DT.isReachableFromEntry(I->getParent()))
6145       return getUnknown(UndefValue::get(V->getType()));
6146   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6147     return getConstant(CI);
6148   else if (isa<ConstantPointerNull>(V))
6149     return getZero(V->getType());
6150   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6151     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6152   else if (!isa<ConstantExpr>(V))
6153     return getUnknown(V);
6154 
6155   Operator *U = cast<Operator>(V);
6156   if (auto BO = MatchBinaryOp(U, DT)) {
6157     switch (BO->Opcode) {
6158     case Instruction::Add: {
6159       // The simple thing to do would be to just call getSCEV on both operands
6160       // and call getAddExpr with the result. However if we're looking at a
6161       // bunch of things all added together, this can be quite inefficient,
6162       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6163       // Instead, gather up all the operands and make a single getAddExpr call.
6164       // LLVM IR canonical form means we need only traverse the left operands.
6165       SmallVector<const SCEV *, 4> AddOps;
6166       do {
6167         if (BO->Op) {
6168           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6169             AddOps.push_back(OpSCEV);
6170             break;
6171           }
6172 
6173           // If a NUW or NSW flag can be applied to the SCEV for this
6174           // addition, then compute the SCEV for this addition by itself
6175           // with a separate call to getAddExpr. We need to do that
6176           // instead of pushing the operands of the addition onto AddOps,
6177           // since the flags are only known to apply to this particular
6178           // addition - they may not apply to other additions that can be
6179           // formed with operands from AddOps.
6180           const SCEV *RHS = getSCEV(BO->RHS);
6181           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6182           if (Flags != SCEV::FlagAnyWrap) {
6183             const SCEV *LHS = getSCEV(BO->LHS);
6184             if (BO->Opcode == Instruction::Sub)
6185               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6186             else
6187               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6188             break;
6189           }
6190         }
6191 
6192         if (BO->Opcode == Instruction::Sub)
6193           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6194         else
6195           AddOps.push_back(getSCEV(BO->RHS));
6196 
6197         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6198         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6199                        NewBO->Opcode != Instruction::Sub)) {
6200           AddOps.push_back(getSCEV(BO->LHS));
6201           break;
6202         }
6203         BO = NewBO;
6204       } while (true);
6205 
6206       return getAddExpr(AddOps);
6207     }
6208 
6209     case Instruction::Mul: {
6210       SmallVector<const SCEV *, 4> MulOps;
6211       do {
6212         if (BO->Op) {
6213           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6214             MulOps.push_back(OpSCEV);
6215             break;
6216           }
6217 
6218           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6219           if (Flags != SCEV::FlagAnyWrap) {
6220             MulOps.push_back(
6221                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6222             break;
6223           }
6224         }
6225 
6226         MulOps.push_back(getSCEV(BO->RHS));
6227         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6228         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6229           MulOps.push_back(getSCEV(BO->LHS));
6230           break;
6231         }
6232         BO = NewBO;
6233       } while (true);
6234 
6235       return getMulExpr(MulOps);
6236     }
6237     case Instruction::UDiv:
6238       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6239     case Instruction::URem:
6240       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6241     case Instruction::Sub: {
6242       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6243       if (BO->Op)
6244         Flags = getNoWrapFlagsFromUB(BO->Op);
6245       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6246     }
6247     case Instruction::And:
6248       // For an expression like x&255 that merely masks off the high bits,
6249       // use zext(trunc(x)) as the SCEV expression.
6250       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6251         if (CI->isZero())
6252           return getSCEV(BO->RHS);
6253         if (CI->isMinusOne())
6254           return getSCEV(BO->LHS);
6255         const APInt &A = CI->getValue();
6256 
6257         // Instcombine's ShrinkDemandedConstant may strip bits out of
6258         // constants, obscuring what would otherwise be a low-bits mask.
6259         // Use computeKnownBits to compute what ShrinkDemandedConstant
6260         // knew about to reconstruct a low-bits mask value.
6261         unsigned LZ = A.countLeadingZeros();
6262         unsigned TZ = A.countTrailingZeros();
6263         unsigned BitWidth = A.getBitWidth();
6264         KnownBits Known(BitWidth);
6265         computeKnownBits(BO->LHS, Known, getDataLayout(),
6266                          0, &AC, nullptr, &DT);
6267 
6268         APInt EffectiveMask =
6269             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6270         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6271           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6272           const SCEV *LHS = getSCEV(BO->LHS);
6273           const SCEV *ShiftedLHS = nullptr;
6274           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6275             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6276               // For an expression like (x * 8) & 8, simplify the multiply.
6277               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6278               unsigned GCD = std::min(MulZeros, TZ);
6279               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6280               SmallVector<const SCEV*, 4> MulOps;
6281               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6282               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6283               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6284               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6285             }
6286           }
6287           if (!ShiftedLHS)
6288             ShiftedLHS = getUDivExpr(LHS, MulCount);
6289           return getMulExpr(
6290               getZeroExtendExpr(
6291                   getTruncateExpr(ShiftedLHS,
6292                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6293                   BO->LHS->getType()),
6294               MulCount);
6295         }
6296       }
6297       break;
6298 
6299     case Instruction::Or:
6300       // If the RHS of the Or is a constant, we may have something like:
6301       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6302       // optimizations will transparently handle this case.
6303       //
6304       // In order for this transformation to be safe, the LHS must be of the
6305       // form X*(2^n) and the Or constant must be less than 2^n.
6306       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6307         const SCEV *LHS = getSCEV(BO->LHS);
6308         const APInt &CIVal = CI->getValue();
6309         if (GetMinTrailingZeros(LHS) >=
6310             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6311           // Build a plain add SCEV.
6312           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6313           // If the LHS of the add was an addrec and it has no-wrap flags,
6314           // transfer the no-wrap flags, since an or won't introduce a wrap.
6315           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6316             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6317             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6318                 OldAR->getNoWrapFlags());
6319           }
6320           return S;
6321         }
6322       }
6323       break;
6324 
6325     case Instruction::Xor:
6326       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6327         // If the RHS of xor is -1, then this is a not operation.
6328         if (CI->isMinusOne())
6329           return getNotSCEV(getSCEV(BO->LHS));
6330 
6331         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6332         // This is a variant of the check for xor with -1, and it handles
6333         // the case where instcombine has trimmed non-demanded bits out
6334         // of an xor with -1.
6335         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6336           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6337             if (LBO->getOpcode() == Instruction::And &&
6338                 LCI->getValue() == CI->getValue())
6339               if (const SCEVZeroExtendExpr *Z =
6340                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6341                 Type *UTy = BO->LHS->getType();
6342                 const SCEV *Z0 = Z->getOperand();
6343                 Type *Z0Ty = Z0->getType();
6344                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6345 
6346                 // If C is a low-bits mask, the zero extend is serving to
6347                 // mask off the high bits. Complement the operand and
6348                 // re-apply the zext.
6349                 if (CI->getValue().isMask(Z0TySize))
6350                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6351 
6352                 // If C is a single bit, it may be in the sign-bit position
6353                 // before the zero-extend. In this case, represent the xor
6354                 // using an add, which is equivalent, and re-apply the zext.
6355                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6356                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6357                     Trunc.isSignMask())
6358                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6359                                            UTy);
6360               }
6361       }
6362       break;
6363 
6364     case Instruction::Shl:
6365       // Turn shift left of a constant amount into a multiply.
6366       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6367         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6368 
6369         // If the shift count is not less than the bitwidth, the result of
6370         // the shift is undefined. Don't try to analyze it, because the
6371         // resolution chosen here may differ from the resolution chosen in
6372         // other parts of the compiler.
6373         if (SA->getValue().uge(BitWidth))
6374           break;
6375 
6376         // It is currently not resolved how to interpret NSW for left
6377         // shift by BitWidth - 1, so we avoid applying flags in that
6378         // case. Remove this check (or this comment) once the situation
6379         // is resolved. See
6380         // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6381         // and http://reviews.llvm.org/D8890 .
6382         auto Flags = SCEV::FlagAnyWrap;
6383         if (BO->Op && SA->getValue().ult(BitWidth - 1))
6384           Flags = getNoWrapFlagsFromUB(BO->Op);
6385 
6386         Constant *X = ConstantInt::get(
6387             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6388         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6389       }
6390       break;
6391 
6392     case Instruction::AShr: {
6393       // AShr X, C, where C is a constant.
6394       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6395       if (!CI)
6396         break;
6397 
6398       Type *OuterTy = BO->LHS->getType();
6399       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6400       // If the shift count is not less than the bitwidth, the result of
6401       // the shift is undefined. Don't try to analyze it, because the
6402       // resolution chosen here may differ from the resolution chosen in
6403       // other parts of the compiler.
6404       if (CI->getValue().uge(BitWidth))
6405         break;
6406 
6407       if (CI->isZero())
6408         return getSCEV(BO->LHS); // shift by zero --> noop
6409 
6410       uint64_t AShrAmt = CI->getZExtValue();
6411       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6412 
6413       Operator *L = dyn_cast<Operator>(BO->LHS);
6414       if (L && L->getOpcode() == Instruction::Shl) {
6415         // X = Shl A, n
6416         // Y = AShr X, m
6417         // Both n and m are constant.
6418 
6419         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6420         if (L->getOperand(1) == BO->RHS)
6421           // For a two-shift sext-inreg, i.e. n = m,
6422           // use sext(trunc(x)) as the SCEV expression.
6423           return getSignExtendExpr(
6424               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6425 
6426         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6427         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6428           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6429           if (ShlAmt > AShrAmt) {
6430             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6431             // expression. We already checked that ShlAmt < BitWidth, so
6432             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6433             // ShlAmt - AShrAmt < Amt.
6434             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6435                                             ShlAmt - AShrAmt);
6436             return getSignExtendExpr(
6437                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6438                 getConstant(Mul)), OuterTy);
6439           }
6440         }
6441       }
6442       break;
6443     }
6444     }
6445   }
6446 
6447   switch (U->getOpcode()) {
6448   case Instruction::Trunc:
6449     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6450 
6451   case Instruction::ZExt:
6452     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6453 
6454   case Instruction::SExt:
6455     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6456       // The NSW flag of a subtract does not always survive the conversion to
6457       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6458       // more likely to preserve NSW and allow later AddRec optimisations.
6459       //
6460       // NOTE: This is effectively duplicating this logic from getSignExtend:
6461       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6462       // but by that point the NSW information has potentially been lost.
6463       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6464         Type *Ty = U->getType();
6465         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6466         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6467         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6468       }
6469     }
6470     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6471 
6472   case Instruction::BitCast:
6473     // BitCasts are no-op casts so we just eliminate the cast.
6474     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6475       return getSCEV(U->getOperand(0));
6476     break;
6477 
6478   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6479   // lead to pointer expressions which cannot safely be expanded to GEPs,
6480   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6481   // simplifying integer expressions.
6482 
6483   case Instruction::GetElementPtr:
6484     return createNodeForGEP(cast<GEPOperator>(U));
6485 
6486   case Instruction::PHI:
6487     return createNodeForPHI(cast<PHINode>(U));
6488 
6489   case Instruction::Select:
6490     // U can also be a select constant expr, which let fall through.  Since
6491     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6492     // constant expressions cannot have instructions as operands, we'd have
6493     // returned getUnknown for a select constant expressions anyway.
6494     if (isa<Instruction>(U))
6495       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6496                                       U->getOperand(1), U->getOperand(2));
6497     break;
6498 
6499   case Instruction::Call:
6500   case Instruction::Invoke:
6501     if (Value *RV = CallSite(U).getReturnedArgOperand())
6502       return getSCEV(RV);
6503     break;
6504   }
6505 
6506   return getUnknown(V);
6507 }
6508 
6509 //===----------------------------------------------------------------------===//
6510 //                   Iteration Count Computation Code
6511 //
6512 
6513 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6514   if (!ExitCount)
6515     return 0;
6516 
6517   ConstantInt *ExitConst = ExitCount->getValue();
6518 
6519   // Guard against huge trip counts.
6520   if (ExitConst->getValue().getActiveBits() > 32)
6521     return 0;
6522 
6523   // In case of integer overflow, this returns 0, which is correct.
6524   return ((unsigned)ExitConst->getZExtValue()) + 1;
6525 }
6526 
6527 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6528   if (BasicBlock *ExitingBB = L->getExitingBlock())
6529     return getSmallConstantTripCount(L, ExitingBB);
6530 
6531   // No trip count information for multiple exits.
6532   return 0;
6533 }
6534 
6535 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6536                                                     BasicBlock *ExitingBlock) {
6537   assert(ExitingBlock && "Must pass a non-null exiting block!");
6538   assert(L->isLoopExiting(ExitingBlock) &&
6539          "Exiting block must actually branch out of the loop!");
6540   const SCEVConstant *ExitCount =
6541       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6542   return getConstantTripCount(ExitCount);
6543 }
6544 
6545 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6546   const auto *MaxExitCount =
6547       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6548   return getConstantTripCount(MaxExitCount);
6549 }
6550 
6551 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6552   if (BasicBlock *ExitingBB = L->getExitingBlock())
6553     return getSmallConstantTripMultiple(L, ExitingBB);
6554 
6555   // No trip multiple information for multiple exits.
6556   return 0;
6557 }
6558 
6559 /// Returns the largest constant divisor of the trip count of this loop as a
6560 /// normal unsigned value, if possible. This means that the actual trip count is
6561 /// always a multiple of the returned value (don't forget the trip count could
6562 /// very well be zero as well!).
6563 ///
6564 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6565 /// multiple of a constant (which is also the case if the trip count is simply
6566 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6567 /// if the trip count is very large (>= 2^32).
6568 ///
6569 /// As explained in the comments for getSmallConstantTripCount, this assumes
6570 /// that control exits the loop via ExitingBlock.
6571 unsigned
6572 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6573                                               BasicBlock *ExitingBlock) {
6574   assert(ExitingBlock && "Must pass a non-null exiting block!");
6575   assert(L->isLoopExiting(ExitingBlock) &&
6576          "Exiting block must actually branch out of the loop!");
6577   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6578   if (ExitCount == getCouldNotCompute())
6579     return 1;
6580 
6581   // Get the trip count from the BE count by adding 1.
6582   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6583 
6584   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6585   if (!TC)
6586     // Attempt to factor more general cases. Returns the greatest power of
6587     // two divisor. If overflow happens, the trip count expression is still
6588     // divisible by the greatest power of 2 divisor returned.
6589     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6590 
6591   ConstantInt *Result = TC->getValue();
6592 
6593   // Guard against huge trip counts (this requires checking
6594   // for zero to handle the case where the trip count == -1 and the
6595   // addition wraps).
6596   if (!Result || Result->getValue().getActiveBits() > 32 ||
6597       Result->getValue().getActiveBits() == 0)
6598     return 1;
6599 
6600   return (unsigned)Result->getZExtValue();
6601 }
6602 
6603 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6604                                           BasicBlock *ExitingBlock,
6605                                           ExitCountKind Kind) {
6606   switch (Kind) {
6607   case Exact:
6608     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6609   case ConstantMaximum:
6610     return getBackedgeTakenInfo(L).getMax(ExitingBlock, this);
6611   };
6612   llvm_unreachable("Invalid ExitCountKind!");
6613 }
6614 
6615 const SCEV *
6616 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6617                                                  SCEVUnionPredicate &Preds) {
6618   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6619 }
6620 
6621 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6622                                                    ExitCountKind Kind) {
6623   switch (Kind) {
6624   case Exact:
6625     return getBackedgeTakenInfo(L).getExact(L, this);
6626   case ConstantMaximum:
6627     return getBackedgeTakenInfo(L).getMax(this);
6628   };
6629   llvm_unreachable("Invalid ExitCountKind!");
6630 }
6631 
6632 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6633   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6634 }
6635 
6636 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6637 static void
6638 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6639   BasicBlock *Header = L->getHeader();
6640 
6641   // Push all Loop-header PHIs onto the Worklist stack.
6642   for (PHINode &PN : Header->phis())
6643     Worklist.push_back(&PN);
6644 }
6645 
6646 const ScalarEvolution::BackedgeTakenInfo &
6647 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6648   auto &BTI = getBackedgeTakenInfo(L);
6649   if (BTI.hasFullInfo())
6650     return BTI;
6651 
6652   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6653 
6654   if (!Pair.second)
6655     return Pair.first->second;
6656 
6657   BackedgeTakenInfo Result =
6658       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6659 
6660   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6661 }
6662 
6663 const ScalarEvolution::BackedgeTakenInfo &
6664 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6665   // Initially insert an invalid entry for this loop. If the insertion
6666   // succeeds, proceed to actually compute a backedge-taken count and
6667   // update the value. The temporary CouldNotCompute value tells SCEV
6668   // code elsewhere that it shouldn't attempt to request a new
6669   // backedge-taken count, which could result in infinite recursion.
6670   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6671       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6672   if (!Pair.second)
6673     return Pair.first->second;
6674 
6675   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6676   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6677   // must be cleared in this scope.
6678   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6679 
6680   // In product build, there are no usage of statistic.
6681   (void)NumTripCountsComputed;
6682   (void)NumTripCountsNotComputed;
6683 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6684   const SCEV *BEExact = Result.getExact(L, this);
6685   if (BEExact != getCouldNotCompute()) {
6686     assert(isLoopInvariant(BEExact, L) &&
6687            isLoopInvariant(Result.getMax(this), L) &&
6688            "Computed backedge-taken count isn't loop invariant for loop!");
6689     ++NumTripCountsComputed;
6690   }
6691   else if (Result.getMax(this) == getCouldNotCompute() &&
6692            isa<PHINode>(L->getHeader()->begin())) {
6693     // Only count loops that have phi nodes as not being computable.
6694     ++NumTripCountsNotComputed;
6695   }
6696 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6697 
6698   // Now that we know more about the trip count for this loop, forget any
6699   // existing SCEV values for PHI nodes in this loop since they are only
6700   // conservative estimates made without the benefit of trip count
6701   // information. This is similar to the code in forgetLoop, except that
6702   // it handles SCEVUnknown PHI nodes specially.
6703   if (Result.hasAnyInfo()) {
6704     SmallVector<Instruction *, 16> Worklist;
6705     PushLoopPHIs(L, Worklist);
6706 
6707     SmallPtrSet<Instruction *, 8> Discovered;
6708     while (!Worklist.empty()) {
6709       Instruction *I = Worklist.pop_back_val();
6710 
6711       ValueExprMapType::iterator It =
6712         ValueExprMap.find_as(static_cast<Value *>(I));
6713       if (It != ValueExprMap.end()) {
6714         const SCEV *Old = It->second;
6715 
6716         // SCEVUnknown for a PHI either means that it has an unrecognized
6717         // structure, or it's a PHI that's in the progress of being computed
6718         // by createNodeForPHI.  In the former case, additional loop trip
6719         // count information isn't going to change anything. In the later
6720         // case, createNodeForPHI will perform the necessary updates on its
6721         // own when it gets to that point.
6722         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6723           eraseValueFromMap(It->first);
6724           forgetMemoizedResults(Old);
6725         }
6726         if (PHINode *PN = dyn_cast<PHINode>(I))
6727           ConstantEvolutionLoopExitValue.erase(PN);
6728       }
6729 
6730       // Since we don't need to invalidate anything for correctness and we're
6731       // only invalidating to make SCEV's results more precise, we get to stop
6732       // early to avoid invalidating too much.  This is especially important in
6733       // cases like:
6734       //
6735       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6736       // loop0:
6737       //   %pn0 = phi
6738       //   ...
6739       // loop1:
6740       //   %pn1 = phi
6741       //   ...
6742       //
6743       // where both loop0 and loop1's backedge taken count uses the SCEV
6744       // expression for %v.  If we don't have the early stop below then in cases
6745       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6746       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6747       // count for loop1, effectively nullifying SCEV's trip count cache.
6748       for (auto *U : I->users())
6749         if (auto *I = dyn_cast<Instruction>(U)) {
6750           auto *LoopForUser = LI.getLoopFor(I->getParent());
6751           if (LoopForUser && L->contains(LoopForUser) &&
6752               Discovered.insert(I).second)
6753             Worklist.push_back(I);
6754         }
6755     }
6756   }
6757 
6758   // Re-lookup the insert position, since the call to
6759   // computeBackedgeTakenCount above could result in a
6760   // recusive call to getBackedgeTakenInfo (on a different
6761   // loop), which would invalidate the iterator computed
6762   // earlier.
6763   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6764 }
6765 
6766 void ScalarEvolution::forgetAllLoops() {
6767   // This method is intended to forget all info about loops. It should
6768   // invalidate caches as if the following happened:
6769   // - The trip counts of all loops have changed arbitrarily
6770   // - Every llvm::Value has been updated in place to produce a different
6771   // result.
6772   BackedgeTakenCounts.clear();
6773   PredicatedBackedgeTakenCounts.clear();
6774   LoopPropertiesCache.clear();
6775   ConstantEvolutionLoopExitValue.clear();
6776   ValueExprMap.clear();
6777   ValuesAtScopes.clear();
6778   LoopDispositions.clear();
6779   BlockDispositions.clear();
6780   UnsignedRanges.clear();
6781   SignedRanges.clear();
6782   ExprValueMap.clear();
6783   HasRecMap.clear();
6784   MinTrailingZerosCache.clear();
6785   PredicatedSCEVRewrites.clear();
6786 }
6787 
6788 void ScalarEvolution::forgetLoop(const Loop *L) {
6789   // Drop any stored trip count value.
6790   auto RemoveLoopFromBackedgeMap =
6791       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6792         auto BTCPos = Map.find(L);
6793         if (BTCPos != Map.end()) {
6794           BTCPos->second.clear();
6795           Map.erase(BTCPos);
6796         }
6797       };
6798 
6799   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6800   SmallVector<Instruction *, 32> Worklist;
6801   SmallPtrSet<Instruction *, 16> Visited;
6802 
6803   // Iterate over all the loops and sub-loops to drop SCEV information.
6804   while (!LoopWorklist.empty()) {
6805     auto *CurrL = LoopWorklist.pop_back_val();
6806 
6807     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6808     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6809 
6810     // Drop information about predicated SCEV rewrites for this loop.
6811     for (auto I = PredicatedSCEVRewrites.begin();
6812          I != PredicatedSCEVRewrites.end();) {
6813       std::pair<const SCEV *, const Loop *> Entry = I->first;
6814       if (Entry.second == CurrL)
6815         PredicatedSCEVRewrites.erase(I++);
6816       else
6817         ++I;
6818     }
6819 
6820     auto LoopUsersItr = LoopUsers.find(CurrL);
6821     if (LoopUsersItr != LoopUsers.end()) {
6822       for (auto *S : LoopUsersItr->second)
6823         forgetMemoizedResults(S);
6824       LoopUsers.erase(LoopUsersItr);
6825     }
6826 
6827     // Drop information about expressions based on loop-header PHIs.
6828     PushLoopPHIs(CurrL, Worklist);
6829 
6830     while (!Worklist.empty()) {
6831       Instruction *I = Worklist.pop_back_val();
6832       if (!Visited.insert(I).second)
6833         continue;
6834 
6835       ValueExprMapType::iterator It =
6836           ValueExprMap.find_as(static_cast<Value *>(I));
6837       if (It != ValueExprMap.end()) {
6838         eraseValueFromMap(It->first);
6839         forgetMemoizedResults(It->second);
6840         if (PHINode *PN = dyn_cast<PHINode>(I))
6841           ConstantEvolutionLoopExitValue.erase(PN);
6842       }
6843 
6844       PushDefUseChildren(I, Worklist);
6845     }
6846 
6847     LoopPropertiesCache.erase(CurrL);
6848     // Forget all contained loops too, to avoid dangling entries in the
6849     // ValuesAtScopes map.
6850     LoopWorklist.append(CurrL->begin(), CurrL->end());
6851   }
6852 }
6853 
6854 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6855   while (Loop *Parent = L->getParentLoop())
6856     L = Parent;
6857   forgetLoop(L);
6858 }
6859 
6860 void ScalarEvolution::forgetValue(Value *V) {
6861   Instruction *I = dyn_cast<Instruction>(V);
6862   if (!I) return;
6863 
6864   // Drop information about expressions based on loop-header PHIs.
6865   SmallVector<Instruction *, 16> Worklist;
6866   Worklist.push_back(I);
6867 
6868   SmallPtrSet<Instruction *, 8> Visited;
6869   while (!Worklist.empty()) {
6870     I = Worklist.pop_back_val();
6871     if (!Visited.insert(I).second)
6872       continue;
6873 
6874     ValueExprMapType::iterator It =
6875       ValueExprMap.find_as(static_cast<Value *>(I));
6876     if (It != ValueExprMap.end()) {
6877       eraseValueFromMap(It->first);
6878       forgetMemoizedResults(It->second);
6879       if (PHINode *PN = dyn_cast<PHINode>(I))
6880         ConstantEvolutionLoopExitValue.erase(PN);
6881     }
6882 
6883     PushDefUseChildren(I, Worklist);
6884   }
6885 }
6886 
6887 /// Get the exact loop backedge taken count considering all loop exits. A
6888 /// computable result can only be returned for loops with all exiting blocks
6889 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6890 /// is never skipped. This is a valid assumption as long as the loop exits via
6891 /// that test. For precise results, it is the caller's responsibility to specify
6892 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6893 const SCEV *
6894 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6895                                              SCEVUnionPredicate *Preds) const {
6896   // If any exits were not computable, the loop is not computable.
6897   if (!isComplete() || ExitNotTaken.empty())
6898     return SE->getCouldNotCompute();
6899 
6900   const BasicBlock *Latch = L->getLoopLatch();
6901   // All exiting blocks we have collected must dominate the only backedge.
6902   if (!Latch)
6903     return SE->getCouldNotCompute();
6904 
6905   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6906   // count is simply a minimum out of all these calculated exit counts.
6907   SmallVector<const SCEV *, 2> Ops;
6908   for (auto &ENT : ExitNotTaken) {
6909     const SCEV *BECount = ENT.ExactNotTaken;
6910     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6911     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6912            "We should only have known counts for exiting blocks that dominate "
6913            "latch!");
6914 
6915     Ops.push_back(BECount);
6916 
6917     if (Preds && !ENT.hasAlwaysTruePredicate())
6918       Preds->add(ENT.Predicate.get());
6919 
6920     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6921            "Predicate should be always true!");
6922   }
6923 
6924   return SE->getUMinFromMismatchedTypes(Ops);
6925 }
6926 
6927 /// Get the exact not taken count for this loop exit.
6928 const SCEV *
6929 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6930                                              ScalarEvolution *SE) const {
6931   for (auto &ENT : ExitNotTaken)
6932     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6933       return ENT.ExactNotTaken;
6934 
6935   return SE->getCouldNotCompute();
6936 }
6937 
6938 const SCEV *
6939 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock,
6940                                            ScalarEvolution *SE) const {
6941   for (auto &ENT : ExitNotTaken)
6942     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6943       return ENT.MaxNotTaken;
6944 
6945   return SE->getCouldNotCompute();
6946 }
6947 
6948 /// getMax - Get the max backedge taken count for the loop.
6949 const SCEV *
6950 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6951   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6952     return !ENT.hasAlwaysTruePredicate();
6953   };
6954 
6955   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6956     return SE->getCouldNotCompute();
6957 
6958   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6959          "No point in having a non-constant max backedge taken count!");
6960   return getMax();
6961 }
6962 
6963 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6964   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6965     return !ENT.hasAlwaysTruePredicate();
6966   };
6967   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6968 }
6969 
6970 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6971                                                     ScalarEvolution *SE) const {
6972   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6973       SE->hasOperand(getMax(), S))
6974     return true;
6975 
6976   for (auto &ENT : ExitNotTaken)
6977     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6978         SE->hasOperand(ENT.ExactNotTaken, S))
6979       return true;
6980 
6981   return false;
6982 }
6983 
6984 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6985     : ExactNotTaken(E), MaxNotTaken(E) {
6986   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6987           isa<SCEVConstant>(MaxNotTaken)) &&
6988          "No point in having a non-constant max backedge taken count!");
6989 }
6990 
6991 ScalarEvolution::ExitLimit::ExitLimit(
6992     const SCEV *E, const SCEV *M, bool MaxOrZero,
6993     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6994     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6995   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6996           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6997          "Exact is not allowed to be less precise than Max");
6998   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6999           isa<SCEVConstant>(MaxNotTaken)) &&
7000          "No point in having a non-constant max backedge taken count!");
7001   for (auto *PredSet : PredSetList)
7002     for (auto *P : *PredSet)
7003       addPredicate(P);
7004 }
7005 
7006 ScalarEvolution::ExitLimit::ExitLimit(
7007     const SCEV *E, const SCEV *M, bool MaxOrZero,
7008     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7009     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7010   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7011           isa<SCEVConstant>(MaxNotTaken)) &&
7012          "No point in having a non-constant max backedge taken count!");
7013 }
7014 
7015 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7016                                       bool MaxOrZero)
7017     : ExitLimit(E, M, MaxOrZero, None) {
7018   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7019           isa<SCEVConstant>(MaxNotTaken)) &&
7020          "No point in having a non-constant max backedge taken count!");
7021 }
7022 
7023 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7024 /// computable exit into a persistent ExitNotTakenInfo array.
7025 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7026     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
7027         ExitCounts,
7028     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
7029     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
7030   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7031 
7032   ExitNotTaken.reserve(ExitCounts.size());
7033   std::transform(
7034       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7035       [&](const EdgeExitInfo &EEI) {
7036         BasicBlock *ExitBB = EEI.first;
7037         const ExitLimit &EL = EEI.second;
7038         if (EL.Predicates.empty())
7039           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7040                                   nullptr);
7041 
7042         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7043         for (auto *Pred : EL.Predicates)
7044           Predicate->add(Pred);
7045 
7046         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7047                                 std::move(Predicate));
7048       });
7049   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
7050          "No point in having a non-constant max backedge taken count!");
7051 }
7052 
7053 /// Invalidate this result and free the ExitNotTakenInfo array.
7054 void ScalarEvolution::BackedgeTakenInfo::clear() {
7055   ExitNotTaken.clear();
7056 }
7057 
7058 /// Compute the number of times the backedge of the specified loop will execute.
7059 ScalarEvolution::BackedgeTakenInfo
7060 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7061                                            bool AllowPredicates) {
7062   SmallVector<BasicBlock *, 8> ExitingBlocks;
7063   L->getExitingBlocks(ExitingBlocks);
7064 
7065   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7066 
7067   SmallVector<EdgeExitInfo, 4> ExitCounts;
7068   bool CouldComputeBECount = true;
7069   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7070   const SCEV *MustExitMaxBECount = nullptr;
7071   const SCEV *MayExitMaxBECount = nullptr;
7072   bool MustExitMaxOrZero = false;
7073 
7074   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7075   // and compute maxBECount.
7076   // Do a union of all the predicates here.
7077   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7078     BasicBlock *ExitBB = ExitingBlocks[i];
7079 
7080     // We canonicalize untaken exits to br (constant), ignore them so that
7081     // proving an exit untaken doesn't negatively impact our ability to reason
7082     // about the loop as whole.
7083     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7084       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7085         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7086         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7087           continue;
7088       }
7089 
7090     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7091 
7092     assert((AllowPredicates || EL.Predicates.empty()) &&
7093            "Predicated exit limit when predicates are not allowed!");
7094 
7095     // 1. For each exit that can be computed, add an entry to ExitCounts.
7096     // CouldComputeBECount is true only if all exits can be computed.
7097     if (EL.ExactNotTaken == getCouldNotCompute())
7098       // We couldn't compute an exact value for this exit, so
7099       // we won't be able to compute an exact value for the loop.
7100       CouldComputeBECount = false;
7101     else
7102       ExitCounts.emplace_back(ExitBB, EL);
7103 
7104     // 2. Derive the loop's MaxBECount from each exit's max number of
7105     // non-exiting iterations. Partition the loop exits into two kinds:
7106     // LoopMustExits and LoopMayExits.
7107     //
7108     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7109     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7110     // MaxBECount is the minimum EL.MaxNotTaken of computable
7111     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7112     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7113     // computable EL.MaxNotTaken.
7114     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7115         DT.dominates(ExitBB, Latch)) {
7116       if (!MustExitMaxBECount) {
7117         MustExitMaxBECount = EL.MaxNotTaken;
7118         MustExitMaxOrZero = EL.MaxOrZero;
7119       } else {
7120         MustExitMaxBECount =
7121             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7122       }
7123     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7124       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7125         MayExitMaxBECount = EL.MaxNotTaken;
7126       else {
7127         MayExitMaxBECount =
7128             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7129       }
7130     }
7131   }
7132   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7133     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7134   // The loop backedge will be taken the maximum or zero times if there's
7135   // a single exit that must be taken the maximum or zero times.
7136   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7137   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7138                            MaxBECount, MaxOrZero);
7139 }
7140 
7141 ScalarEvolution::ExitLimit
7142 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7143                                       bool AllowPredicates) {
7144   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7145   // If our exiting block does not dominate the latch, then its connection with
7146   // loop's exit limit may be far from trivial.
7147   const BasicBlock *Latch = L->getLoopLatch();
7148   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7149     return getCouldNotCompute();
7150 
7151   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7152   Instruction *Term = ExitingBlock->getTerminator();
7153   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7154     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7155     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7156     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7157            "It should have one successor in loop and one exit block!");
7158     // Proceed to the next level to examine the exit condition expression.
7159     return computeExitLimitFromCond(
7160         L, BI->getCondition(), ExitIfTrue,
7161         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7162   }
7163 
7164   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7165     // For switch, make sure that there is a single exit from the loop.
7166     BasicBlock *Exit = nullptr;
7167     for (auto *SBB : successors(ExitingBlock))
7168       if (!L->contains(SBB)) {
7169         if (Exit) // Multiple exit successors.
7170           return getCouldNotCompute();
7171         Exit = SBB;
7172       }
7173     assert(Exit && "Exiting block must have at least one exit");
7174     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7175                                                 /*ControlsExit=*/IsOnlyExit);
7176   }
7177 
7178   return getCouldNotCompute();
7179 }
7180 
7181 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7182     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7183     bool ControlsExit, bool AllowPredicates) {
7184   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7185   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7186                                         ControlsExit, AllowPredicates);
7187 }
7188 
7189 Optional<ScalarEvolution::ExitLimit>
7190 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7191                                       bool ExitIfTrue, bool ControlsExit,
7192                                       bool AllowPredicates) {
7193   (void)this->L;
7194   (void)this->ExitIfTrue;
7195   (void)this->AllowPredicates;
7196 
7197   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7198          this->AllowPredicates == AllowPredicates &&
7199          "Variance in assumed invariant key components!");
7200   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7201   if (Itr == TripCountMap.end())
7202     return None;
7203   return Itr->second;
7204 }
7205 
7206 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7207                                              bool ExitIfTrue,
7208                                              bool ControlsExit,
7209                                              bool AllowPredicates,
7210                                              const ExitLimit &EL) {
7211   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7212          this->AllowPredicates == AllowPredicates &&
7213          "Variance in assumed invariant key components!");
7214 
7215   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7216   assert(InsertResult.second && "Expected successful insertion!");
7217   (void)InsertResult;
7218   (void)ExitIfTrue;
7219 }
7220 
7221 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7222     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7223     bool ControlsExit, bool AllowPredicates) {
7224 
7225   if (auto MaybeEL =
7226           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7227     return *MaybeEL;
7228 
7229   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7230                                               ControlsExit, AllowPredicates);
7231   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7232   return EL;
7233 }
7234 
7235 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7236     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7237     bool ControlsExit, bool AllowPredicates) {
7238   // Check if the controlling expression for this loop is an And or Or.
7239   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7240     if (BO->getOpcode() == Instruction::And) {
7241       // Recurse on the operands of the and.
7242       bool EitherMayExit = !ExitIfTrue;
7243       ExitLimit EL0 = computeExitLimitFromCondCached(
7244           Cache, L, BO->getOperand(0), ExitIfTrue,
7245           ControlsExit && !EitherMayExit, AllowPredicates);
7246       ExitLimit EL1 = computeExitLimitFromCondCached(
7247           Cache, L, BO->getOperand(1), ExitIfTrue,
7248           ControlsExit && !EitherMayExit, AllowPredicates);
7249       const SCEV *BECount = getCouldNotCompute();
7250       const SCEV *MaxBECount = getCouldNotCompute();
7251       if (EitherMayExit) {
7252         // Both conditions must be true for the loop to continue executing.
7253         // Choose the less conservative count.
7254         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7255             EL1.ExactNotTaken == getCouldNotCompute())
7256           BECount = getCouldNotCompute();
7257         else
7258           BECount =
7259               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7260         if (EL0.MaxNotTaken == getCouldNotCompute())
7261           MaxBECount = EL1.MaxNotTaken;
7262         else if (EL1.MaxNotTaken == getCouldNotCompute())
7263           MaxBECount = EL0.MaxNotTaken;
7264         else
7265           MaxBECount =
7266               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7267       } else {
7268         // Both conditions must be true at the same time for the loop to exit.
7269         // For now, be conservative.
7270         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7271           MaxBECount = EL0.MaxNotTaken;
7272         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7273           BECount = EL0.ExactNotTaken;
7274       }
7275 
7276       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7277       // to be more aggressive when computing BECount than when computing
7278       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7279       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7280       // to not.
7281       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7282           !isa<SCEVCouldNotCompute>(BECount))
7283         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7284 
7285       return ExitLimit(BECount, MaxBECount, false,
7286                        {&EL0.Predicates, &EL1.Predicates});
7287     }
7288     if (BO->getOpcode() == Instruction::Or) {
7289       // Recurse on the operands of the or.
7290       bool EitherMayExit = ExitIfTrue;
7291       ExitLimit EL0 = computeExitLimitFromCondCached(
7292           Cache, L, BO->getOperand(0), ExitIfTrue,
7293           ControlsExit && !EitherMayExit, AllowPredicates);
7294       ExitLimit EL1 = computeExitLimitFromCondCached(
7295           Cache, L, BO->getOperand(1), ExitIfTrue,
7296           ControlsExit && !EitherMayExit, AllowPredicates);
7297       const SCEV *BECount = getCouldNotCompute();
7298       const SCEV *MaxBECount = getCouldNotCompute();
7299       if (EitherMayExit) {
7300         // Both conditions must be false for the loop to continue executing.
7301         // Choose the less conservative count.
7302         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7303             EL1.ExactNotTaken == getCouldNotCompute())
7304           BECount = getCouldNotCompute();
7305         else
7306           BECount =
7307               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7308         if (EL0.MaxNotTaken == getCouldNotCompute())
7309           MaxBECount = EL1.MaxNotTaken;
7310         else if (EL1.MaxNotTaken == getCouldNotCompute())
7311           MaxBECount = EL0.MaxNotTaken;
7312         else
7313           MaxBECount =
7314               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7315       } else {
7316         // Both conditions must be false at the same time for the loop to exit.
7317         // For now, be conservative.
7318         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7319           MaxBECount = EL0.MaxNotTaken;
7320         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7321           BECount = EL0.ExactNotTaken;
7322       }
7323       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7324       // to be more aggressive when computing BECount than when computing
7325       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7326       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7327       // to not.
7328       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7329           !isa<SCEVCouldNotCompute>(BECount))
7330         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7331 
7332       return ExitLimit(BECount, MaxBECount, false,
7333                        {&EL0.Predicates, &EL1.Predicates});
7334     }
7335   }
7336 
7337   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7338   // Proceed to the next level to examine the icmp.
7339   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7340     ExitLimit EL =
7341         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7342     if (EL.hasFullInfo() || !AllowPredicates)
7343       return EL;
7344 
7345     // Try again, but use SCEV predicates this time.
7346     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7347                                     /*AllowPredicates=*/true);
7348   }
7349 
7350   // Check for a constant condition. These are normally stripped out by
7351   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7352   // preserve the CFG and is temporarily leaving constant conditions
7353   // in place.
7354   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7355     if (ExitIfTrue == !CI->getZExtValue())
7356       // The backedge is always taken.
7357       return getCouldNotCompute();
7358     else
7359       // The backedge is never taken.
7360       return getZero(CI->getType());
7361   }
7362 
7363   // If it's not an integer or pointer comparison then compute it the hard way.
7364   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7365 }
7366 
7367 ScalarEvolution::ExitLimit
7368 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7369                                           ICmpInst *ExitCond,
7370                                           bool ExitIfTrue,
7371                                           bool ControlsExit,
7372                                           bool AllowPredicates) {
7373   // If the condition was exit on true, convert the condition to exit on false
7374   ICmpInst::Predicate Pred;
7375   if (!ExitIfTrue)
7376     Pred = ExitCond->getPredicate();
7377   else
7378     Pred = ExitCond->getInversePredicate();
7379   const ICmpInst::Predicate OriginalPred = Pred;
7380 
7381   // Handle common loops like: for (X = "string"; *X; ++X)
7382   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7383     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7384       ExitLimit ItCnt =
7385         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7386       if (ItCnt.hasAnyInfo())
7387         return ItCnt;
7388     }
7389 
7390   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7391   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7392 
7393   // Try to evaluate any dependencies out of the loop.
7394   LHS = getSCEVAtScope(LHS, L);
7395   RHS = getSCEVAtScope(RHS, L);
7396 
7397   // At this point, we would like to compute how many iterations of the
7398   // loop the predicate will return true for these inputs.
7399   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7400     // If there is a loop-invariant, force it into the RHS.
7401     std::swap(LHS, RHS);
7402     Pred = ICmpInst::getSwappedPredicate(Pred);
7403   }
7404 
7405   // Simplify the operands before analyzing them.
7406   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7407 
7408   // If we have a comparison of a chrec against a constant, try to use value
7409   // ranges to answer this query.
7410   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7411     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7412       if (AddRec->getLoop() == L) {
7413         // Form the constant range.
7414         ConstantRange CompRange =
7415             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7416 
7417         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7418         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7419       }
7420 
7421   switch (Pred) {
7422   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7423     // Convert to: while (X-Y != 0)
7424     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7425                                 AllowPredicates);
7426     if (EL.hasAnyInfo()) return EL;
7427     break;
7428   }
7429   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7430     // Convert to: while (X-Y == 0)
7431     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7432     if (EL.hasAnyInfo()) return EL;
7433     break;
7434   }
7435   case ICmpInst::ICMP_SLT:
7436   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7437     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7438     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7439                                     AllowPredicates);
7440     if (EL.hasAnyInfo()) return EL;
7441     break;
7442   }
7443   case ICmpInst::ICMP_SGT:
7444   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7445     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7446     ExitLimit EL =
7447         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7448                             AllowPredicates);
7449     if (EL.hasAnyInfo()) return EL;
7450     break;
7451   }
7452   default:
7453     break;
7454   }
7455 
7456   auto *ExhaustiveCount =
7457       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7458 
7459   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7460     return ExhaustiveCount;
7461 
7462   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7463                                       ExitCond->getOperand(1), L, OriginalPred);
7464 }
7465 
7466 ScalarEvolution::ExitLimit
7467 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7468                                                       SwitchInst *Switch,
7469                                                       BasicBlock *ExitingBlock,
7470                                                       bool ControlsExit) {
7471   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7472 
7473   // Give up if the exit is the default dest of a switch.
7474   if (Switch->getDefaultDest() == ExitingBlock)
7475     return getCouldNotCompute();
7476 
7477   assert(L->contains(Switch->getDefaultDest()) &&
7478          "Default case must not exit the loop!");
7479   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7480   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7481 
7482   // while (X != Y) --> while (X-Y != 0)
7483   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7484   if (EL.hasAnyInfo())
7485     return EL;
7486 
7487   return getCouldNotCompute();
7488 }
7489 
7490 static ConstantInt *
7491 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7492                                 ScalarEvolution &SE) {
7493   const SCEV *InVal = SE.getConstant(C);
7494   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7495   assert(isa<SCEVConstant>(Val) &&
7496          "Evaluation of SCEV at constant didn't fold correctly?");
7497   return cast<SCEVConstant>(Val)->getValue();
7498 }
7499 
7500 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7501 /// compute the backedge execution count.
7502 ScalarEvolution::ExitLimit
7503 ScalarEvolution::computeLoadConstantCompareExitLimit(
7504   LoadInst *LI,
7505   Constant *RHS,
7506   const Loop *L,
7507   ICmpInst::Predicate predicate) {
7508   if (LI->isVolatile()) return getCouldNotCompute();
7509 
7510   // Check to see if the loaded pointer is a getelementptr of a global.
7511   // TODO: Use SCEV instead of manually grubbing with GEPs.
7512   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7513   if (!GEP) return getCouldNotCompute();
7514 
7515   // Make sure that it is really a constant global we are gepping, with an
7516   // initializer, and make sure the first IDX is really 0.
7517   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7518   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7519       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7520       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7521     return getCouldNotCompute();
7522 
7523   // Okay, we allow one non-constant index into the GEP instruction.
7524   Value *VarIdx = nullptr;
7525   std::vector<Constant*> Indexes;
7526   unsigned VarIdxNum = 0;
7527   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7528     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7529       Indexes.push_back(CI);
7530     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7531       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7532       VarIdx = GEP->getOperand(i);
7533       VarIdxNum = i-2;
7534       Indexes.push_back(nullptr);
7535     }
7536 
7537   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7538   if (!VarIdx)
7539     return getCouldNotCompute();
7540 
7541   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7542   // Check to see if X is a loop variant variable value now.
7543   const SCEV *Idx = getSCEV(VarIdx);
7544   Idx = getSCEVAtScope(Idx, L);
7545 
7546   // We can only recognize very limited forms of loop index expressions, in
7547   // particular, only affine AddRec's like {C1,+,C2}.
7548   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7549   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7550       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7551       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7552     return getCouldNotCompute();
7553 
7554   unsigned MaxSteps = MaxBruteForceIterations;
7555   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7556     ConstantInt *ItCst = ConstantInt::get(
7557                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7558     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7559 
7560     // Form the GEP offset.
7561     Indexes[VarIdxNum] = Val;
7562 
7563     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7564                                                          Indexes);
7565     if (!Result) break;  // Cannot compute!
7566 
7567     // Evaluate the condition for this iteration.
7568     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7569     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7570     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7571       ++NumArrayLenItCounts;
7572       return getConstant(ItCst);   // Found terminating iteration!
7573     }
7574   }
7575   return getCouldNotCompute();
7576 }
7577 
7578 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7579     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7580   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7581   if (!RHS)
7582     return getCouldNotCompute();
7583 
7584   const BasicBlock *Latch = L->getLoopLatch();
7585   if (!Latch)
7586     return getCouldNotCompute();
7587 
7588   const BasicBlock *Predecessor = L->getLoopPredecessor();
7589   if (!Predecessor)
7590     return getCouldNotCompute();
7591 
7592   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7593   // Return LHS in OutLHS and shift_opt in OutOpCode.
7594   auto MatchPositiveShift =
7595       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7596 
7597     using namespace PatternMatch;
7598 
7599     ConstantInt *ShiftAmt;
7600     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7601       OutOpCode = Instruction::LShr;
7602     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7603       OutOpCode = Instruction::AShr;
7604     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7605       OutOpCode = Instruction::Shl;
7606     else
7607       return false;
7608 
7609     return ShiftAmt->getValue().isStrictlyPositive();
7610   };
7611 
7612   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7613   //
7614   // loop:
7615   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7616   //   %iv.shifted = lshr i32 %iv, <positive constant>
7617   //
7618   // Return true on a successful match.  Return the corresponding PHI node (%iv
7619   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7620   auto MatchShiftRecurrence =
7621       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7622     Optional<Instruction::BinaryOps> PostShiftOpCode;
7623 
7624     {
7625       Instruction::BinaryOps OpC;
7626       Value *V;
7627 
7628       // If we encounter a shift instruction, "peel off" the shift operation,
7629       // and remember that we did so.  Later when we inspect %iv's backedge
7630       // value, we will make sure that the backedge value uses the same
7631       // operation.
7632       //
7633       // Note: the peeled shift operation does not have to be the same
7634       // instruction as the one feeding into the PHI's backedge value.  We only
7635       // really care about it being the same *kind* of shift instruction --
7636       // that's all that is required for our later inferences to hold.
7637       if (MatchPositiveShift(LHS, V, OpC)) {
7638         PostShiftOpCode = OpC;
7639         LHS = V;
7640       }
7641     }
7642 
7643     PNOut = dyn_cast<PHINode>(LHS);
7644     if (!PNOut || PNOut->getParent() != L->getHeader())
7645       return false;
7646 
7647     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7648     Value *OpLHS;
7649 
7650     return
7651         // The backedge value for the PHI node must be a shift by a positive
7652         // amount
7653         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7654 
7655         // of the PHI node itself
7656         OpLHS == PNOut &&
7657 
7658         // and the kind of shift should be match the kind of shift we peeled
7659         // off, if any.
7660         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7661   };
7662 
7663   PHINode *PN;
7664   Instruction::BinaryOps OpCode;
7665   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7666     return getCouldNotCompute();
7667 
7668   const DataLayout &DL = getDataLayout();
7669 
7670   // The key rationale for this optimization is that for some kinds of shift
7671   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7672   // within a finite number of iterations.  If the condition guarding the
7673   // backedge (in the sense that the backedge is taken if the condition is true)
7674   // is false for the value the shift recurrence stabilizes to, then we know
7675   // that the backedge is taken only a finite number of times.
7676 
7677   ConstantInt *StableValue = nullptr;
7678   switch (OpCode) {
7679   default:
7680     llvm_unreachable("Impossible case!");
7681 
7682   case Instruction::AShr: {
7683     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7684     // bitwidth(K) iterations.
7685     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7686     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7687                                        Predecessor->getTerminator(), &DT);
7688     auto *Ty = cast<IntegerType>(RHS->getType());
7689     if (Known.isNonNegative())
7690       StableValue = ConstantInt::get(Ty, 0);
7691     else if (Known.isNegative())
7692       StableValue = ConstantInt::get(Ty, -1, true);
7693     else
7694       return getCouldNotCompute();
7695 
7696     break;
7697   }
7698   case Instruction::LShr:
7699   case Instruction::Shl:
7700     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7701     // stabilize to 0 in at most bitwidth(K) iterations.
7702     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7703     break;
7704   }
7705 
7706   auto *Result =
7707       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7708   assert(Result->getType()->isIntegerTy(1) &&
7709          "Otherwise cannot be an operand to a branch instruction");
7710 
7711   if (Result->isZeroValue()) {
7712     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7713     const SCEV *UpperBound =
7714         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7715     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7716   }
7717 
7718   return getCouldNotCompute();
7719 }
7720 
7721 /// Return true if we can constant fold an instruction of the specified type,
7722 /// assuming that all operands were constants.
7723 static bool CanConstantFold(const Instruction *I) {
7724   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7725       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7726       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
7727     return true;
7728 
7729   if (const CallInst *CI = dyn_cast<CallInst>(I))
7730     if (const Function *F = CI->getCalledFunction())
7731       return canConstantFoldCallTo(CI, F);
7732   return false;
7733 }
7734 
7735 /// Determine whether this instruction can constant evolve within this loop
7736 /// assuming its operands can all constant evolve.
7737 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7738   // An instruction outside of the loop can't be derived from a loop PHI.
7739   if (!L->contains(I)) return false;
7740 
7741   if (isa<PHINode>(I)) {
7742     // We don't currently keep track of the control flow needed to evaluate
7743     // PHIs, so we cannot handle PHIs inside of loops.
7744     return L->getHeader() == I->getParent();
7745   }
7746 
7747   // If we won't be able to constant fold this expression even if the operands
7748   // are constants, bail early.
7749   return CanConstantFold(I);
7750 }
7751 
7752 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7753 /// recursing through each instruction operand until reaching a loop header phi.
7754 static PHINode *
7755 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7756                                DenseMap<Instruction *, PHINode *> &PHIMap,
7757                                unsigned Depth) {
7758   if (Depth > MaxConstantEvolvingDepth)
7759     return nullptr;
7760 
7761   // Otherwise, we can evaluate this instruction if all of its operands are
7762   // constant or derived from a PHI node themselves.
7763   PHINode *PHI = nullptr;
7764   for (Value *Op : UseInst->operands()) {
7765     if (isa<Constant>(Op)) continue;
7766 
7767     Instruction *OpInst = dyn_cast<Instruction>(Op);
7768     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7769 
7770     PHINode *P = dyn_cast<PHINode>(OpInst);
7771     if (!P)
7772       // If this operand is already visited, reuse the prior result.
7773       // We may have P != PHI if this is the deepest point at which the
7774       // inconsistent paths meet.
7775       P = PHIMap.lookup(OpInst);
7776     if (!P) {
7777       // Recurse and memoize the results, whether a phi is found or not.
7778       // This recursive call invalidates pointers into PHIMap.
7779       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7780       PHIMap[OpInst] = P;
7781     }
7782     if (!P)
7783       return nullptr;  // Not evolving from PHI
7784     if (PHI && PHI != P)
7785       return nullptr;  // Evolving from multiple different PHIs.
7786     PHI = P;
7787   }
7788   // This is a expression evolving from a constant PHI!
7789   return PHI;
7790 }
7791 
7792 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7793 /// in the loop that V is derived from.  We allow arbitrary operations along the
7794 /// way, but the operands of an operation must either be constants or a value
7795 /// derived from a constant PHI.  If this expression does not fit with these
7796 /// constraints, return null.
7797 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7798   Instruction *I = dyn_cast<Instruction>(V);
7799   if (!I || !canConstantEvolve(I, L)) return nullptr;
7800 
7801   if (PHINode *PN = dyn_cast<PHINode>(I))
7802     return PN;
7803 
7804   // Record non-constant instructions contained by the loop.
7805   DenseMap<Instruction *, PHINode *> PHIMap;
7806   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7807 }
7808 
7809 /// EvaluateExpression - Given an expression that passes the
7810 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7811 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7812 /// reason, return null.
7813 static Constant *EvaluateExpression(Value *V, const Loop *L,
7814                                     DenseMap<Instruction *, Constant *> &Vals,
7815                                     const DataLayout &DL,
7816                                     const TargetLibraryInfo *TLI) {
7817   // Convenient constant check, but redundant for recursive calls.
7818   if (Constant *C = dyn_cast<Constant>(V)) return C;
7819   Instruction *I = dyn_cast<Instruction>(V);
7820   if (!I) return nullptr;
7821 
7822   if (Constant *C = Vals.lookup(I)) return C;
7823 
7824   // An instruction inside the loop depends on a value outside the loop that we
7825   // weren't given a mapping for, or a value such as a call inside the loop.
7826   if (!canConstantEvolve(I, L)) return nullptr;
7827 
7828   // An unmapped PHI can be due to a branch or another loop inside this loop,
7829   // or due to this not being the initial iteration through a loop where we
7830   // couldn't compute the evolution of this particular PHI last time.
7831   if (isa<PHINode>(I)) return nullptr;
7832 
7833   std::vector<Constant*> Operands(I->getNumOperands());
7834 
7835   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7836     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7837     if (!Operand) {
7838       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7839       if (!Operands[i]) return nullptr;
7840       continue;
7841     }
7842     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7843     Vals[Operand] = C;
7844     if (!C) return nullptr;
7845     Operands[i] = C;
7846   }
7847 
7848   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7849     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7850                                            Operands[1], DL, TLI);
7851   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7852     if (!LI->isVolatile())
7853       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7854   }
7855   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7856 }
7857 
7858 
7859 // If every incoming value to PN except the one for BB is a specific Constant,
7860 // return that, else return nullptr.
7861 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7862   Constant *IncomingVal = nullptr;
7863 
7864   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7865     if (PN->getIncomingBlock(i) == BB)
7866       continue;
7867 
7868     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7869     if (!CurrentVal)
7870       return nullptr;
7871 
7872     if (IncomingVal != CurrentVal) {
7873       if (IncomingVal)
7874         return nullptr;
7875       IncomingVal = CurrentVal;
7876     }
7877   }
7878 
7879   return IncomingVal;
7880 }
7881 
7882 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7883 /// in the header of its containing loop, we know the loop executes a
7884 /// constant number of times, and the PHI node is just a recurrence
7885 /// involving constants, fold it.
7886 Constant *
7887 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7888                                                    const APInt &BEs,
7889                                                    const Loop *L) {
7890   auto I = ConstantEvolutionLoopExitValue.find(PN);
7891   if (I != ConstantEvolutionLoopExitValue.end())
7892     return I->second;
7893 
7894   if (BEs.ugt(MaxBruteForceIterations))
7895     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7896 
7897   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7898 
7899   DenseMap<Instruction *, Constant *> CurrentIterVals;
7900   BasicBlock *Header = L->getHeader();
7901   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7902 
7903   BasicBlock *Latch = L->getLoopLatch();
7904   if (!Latch)
7905     return nullptr;
7906 
7907   for (PHINode &PHI : Header->phis()) {
7908     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7909       CurrentIterVals[&PHI] = StartCST;
7910   }
7911   if (!CurrentIterVals.count(PN))
7912     return RetVal = nullptr;
7913 
7914   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7915 
7916   // Execute the loop symbolically to determine the exit value.
7917   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7918          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7919 
7920   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7921   unsigned IterationNum = 0;
7922   const DataLayout &DL = getDataLayout();
7923   for (; ; ++IterationNum) {
7924     if (IterationNum == NumIterations)
7925       return RetVal = CurrentIterVals[PN];  // Got exit value!
7926 
7927     // Compute the value of the PHIs for the next iteration.
7928     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7929     DenseMap<Instruction *, Constant *> NextIterVals;
7930     Constant *NextPHI =
7931         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7932     if (!NextPHI)
7933       return nullptr;        // Couldn't evaluate!
7934     NextIterVals[PN] = NextPHI;
7935 
7936     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7937 
7938     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7939     // cease to be able to evaluate one of them or if they stop evolving,
7940     // because that doesn't necessarily prevent us from computing PN.
7941     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7942     for (const auto &I : CurrentIterVals) {
7943       PHINode *PHI = dyn_cast<PHINode>(I.first);
7944       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7945       PHIsToCompute.emplace_back(PHI, I.second);
7946     }
7947     // We use two distinct loops because EvaluateExpression may invalidate any
7948     // iterators into CurrentIterVals.
7949     for (const auto &I : PHIsToCompute) {
7950       PHINode *PHI = I.first;
7951       Constant *&NextPHI = NextIterVals[PHI];
7952       if (!NextPHI) {   // Not already computed.
7953         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7954         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7955       }
7956       if (NextPHI != I.second)
7957         StoppedEvolving = false;
7958     }
7959 
7960     // If all entries in CurrentIterVals == NextIterVals then we can stop
7961     // iterating, the loop can't continue to change.
7962     if (StoppedEvolving)
7963       return RetVal = CurrentIterVals[PN];
7964 
7965     CurrentIterVals.swap(NextIterVals);
7966   }
7967 }
7968 
7969 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7970                                                           Value *Cond,
7971                                                           bool ExitWhen) {
7972   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7973   if (!PN) return getCouldNotCompute();
7974 
7975   // If the loop is canonicalized, the PHI will have exactly two entries.
7976   // That's the only form we support here.
7977   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7978 
7979   DenseMap<Instruction *, Constant *> CurrentIterVals;
7980   BasicBlock *Header = L->getHeader();
7981   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7982 
7983   BasicBlock *Latch = L->getLoopLatch();
7984   assert(Latch && "Should follow from NumIncomingValues == 2!");
7985 
7986   for (PHINode &PHI : Header->phis()) {
7987     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7988       CurrentIterVals[&PHI] = StartCST;
7989   }
7990   if (!CurrentIterVals.count(PN))
7991     return getCouldNotCompute();
7992 
7993   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7994   // the loop symbolically to determine when the condition gets a value of
7995   // "ExitWhen".
7996   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7997   const DataLayout &DL = getDataLayout();
7998   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7999     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8000         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8001 
8002     // Couldn't symbolically evaluate.
8003     if (!CondVal) return getCouldNotCompute();
8004 
8005     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8006       ++NumBruteForceTripCountsComputed;
8007       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8008     }
8009 
8010     // Update all the PHI nodes for the next iteration.
8011     DenseMap<Instruction *, Constant *> NextIterVals;
8012 
8013     // Create a list of which PHIs we need to compute. We want to do this before
8014     // calling EvaluateExpression on them because that may invalidate iterators
8015     // into CurrentIterVals.
8016     SmallVector<PHINode *, 8> PHIsToCompute;
8017     for (const auto &I : CurrentIterVals) {
8018       PHINode *PHI = dyn_cast<PHINode>(I.first);
8019       if (!PHI || PHI->getParent() != Header) continue;
8020       PHIsToCompute.push_back(PHI);
8021     }
8022     for (PHINode *PHI : PHIsToCompute) {
8023       Constant *&NextPHI = NextIterVals[PHI];
8024       if (NextPHI) continue;    // Already computed!
8025 
8026       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8027       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8028     }
8029     CurrentIterVals.swap(NextIterVals);
8030   }
8031 
8032   // Too many iterations were needed to evaluate.
8033   return getCouldNotCompute();
8034 }
8035 
8036 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8037   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8038       ValuesAtScopes[V];
8039   // Check to see if we've folded this expression at this loop before.
8040   for (auto &LS : Values)
8041     if (LS.first == L)
8042       return LS.second ? LS.second : V;
8043 
8044   Values.emplace_back(L, nullptr);
8045 
8046   // Otherwise compute it.
8047   const SCEV *C = computeSCEVAtScope(V, L);
8048   for (auto &LS : reverse(ValuesAtScopes[V]))
8049     if (LS.first == L) {
8050       LS.second = C;
8051       break;
8052     }
8053   return C;
8054 }
8055 
8056 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8057 /// will return Constants for objects which aren't represented by a
8058 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8059 /// Returns NULL if the SCEV isn't representable as a Constant.
8060 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8061   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
8062     case scCouldNotCompute:
8063     case scAddRecExpr:
8064       break;
8065     case scConstant:
8066       return cast<SCEVConstant>(V)->getValue();
8067     case scUnknown:
8068       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8069     case scSignExtend: {
8070       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8071       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8072         return ConstantExpr::getSExt(CastOp, SS->getType());
8073       break;
8074     }
8075     case scZeroExtend: {
8076       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8077       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8078         return ConstantExpr::getZExt(CastOp, SZ->getType());
8079       break;
8080     }
8081     case scTruncate: {
8082       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8083       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8084         return ConstantExpr::getTrunc(CastOp, ST->getType());
8085       break;
8086     }
8087     case scAddExpr: {
8088       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8089       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8090         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8091           unsigned AS = PTy->getAddressSpace();
8092           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8093           C = ConstantExpr::getBitCast(C, DestPtrTy);
8094         }
8095         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8096           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8097           if (!C2) return nullptr;
8098 
8099           // First pointer!
8100           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8101             unsigned AS = C2->getType()->getPointerAddressSpace();
8102             std::swap(C, C2);
8103             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8104             // The offsets have been converted to bytes.  We can add bytes to an
8105             // i8* by GEP with the byte count in the first index.
8106             C = ConstantExpr::getBitCast(C, DestPtrTy);
8107           }
8108 
8109           // Don't bother trying to sum two pointers. We probably can't
8110           // statically compute a load that results from it anyway.
8111           if (C2->getType()->isPointerTy())
8112             return nullptr;
8113 
8114           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8115             if (PTy->getElementType()->isStructTy())
8116               C2 = ConstantExpr::getIntegerCast(
8117                   C2, Type::getInt32Ty(C->getContext()), true);
8118             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8119           } else
8120             C = ConstantExpr::getAdd(C, C2);
8121         }
8122         return C;
8123       }
8124       break;
8125     }
8126     case scMulExpr: {
8127       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8128       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8129         // Don't bother with pointers at all.
8130         if (C->getType()->isPointerTy()) return nullptr;
8131         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8132           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8133           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
8134           C = ConstantExpr::getMul(C, C2);
8135         }
8136         return C;
8137       }
8138       break;
8139     }
8140     case scUDivExpr: {
8141       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8142       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8143         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8144           if (LHS->getType() == RHS->getType())
8145             return ConstantExpr::getUDiv(LHS, RHS);
8146       break;
8147     }
8148     case scSMaxExpr:
8149     case scUMaxExpr:
8150     case scSMinExpr:
8151     case scUMinExpr:
8152       break; // TODO: smax, umax, smin, umax.
8153   }
8154   return nullptr;
8155 }
8156 
8157 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8158   if (isa<SCEVConstant>(V)) return V;
8159 
8160   // If this instruction is evolved from a constant-evolving PHI, compute the
8161   // exit value from the loop without using SCEVs.
8162   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8163     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8164       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8165         const Loop *LI = this->LI[I->getParent()];
8166         // Looking for loop exit value.
8167         if (LI && LI->getParentLoop() == L &&
8168             PN->getParent() == LI->getHeader()) {
8169           // Okay, there is no closed form solution for the PHI node.  Check
8170           // to see if the loop that contains it has a known backedge-taken
8171           // count.  If so, we may be able to force computation of the exit
8172           // value.
8173           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8174           // This trivial case can show up in some degenerate cases where
8175           // the incoming IR has not yet been fully simplified.
8176           if (BackedgeTakenCount->isZero()) {
8177             Value *InitValue = nullptr;
8178             bool MultipleInitValues = false;
8179             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8180               if (!LI->contains(PN->getIncomingBlock(i))) {
8181                 if (!InitValue)
8182                   InitValue = PN->getIncomingValue(i);
8183                 else if (InitValue != PN->getIncomingValue(i)) {
8184                   MultipleInitValues = true;
8185                   break;
8186                 }
8187               }
8188             }
8189             if (!MultipleInitValues && InitValue)
8190               return getSCEV(InitValue);
8191           }
8192           // Do we have a loop invariant value flowing around the backedge
8193           // for a loop which must execute the backedge?
8194           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8195               isKnownPositive(BackedgeTakenCount) &&
8196               PN->getNumIncomingValues() == 2) {
8197             unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8198             const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred));
8199             if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent()))
8200               return OnBackedge;
8201           }
8202           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8203             // Okay, we know how many times the containing loop executes.  If
8204             // this is a constant evolving PHI node, get the final value at
8205             // the specified iteration number.
8206             Constant *RV =
8207                 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8208             if (RV) return getSCEV(RV);
8209           }
8210         }
8211 
8212         // If there is a single-input Phi, evaluate it at our scope. If we can
8213         // prove that this replacement does not break LCSSA form, use new value.
8214         if (PN->getNumOperands() == 1) {
8215           const SCEV *Input = getSCEV(PN->getOperand(0));
8216           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8217           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8218           // for the simplest case just support constants.
8219           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8220         }
8221       }
8222 
8223       // Okay, this is an expression that we cannot symbolically evaluate
8224       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8225       // the arguments into constants, and if so, try to constant propagate the
8226       // result.  This is particularly useful for computing loop exit values.
8227       if (CanConstantFold(I)) {
8228         SmallVector<Constant *, 4> Operands;
8229         bool MadeImprovement = false;
8230         for (Value *Op : I->operands()) {
8231           if (Constant *C = dyn_cast<Constant>(Op)) {
8232             Operands.push_back(C);
8233             continue;
8234           }
8235 
8236           // If any of the operands is non-constant and if they are
8237           // non-integer and non-pointer, don't even try to analyze them
8238           // with scev techniques.
8239           if (!isSCEVable(Op->getType()))
8240             return V;
8241 
8242           const SCEV *OrigV = getSCEV(Op);
8243           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8244           MadeImprovement |= OrigV != OpV;
8245 
8246           Constant *C = BuildConstantFromSCEV(OpV);
8247           if (!C) return V;
8248           if (C->getType() != Op->getType())
8249             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8250                                                               Op->getType(),
8251                                                               false),
8252                                       C, Op->getType());
8253           Operands.push_back(C);
8254         }
8255 
8256         // Check to see if getSCEVAtScope actually made an improvement.
8257         if (MadeImprovement) {
8258           Constant *C = nullptr;
8259           const DataLayout &DL = getDataLayout();
8260           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8261             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8262                                                 Operands[1], DL, &TLI);
8263           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8264             if (!LI->isVolatile())
8265               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8266           } else
8267             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8268           if (!C) return V;
8269           return getSCEV(C);
8270         }
8271       }
8272     }
8273 
8274     // This is some other type of SCEVUnknown, just return it.
8275     return V;
8276   }
8277 
8278   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8279     // Avoid performing the look-up in the common case where the specified
8280     // expression has no loop-variant portions.
8281     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8282       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8283       if (OpAtScope != Comm->getOperand(i)) {
8284         // Okay, at least one of these operands is loop variant but might be
8285         // foldable.  Build a new instance of the folded commutative expression.
8286         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8287                                             Comm->op_begin()+i);
8288         NewOps.push_back(OpAtScope);
8289 
8290         for (++i; i != e; ++i) {
8291           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8292           NewOps.push_back(OpAtScope);
8293         }
8294         if (isa<SCEVAddExpr>(Comm))
8295           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8296         if (isa<SCEVMulExpr>(Comm))
8297           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8298         if (isa<SCEVMinMaxExpr>(Comm))
8299           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8300         llvm_unreachable("Unknown commutative SCEV type!");
8301       }
8302     }
8303     // If we got here, all operands are loop invariant.
8304     return Comm;
8305   }
8306 
8307   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8308     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8309     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8310     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8311       return Div;   // must be loop invariant
8312     return getUDivExpr(LHS, RHS);
8313   }
8314 
8315   // If this is a loop recurrence for a loop that does not contain L, then we
8316   // are dealing with the final value computed by the loop.
8317   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8318     // First, attempt to evaluate each operand.
8319     // Avoid performing the look-up in the common case where the specified
8320     // expression has no loop-variant portions.
8321     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8322       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8323       if (OpAtScope == AddRec->getOperand(i))
8324         continue;
8325 
8326       // Okay, at least one of these operands is loop variant but might be
8327       // foldable.  Build a new instance of the folded commutative expression.
8328       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8329                                           AddRec->op_begin()+i);
8330       NewOps.push_back(OpAtScope);
8331       for (++i; i != e; ++i)
8332         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8333 
8334       const SCEV *FoldedRec =
8335         getAddRecExpr(NewOps, AddRec->getLoop(),
8336                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8337       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8338       // The addrec may be folded to a nonrecurrence, for example, if the
8339       // induction variable is multiplied by zero after constant folding. Go
8340       // ahead and return the folded value.
8341       if (!AddRec)
8342         return FoldedRec;
8343       break;
8344     }
8345 
8346     // If the scope is outside the addrec's loop, evaluate it by using the
8347     // loop exit value of the addrec.
8348     if (!AddRec->getLoop()->contains(L)) {
8349       // To evaluate this recurrence, we need to know how many times the AddRec
8350       // loop iterates.  Compute this now.
8351       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8352       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8353 
8354       // Then, evaluate the AddRec.
8355       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8356     }
8357 
8358     return AddRec;
8359   }
8360 
8361   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8362     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8363     if (Op == Cast->getOperand())
8364       return Cast;  // must be loop invariant
8365     return getZeroExtendExpr(Op, Cast->getType());
8366   }
8367 
8368   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8369     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8370     if (Op == Cast->getOperand())
8371       return Cast;  // must be loop invariant
8372     return getSignExtendExpr(Op, Cast->getType());
8373   }
8374 
8375   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8376     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8377     if (Op == Cast->getOperand())
8378       return Cast;  // must be loop invariant
8379     return getTruncateExpr(Op, Cast->getType());
8380   }
8381 
8382   llvm_unreachable("Unknown SCEV type!");
8383 }
8384 
8385 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8386   return getSCEVAtScope(getSCEV(V), L);
8387 }
8388 
8389 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8390   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8391     return stripInjectiveFunctions(ZExt->getOperand());
8392   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8393     return stripInjectiveFunctions(SExt->getOperand());
8394   return S;
8395 }
8396 
8397 /// Finds the minimum unsigned root of the following equation:
8398 ///
8399 ///     A * X = B (mod N)
8400 ///
8401 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8402 /// A and B isn't important.
8403 ///
8404 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8405 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8406                                                ScalarEvolution &SE) {
8407   uint32_t BW = A.getBitWidth();
8408   assert(BW == SE.getTypeSizeInBits(B->getType()));
8409   assert(A != 0 && "A must be non-zero.");
8410 
8411   // 1. D = gcd(A, N)
8412   //
8413   // The gcd of A and N may have only one prime factor: 2. The number of
8414   // trailing zeros in A is its multiplicity
8415   uint32_t Mult2 = A.countTrailingZeros();
8416   // D = 2^Mult2
8417 
8418   // 2. Check if B is divisible by D.
8419   //
8420   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8421   // is not less than multiplicity of this prime factor for D.
8422   if (SE.GetMinTrailingZeros(B) < Mult2)
8423     return SE.getCouldNotCompute();
8424 
8425   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8426   // modulo (N / D).
8427   //
8428   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8429   // (N / D) in general. The inverse itself always fits into BW bits, though,
8430   // so we immediately truncate it.
8431   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8432   APInt Mod(BW + 1, 0);
8433   Mod.setBit(BW - Mult2);  // Mod = N / D
8434   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8435 
8436   // 4. Compute the minimum unsigned root of the equation:
8437   // I * (B / D) mod (N / D)
8438   // To simplify the computation, we factor out the divide by D:
8439   // (I * B mod N) / D
8440   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8441   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8442 }
8443 
8444 /// For a given quadratic addrec, generate coefficients of the corresponding
8445 /// quadratic equation, multiplied by a common value to ensure that they are
8446 /// integers.
8447 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8448 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8449 /// were multiplied by, and BitWidth is the bit width of the original addrec
8450 /// coefficients.
8451 /// This function returns None if the addrec coefficients are not compile-
8452 /// time constants.
8453 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8454 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8455   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8456   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8457   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8458   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8459   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8460                     << *AddRec << '\n');
8461 
8462   // We currently can only solve this if the coefficients are constants.
8463   if (!LC || !MC || !NC) {
8464     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8465     return None;
8466   }
8467 
8468   APInt L = LC->getAPInt();
8469   APInt M = MC->getAPInt();
8470   APInt N = NC->getAPInt();
8471   assert(!N.isNullValue() && "This is not a quadratic addrec");
8472 
8473   unsigned BitWidth = LC->getAPInt().getBitWidth();
8474   unsigned NewWidth = BitWidth + 1;
8475   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8476                     << BitWidth << '\n');
8477   // The sign-extension (as opposed to a zero-extension) here matches the
8478   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8479   N = N.sext(NewWidth);
8480   M = M.sext(NewWidth);
8481   L = L.sext(NewWidth);
8482 
8483   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8484   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8485   //   L+M, L+2M+N, L+3M+3N, ...
8486   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8487   //
8488   // The equation Acc = 0 is then
8489   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8490   // In a quadratic form it becomes:
8491   //   N n^2 + (2M-N) n + 2L = 0.
8492 
8493   APInt A = N;
8494   APInt B = 2 * M - A;
8495   APInt C = 2 * L;
8496   APInt T = APInt(NewWidth, 2);
8497   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8498                     << "x + " << C << ", coeff bw: " << NewWidth
8499                     << ", multiplied by " << T << '\n');
8500   return std::make_tuple(A, B, C, T, BitWidth);
8501 }
8502 
8503 /// Helper function to compare optional APInts:
8504 /// (a) if X and Y both exist, return min(X, Y),
8505 /// (b) if neither X nor Y exist, return None,
8506 /// (c) if exactly one of X and Y exists, return that value.
8507 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8508   if (X.hasValue() && Y.hasValue()) {
8509     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8510     APInt XW = X->sextOrSelf(W);
8511     APInt YW = Y->sextOrSelf(W);
8512     return XW.slt(YW) ? *X : *Y;
8513   }
8514   if (!X.hasValue() && !Y.hasValue())
8515     return None;
8516   return X.hasValue() ? *X : *Y;
8517 }
8518 
8519 /// Helper function to truncate an optional APInt to a given BitWidth.
8520 /// When solving addrec-related equations, it is preferable to return a value
8521 /// that has the same bit width as the original addrec's coefficients. If the
8522 /// solution fits in the original bit width, truncate it (except for i1).
8523 /// Returning a value of a different bit width may inhibit some optimizations.
8524 ///
8525 /// In general, a solution to a quadratic equation generated from an addrec
8526 /// may require BW+1 bits, where BW is the bit width of the addrec's
8527 /// coefficients. The reason is that the coefficients of the quadratic
8528 /// equation are BW+1 bits wide (to avoid truncation when converting from
8529 /// the addrec to the equation).
8530 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8531   if (!X.hasValue())
8532     return None;
8533   unsigned W = X->getBitWidth();
8534   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8535     return X->trunc(BitWidth);
8536   return X;
8537 }
8538 
8539 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8540 /// iterations. The values L, M, N are assumed to be signed, and they
8541 /// should all have the same bit widths.
8542 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8543 /// where BW is the bit width of the addrec's coefficients.
8544 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8545 /// returned as such, otherwise the bit width of the returned value may
8546 /// be greater than BW.
8547 ///
8548 /// This function returns None if
8549 /// (a) the addrec coefficients are not constant, or
8550 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8551 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8552 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8553 static Optional<APInt>
8554 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8555   APInt A, B, C, M;
8556   unsigned BitWidth;
8557   auto T = GetQuadraticEquation(AddRec);
8558   if (!T.hasValue())
8559     return None;
8560 
8561   std::tie(A, B, C, M, BitWidth) = *T;
8562   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8563   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8564   if (!X.hasValue())
8565     return None;
8566 
8567   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8568   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8569   if (!V->isZero())
8570     return None;
8571 
8572   return TruncIfPossible(X, BitWidth);
8573 }
8574 
8575 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8576 /// iterations. The values M, N are assumed to be signed, and they
8577 /// should all have the same bit widths.
8578 /// Find the least n such that c(n) does not belong to the given range,
8579 /// while c(n-1) does.
8580 ///
8581 /// This function returns None if
8582 /// (a) the addrec coefficients are not constant, or
8583 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8584 ///     bounds of the range.
8585 static Optional<APInt>
8586 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8587                           const ConstantRange &Range, ScalarEvolution &SE) {
8588   assert(AddRec->getOperand(0)->isZero() &&
8589          "Starting value of addrec should be 0");
8590   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8591                     << Range << ", addrec " << *AddRec << '\n');
8592   // This case is handled in getNumIterationsInRange. Here we can assume that
8593   // we start in the range.
8594   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8595          "Addrec's initial value should be in range");
8596 
8597   APInt A, B, C, M;
8598   unsigned BitWidth;
8599   auto T = GetQuadraticEquation(AddRec);
8600   if (!T.hasValue())
8601     return None;
8602 
8603   // Be careful about the return value: there can be two reasons for not
8604   // returning an actual number. First, if no solutions to the equations
8605   // were found, and second, if the solutions don't leave the given range.
8606   // The first case means that the actual solution is "unknown", the second
8607   // means that it's known, but not valid. If the solution is unknown, we
8608   // cannot make any conclusions.
8609   // Return a pair: the optional solution and a flag indicating if the
8610   // solution was found.
8611   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8612     // Solve for signed overflow and unsigned overflow, pick the lower
8613     // solution.
8614     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8615                       << Bound << " (before multiplying by " << M << ")\n");
8616     Bound *= M; // The quadratic equation multiplier.
8617 
8618     Optional<APInt> SO = None;
8619     if (BitWidth > 1) {
8620       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8621                            "signed overflow\n");
8622       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8623     }
8624     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8625                          "unsigned overflow\n");
8626     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8627                                                               BitWidth+1);
8628 
8629     auto LeavesRange = [&] (const APInt &X) {
8630       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8631       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8632       if (Range.contains(V0->getValue()))
8633         return false;
8634       // X should be at least 1, so X-1 is non-negative.
8635       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8636       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8637       if (Range.contains(V1->getValue()))
8638         return true;
8639       return false;
8640     };
8641 
8642     // If SolveQuadraticEquationWrap returns None, it means that there can
8643     // be a solution, but the function failed to find it. We cannot treat it
8644     // as "no solution".
8645     if (!SO.hasValue() || !UO.hasValue())
8646       return { None, false };
8647 
8648     // Check the smaller value first to see if it leaves the range.
8649     // At this point, both SO and UO must have values.
8650     Optional<APInt> Min = MinOptional(SO, UO);
8651     if (LeavesRange(*Min))
8652       return { Min, true };
8653     Optional<APInt> Max = Min == SO ? UO : SO;
8654     if (LeavesRange(*Max))
8655       return { Max, true };
8656 
8657     // Solutions were found, but were eliminated, hence the "true".
8658     return { None, true };
8659   };
8660 
8661   std::tie(A, B, C, M, BitWidth) = *T;
8662   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8663   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8664   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8665   auto SL = SolveForBoundary(Lower);
8666   auto SU = SolveForBoundary(Upper);
8667   // If any of the solutions was unknown, no meaninigful conclusions can
8668   // be made.
8669   if (!SL.second || !SU.second)
8670     return None;
8671 
8672   // Claim: The correct solution is not some value between Min and Max.
8673   //
8674   // Justification: Assuming that Min and Max are different values, one of
8675   // them is when the first signed overflow happens, the other is when the
8676   // first unsigned overflow happens. Crossing the range boundary is only
8677   // possible via an overflow (treating 0 as a special case of it, modeling
8678   // an overflow as crossing k*2^W for some k).
8679   //
8680   // The interesting case here is when Min was eliminated as an invalid
8681   // solution, but Max was not. The argument is that if there was another
8682   // overflow between Min and Max, it would also have been eliminated if
8683   // it was considered.
8684   //
8685   // For a given boundary, it is possible to have two overflows of the same
8686   // type (signed/unsigned) without having the other type in between: this
8687   // can happen when the vertex of the parabola is between the iterations
8688   // corresponding to the overflows. This is only possible when the two
8689   // overflows cross k*2^W for the same k. In such case, if the second one
8690   // left the range (and was the first one to do so), the first overflow
8691   // would have to enter the range, which would mean that either we had left
8692   // the range before or that we started outside of it. Both of these cases
8693   // are contradictions.
8694   //
8695   // Claim: In the case where SolveForBoundary returns None, the correct
8696   // solution is not some value between the Max for this boundary and the
8697   // Min of the other boundary.
8698   //
8699   // Justification: Assume that we had such Max_A and Min_B corresponding
8700   // to range boundaries A and B and such that Max_A < Min_B. If there was
8701   // a solution between Max_A and Min_B, it would have to be caused by an
8702   // overflow corresponding to either A or B. It cannot correspond to B,
8703   // since Min_B is the first occurrence of such an overflow. If it
8704   // corresponded to A, it would have to be either a signed or an unsigned
8705   // overflow that is larger than both eliminated overflows for A. But
8706   // between the eliminated overflows and this overflow, the values would
8707   // cover the entire value space, thus crossing the other boundary, which
8708   // is a contradiction.
8709 
8710   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8711 }
8712 
8713 ScalarEvolution::ExitLimit
8714 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8715                               bool AllowPredicates) {
8716 
8717   // This is only used for loops with a "x != y" exit test. The exit condition
8718   // is now expressed as a single expression, V = x-y. So the exit test is
8719   // effectively V != 0.  We know and take advantage of the fact that this
8720   // expression only being used in a comparison by zero context.
8721 
8722   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8723   // If the value is a constant
8724   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8725     // If the value is already zero, the branch will execute zero times.
8726     if (C->getValue()->isZero()) return C;
8727     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8728   }
8729 
8730   const SCEVAddRecExpr *AddRec =
8731       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8732 
8733   if (!AddRec && AllowPredicates)
8734     // Try to make this an AddRec using runtime tests, in the first X
8735     // iterations of this loop, where X is the SCEV expression found by the
8736     // algorithm below.
8737     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8738 
8739   if (!AddRec || AddRec->getLoop() != L)
8740     return getCouldNotCompute();
8741 
8742   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8743   // the quadratic equation to solve it.
8744   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8745     // We can only use this value if the chrec ends up with an exact zero
8746     // value at this index.  When solving for "X*X != 5", for example, we
8747     // should not accept a root of 2.
8748     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8749       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8750       return ExitLimit(R, R, false, Predicates);
8751     }
8752     return getCouldNotCompute();
8753   }
8754 
8755   // Otherwise we can only handle this if it is affine.
8756   if (!AddRec->isAffine())
8757     return getCouldNotCompute();
8758 
8759   // If this is an affine expression, the execution count of this branch is
8760   // the minimum unsigned root of the following equation:
8761   //
8762   //     Start + Step*N = 0 (mod 2^BW)
8763   //
8764   // equivalent to:
8765   //
8766   //             Step*N = -Start (mod 2^BW)
8767   //
8768   // where BW is the common bit width of Start and Step.
8769 
8770   // Get the initial value for the loop.
8771   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8772   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8773 
8774   // For now we handle only constant steps.
8775   //
8776   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8777   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8778   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8779   // We have not yet seen any such cases.
8780   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8781   if (!StepC || StepC->getValue()->isZero())
8782     return getCouldNotCompute();
8783 
8784   // For positive steps (counting up until unsigned overflow):
8785   //   N = -Start/Step (as unsigned)
8786   // For negative steps (counting down to zero):
8787   //   N = Start/-Step
8788   // First compute the unsigned distance from zero in the direction of Step.
8789   bool CountDown = StepC->getAPInt().isNegative();
8790   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8791 
8792   // Handle unitary steps, which cannot wraparound.
8793   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8794   //   N = Distance (as unsigned)
8795   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8796     APInt MaxBECount = getUnsignedRangeMax(Distance);
8797 
8798     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8799     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8800     // case, and see if we can improve the bound.
8801     //
8802     // Explicitly handling this here is necessary because getUnsignedRange
8803     // isn't context-sensitive; it doesn't know that we only care about the
8804     // range inside the loop.
8805     const SCEV *Zero = getZero(Distance->getType());
8806     const SCEV *One = getOne(Distance->getType());
8807     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8808     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8809       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8810       // as "unsigned_max(Distance + 1) - 1".
8811       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8812       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8813     }
8814     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8815   }
8816 
8817   // If the condition controls loop exit (the loop exits only if the expression
8818   // is true) and the addition is no-wrap we can use unsigned divide to
8819   // compute the backedge count.  In this case, the step may not divide the
8820   // distance, but we don't care because if the condition is "missed" the loop
8821   // will have undefined behavior due to wrapping.
8822   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8823       loopHasNoAbnormalExits(AddRec->getLoop())) {
8824     const SCEV *Exact =
8825         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8826     const SCEV *Max =
8827         Exact == getCouldNotCompute()
8828             ? Exact
8829             : getConstant(getUnsignedRangeMax(Exact));
8830     return ExitLimit(Exact, Max, false, Predicates);
8831   }
8832 
8833   // Solve the general equation.
8834   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8835                                                getNegativeSCEV(Start), *this);
8836   const SCEV *M = E == getCouldNotCompute()
8837                       ? E
8838                       : getConstant(getUnsignedRangeMax(E));
8839   return ExitLimit(E, M, false, Predicates);
8840 }
8841 
8842 ScalarEvolution::ExitLimit
8843 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8844   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8845   // handle them yet except for the trivial case.  This could be expanded in the
8846   // future as needed.
8847 
8848   // If the value is a constant, check to see if it is known to be non-zero
8849   // already.  If so, the backedge will execute zero times.
8850   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8851     if (!C->getValue()->isZero())
8852       return getZero(C->getType());
8853     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8854   }
8855 
8856   // We could implement others, but I really doubt anyone writes loops like
8857   // this, and if they did, they would already be constant folded.
8858   return getCouldNotCompute();
8859 }
8860 
8861 std::pair<BasicBlock *, BasicBlock *>
8862 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8863   // If the block has a unique predecessor, then there is no path from the
8864   // predecessor to the block that does not go through the direct edge
8865   // from the predecessor to the block.
8866   if (BasicBlock *Pred = BB->getSinglePredecessor())
8867     return {Pred, BB};
8868 
8869   // A loop's header is defined to be a block that dominates the loop.
8870   // If the header has a unique predecessor outside the loop, it must be
8871   // a block that has exactly one successor that can reach the loop.
8872   if (Loop *L = LI.getLoopFor(BB))
8873     return {L->getLoopPredecessor(), L->getHeader()};
8874 
8875   return {nullptr, nullptr};
8876 }
8877 
8878 /// SCEV structural equivalence is usually sufficient for testing whether two
8879 /// expressions are equal, however for the purposes of looking for a condition
8880 /// guarding a loop, it can be useful to be a little more general, since a
8881 /// front-end may have replicated the controlling expression.
8882 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8883   // Quick check to see if they are the same SCEV.
8884   if (A == B) return true;
8885 
8886   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8887     // Not all instructions that are "identical" compute the same value.  For
8888     // instance, two distinct alloca instructions allocating the same type are
8889     // identical and do not read memory; but compute distinct values.
8890     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8891   };
8892 
8893   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8894   // two different instructions with the same value. Check for this case.
8895   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8896     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8897       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8898         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8899           if (ComputesEqualValues(AI, BI))
8900             return true;
8901 
8902   // Otherwise assume they may have a different value.
8903   return false;
8904 }
8905 
8906 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8907                                            const SCEV *&LHS, const SCEV *&RHS,
8908                                            unsigned Depth) {
8909   bool Changed = false;
8910   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8911   // '0 != 0'.
8912   auto TrivialCase = [&](bool TriviallyTrue) {
8913     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8914     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8915     return true;
8916   };
8917   // If we hit the max recursion limit bail out.
8918   if (Depth >= 3)
8919     return false;
8920 
8921   // Canonicalize a constant to the right side.
8922   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8923     // Check for both operands constant.
8924     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8925       if (ConstantExpr::getICmp(Pred,
8926                                 LHSC->getValue(),
8927                                 RHSC->getValue())->isNullValue())
8928         return TrivialCase(false);
8929       else
8930         return TrivialCase(true);
8931     }
8932     // Otherwise swap the operands to put the constant on the right.
8933     std::swap(LHS, RHS);
8934     Pred = ICmpInst::getSwappedPredicate(Pred);
8935     Changed = true;
8936   }
8937 
8938   // If we're comparing an addrec with a value which is loop-invariant in the
8939   // addrec's loop, put the addrec on the left. Also make a dominance check,
8940   // as both operands could be addrecs loop-invariant in each other's loop.
8941   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8942     const Loop *L = AR->getLoop();
8943     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8944       std::swap(LHS, RHS);
8945       Pred = ICmpInst::getSwappedPredicate(Pred);
8946       Changed = true;
8947     }
8948   }
8949 
8950   // If there's a constant operand, canonicalize comparisons with boundary
8951   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8952   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8953     const APInt &RA = RC->getAPInt();
8954 
8955     bool SimplifiedByConstantRange = false;
8956 
8957     if (!ICmpInst::isEquality(Pred)) {
8958       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8959       if (ExactCR.isFullSet())
8960         return TrivialCase(true);
8961       else if (ExactCR.isEmptySet())
8962         return TrivialCase(false);
8963 
8964       APInt NewRHS;
8965       CmpInst::Predicate NewPred;
8966       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8967           ICmpInst::isEquality(NewPred)) {
8968         // We were able to convert an inequality to an equality.
8969         Pred = NewPred;
8970         RHS = getConstant(NewRHS);
8971         Changed = SimplifiedByConstantRange = true;
8972       }
8973     }
8974 
8975     if (!SimplifiedByConstantRange) {
8976       switch (Pred) {
8977       default:
8978         break;
8979       case ICmpInst::ICMP_EQ:
8980       case ICmpInst::ICMP_NE:
8981         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8982         if (!RA)
8983           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8984             if (const SCEVMulExpr *ME =
8985                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8986               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8987                   ME->getOperand(0)->isAllOnesValue()) {
8988                 RHS = AE->getOperand(1);
8989                 LHS = ME->getOperand(1);
8990                 Changed = true;
8991               }
8992         break;
8993 
8994 
8995         // The "Should have been caught earlier!" messages refer to the fact
8996         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8997         // should have fired on the corresponding cases, and canonicalized the
8998         // check to trivial case.
8999 
9000       case ICmpInst::ICMP_UGE:
9001         assert(!RA.isMinValue() && "Should have been caught earlier!");
9002         Pred = ICmpInst::ICMP_UGT;
9003         RHS = getConstant(RA - 1);
9004         Changed = true;
9005         break;
9006       case ICmpInst::ICMP_ULE:
9007         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9008         Pred = ICmpInst::ICMP_ULT;
9009         RHS = getConstant(RA + 1);
9010         Changed = true;
9011         break;
9012       case ICmpInst::ICMP_SGE:
9013         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9014         Pred = ICmpInst::ICMP_SGT;
9015         RHS = getConstant(RA - 1);
9016         Changed = true;
9017         break;
9018       case ICmpInst::ICMP_SLE:
9019         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9020         Pred = ICmpInst::ICMP_SLT;
9021         RHS = getConstant(RA + 1);
9022         Changed = true;
9023         break;
9024       }
9025     }
9026   }
9027 
9028   // Check for obvious equality.
9029   if (HasSameValue(LHS, RHS)) {
9030     if (ICmpInst::isTrueWhenEqual(Pred))
9031       return TrivialCase(true);
9032     if (ICmpInst::isFalseWhenEqual(Pred))
9033       return TrivialCase(false);
9034   }
9035 
9036   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9037   // adding or subtracting 1 from one of the operands.
9038   switch (Pred) {
9039   case ICmpInst::ICMP_SLE:
9040     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9041       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9042                        SCEV::FlagNSW);
9043       Pred = ICmpInst::ICMP_SLT;
9044       Changed = true;
9045     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9046       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9047                        SCEV::FlagNSW);
9048       Pred = ICmpInst::ICMP_SLT;
9049       Changed = true;
9050     }
9051     break;
9052   case ICmpInst::ICMP_SGE:
9053     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9054       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9055                        SCEV::FlagNSW);
9056       Pred = ICmpInst::ICMP_SGT;
9057       Changed = true;
9058     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9059       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9060                        SCEV::FlagNSW);
9061       Pred = ICmpInst::ICMP_SGT;
9062       Changed = true;
9063     }
9064     break;
9065   case ICmpInst::ICMP_ULE:
9066     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9067       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9068                        SCEV::FlagNUW);
9069       Pred = ICmpInst::ICMP_ULT;
9070       Changed = true;
9071     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9072       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9073       Pred = ICmpInst::ICMP_ULT;
9074       Changed = true;
9075     }
9076     break;
9077   case ICmpInst::ICMP_UGE:
9078     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9079       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9080       Pred = ICmpInst::ICMP_UGT;
9081       Changed = true;
9082     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9083       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9084                        SCEV::FlagNUW);
9085       Pred = ICmpInst::ICMP_UGT;
9086       Changed = true;
9087     }
9088     break;
9089   default:
9090     break;
9091   }
9092 
9093   // TODO: More simplifications are possible here.
9094 
9095   // Recursively simplify until we either hit a recursion limit or nothing
9096   // changes.
9097   if (Changed)
9098     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9099 
9100   return Changed;
9101 }
9102 
9103 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9104   return getSignedRangeMax(S).isNegative();
9105 }
9106 
9107 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9108   return getSignedRangeMin(S).isStrictlyPositive();
9109 }
9110 
9111 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9112   return !getSignedRangeMin(S).isNegative();
9113 }
9114 
9115 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9116   return !getSignedRangeMax(S).isStrictlyPositive();
9117 }
9118 
9119 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9120   return isKnownNegative(S) || isKnownPositive(S);
9121 }
9122 
9123 std::pair<const SCEV *, const SCEV *>
9124 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9125   // Compute SCEV on entry of loop L.
9126   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9127   if (Start == getCouldNotCompute())
9128     return { Start, Start };
9129   // Compute post increment SCEV for loop L.
9130   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9131   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9132   return { Start, PostInc };
9133 }
9134 
9135 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9136                                           const SCEV *LHS, const SCEV *RHS) {
9137   // First collect all loops.
9138   SmallPtrSet<const Loop *, 8> LoopsUsed;
9139   getUsedLoops(LHS, LoopsUsed);
9140   getUsedLoops(RHS, LoopsUsed);
9141 
9142   if (LoopsUsed.empty())
9143     return false;
9144 
9145   // Domination relationship must be a linear order on collected loops.
9146 #ifndef NDEBUG
9147   for (auto *L1 : LoopsUsed)
9148     for (auto *L2 : LoopsUsed)
9149       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9150               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9151              "Domination relationship is not a linear order");
9152 #endif
9153 
9154   const Loop *MDL =
9155       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9156                         [&](const Loop *L1, const Loop *L2) {
9157          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9158        });
9159 
9160   // Get init and post increment value for LHS.
9161   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9162   // if LHS contains unknown non-invariant SCEV then bail out.
9163   if (SplitLHS.first == getCouldNotCompute())
9164     return false;
9165   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9166   // Get init and post increment value for RHS.
9167   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9168   // if RHS contains unknown non-invariant SCEV then bail out.
9169   if (SplitRHS.first == getCouldNotCompute())
9170     return false;
9171   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9172   // It is possible that init SCEV contains an invariant load but it does
9173   // not dominate MDL and is not available at MDL loop entry, so we should
9174   // check it here.
9175   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9176       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9177     return false;
9178 
9179   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9180          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9181                                      SplitRHS.second);
9182 }
9183 
9184 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9185                                        const SCEV *LHS, const SCEV *RHS) {
9186   // Canonicalize the inputs first.
9187   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9188 
9189   if (isKnownViaInduction(Pred, LHS, RHS))
9190     return true;
9191 
9192   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9193     return true;
9194 
9195   // Otherwise see what can be done with some simple reasoning.
9196   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9197 }
9198 
9199 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9200                                               const SCEVAddRecExpr *LHS,
9201                                               const SCEV *RHS) {
9202   const Loop *L = LHS->getLoop();
9203   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9204          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9205 }
9206 
9207 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
9208                                            ICmpInst::Predicate Pred,
9209                                            bool &Increasing) {
9210   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9211 
9212 #ifndef NDEBUG
9213   // Verify an invariant: inverting the predicate should turn a monotonically
9214   // increasing change to a monotonically decreasing one, and vice versa.
9215   bool IncreasingSwapped;
9216   bool ResultSwapped = isMonotonicPredicateImpl(
9217       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
9218 
9219   assert(Result == ResultSwapped && "should be able to analyze both!");
9220   if (ResultSwapped)
9221     assert(Increasing == !IncreasingSwapped &&
9222            "monotonicity should flip as we flip the predicate");
9223 #endif
9224 
9225   return Result;
9226 }
9227 
9228 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
9229                                                ICmpInst::Predicate Pred,
9230                                                bool &Increasing) {
9231 
9232   // A zero step value for LHS means the induction variable is essentially a
9233   // loop invariant value. We don't really depend on the predicate actually
9234   // flipping from false to true (for increasing predicates, and the other way
9235   // around for decreasing predicates), all we care about is that *if* the
9236   // predicate changes then it only changes from false to true.
9237   //
9238   // A zero step value in itself is not very useful, but there may be places
9239   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9240   // as general as possible.
9241 
9242   switch (Pred) {
9243   default:
9244     return false; // Conservative answer
9245 
9246   case ICmpInst::ICMP_UGT:
9247   case ICmpInst::ICMP_UGE:
9248   case ICmpInst::ICMP_ULT:
9249   case ICmpInst::ICMP_ULE:
9250     if (!LHS->hasNoUnsignedWrap())
9251       return false;
9252 
9253     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
9254     return true;
9255 
9256   case ICmpInst::ICMP_SGT:
9257   case ICmpInst::ICMP_SGE:
9258   case ICmpInst::ICMP_SLT:
9259   case ICmpInst::ICMP_SLE: {
9260     if (!LHS->hasNoSignedWrap())
9261       return false;
9262 
9263     const SCEV *Step = LHS->getStepRecurrence(*this);
9264 
9265     if (isKnownNonNegative(Step)) {
9266       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
9267       return true;
9268     }
9269 
9270     if (isKnownNonPositive(Step)) {
9271       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
9272       return true;
9273     }
9274 
9275     return false;
9276   }
9277 
9278   }
9279 
9280   llvm_unreachable("switch has default clause!");
9281 }
9282 
9283 bool ScalarEvolution::isLoopInvariantPredicate(
9284     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9285     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9286     const SCEV *&InvariantRHS) {
9287 
9288   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9289   if (!isLoopInvariant(RHS, L)) {
9290     if (!isLoopInvariant(LHS, L))
9291       return false;
9292 
9293     std::swap(LHS, RHS);
9294     Pred = ICmpInst::getSwappedPredicate(Pred);
9295   }
9296 
9297   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9298   if (!ArLHS || ArLHS->getLoop() != L)
9299     return false;
9300 
9301   bool Increasing;
9302   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9303     return false;
9304 
9305   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9306   // true as the loop iterates, and the backedge is control dependent on
9307   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9308   //
9309   //   * if the predicate was false in the first iteration then the predicate
9310   //     is never evaluated again, since the loop exits without taking the
9311   //     backedge.
9312   //   * if the predicate was true in the first iteration then it will
9313   //     continue to be true for all future iterations since it is
9314   //     monotonically increasing.
9315   //
9316   // For both the above possibilities, we can replace the loop varying
9317   // predicate with its value on the first iteration of the loop (which is
9318   // loop invariant).
9319   //
9320   // A similar reasoning applies for a monotonically decreasing predicate, by
9321   // replacing true with false and false with true in the above two bullets.
9322 
9323   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9324 
9325   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9326     return false;
9327 
9328   InvariantPred = Pred;
9329   InvariantLHS = ArLHS->getStart();
9330   InvariantRHS = RHS;
9331   return true;
9332 }
9333 
9334 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9335     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9336   if (HasSameValue(LHS, RHS))
9337     return ICmpInst::isTrueWhenEqual(Pred);
9338 
9339   // This code is split out from isKnownPredicate because it is called from
9340   // within isLoopEntryGuardedByCond.
9341 
9342   auto CheckRanges =
9343       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9344     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9345         .contains(RangeLHS);
9346   };
9347 
9348   // The check at the top of the function catches the case where the values are
9349   // known to be equal.
9350   if (Pred == CmpInst::ICMP_EQ)
9351     return false;
9352 
9353   if (Pred == CmpInst::ICMP_NE)
9354     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9355            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9356            isKnownNonZero(getMinusSCEV(LHS, RHS));
9357 
9358   if (CmpInst::isSigned(Pred))
9359     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9360 
9361   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9362 }
9363 
9364 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9365                                                     const SCEV *LHS,
9366                                                     const SCEV *RHS) {
9367   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9368   // Return Y via OutY.
9369   auto MatchBinaryAddToConst =
9370       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9371              SCEV::NoWrapFlags ExpectedFlags) {
9372     const SCEV *NonConstOp, *ConstOp;
9373     SCEV::NoWrapFlags FlagsPresent;
9374 
9375     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9376         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9377       return false;
9378 
9379     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9380     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9381   };
9382 
9383   APInt C;
9384 
9385   switch (Pred) {
9386   default:
9387     break;
9388 
9389   case ICmpInst::ICMP_SGE:
9390     std::swap(LHS, RHS);
9391     LLVM_FALLTHROUGH;
9392   case ICmpInst::ICMP_SLE:
9393     // X s<= (X + C)<nsw> if C >= 0
9394     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9395       return true;
9396 
9397     // (X + C)<nsw> s<= X if C <= 0
9398     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9399         !C.isStrictlyPositive())
9400       return true;
9401     break;
9402 
9403   case ICmpInst::ICMP_SGT:
9404     std::swap(LHS, RHS);
9405     LLVM_FALLTHROUGH;
9406   case ICmpInst::ICMP_SLT:
9407     // X s< (X + C)<nsw> if C > 0
9408     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9409         C.isStrictlyPositive())
9410       return true;
9411 
9412     // (X + C)<nsw> s< X if C < 0
9413     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9414       return true;
9415     break;
9416   }
9417 
9418   return false;
9419 }
9420 
9421 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9422                                                    const SCEV *LHS,
9423                                                    const SCEV *RHS) {
9424   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9425     return false;
9426 
9427   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9428   // the stack can result in exponential time complexity.
9429   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9430 
9431   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9432   //
9433   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9434   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9435   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9436   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9437   // use isKnownPredicate later if needed.
9438   return isKnownNonNegative(RHS) &&
9439          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9440          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9441 }
9442 
9443 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9444                                         ICmpInst::Predicate Pred,
9445                                         const SCEV *LHS, const SCEV *RHS) {
9446   // No need to even try if we know the module has no guards.
9447   if (!HasGuards)
9448     return false;
9449 
9450   return any_of(*BB, [&](Instruction &I) {
9451     using namespace llvm::PatternMatch;
9452 
9453     Value *Condition;
9454     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9455                          m_Value(Condition))) &&
9456            isImpliedCond(Pred, LHS, RHS, Condition, false);
9457   });
9458 }
9459 
9460 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9461 /// protected by a conditional between LHS and RHS.  This is used to
9462 /// to eliminate casts.
9463 bool
9464 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9465                                              ICmpInst::Predicate Pred,
9466                                              const SCEV *LHS, const SCEV *RHS) {
9467   // Interpret a null as meaning no loop, where there is obviously no guard
9468   // (interprocedural conditions notwithstanding).
9469   if (!L) return true;
9470 
9471   if (VerifyIR)
9472     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9473            "This cannot be done on broken IR!");
9474 
9475 
9476   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9477     return true;
9478 
9479   BasicBlock *Latch = L->getLoopLatch();
9480   if (!Latch)
9481     return false;
9482 
9483   BranchInst *LoopContinuePredicate =
9484     dyn_cast<BranchInst>(Latch->getTerminator());
9485   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9486       isImpliedCond(Pred, LHS, RHS,
9487                     LoopContinuePredicate->getCondition(),
9488                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9489     return true;
9490 
9491   // We don't want more than one activation of the following loops on the stack
9492   // -- that can lead to O(n!) time complexity.
9493   if (WalkingBEDominatingConds)
9494     return false;
9495 
9496   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9497 
9498   // See if we can exploit a trip count to prove the predicate.
9499   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9500   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9501   if (LatchBECount != getCouldNotCompute()) {
9502     // We know that Latch branches back to the loop header exactly
9503     // LatchBECount times.  This means the backdege condition at Latch is
9504     // equivalent to  "{0,+,1} u< LatchBECount".
9505     Type *Ty = LatchBECount->getType();
9506     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9507     const SCEV *LoopCounter =
9508       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9509     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9510                       LatchBECount))
9511       return true;
9512   }
9513 
9514   // Check conditions due to any @llvm.assume intrinsics.
9515   for (auto &AssumeVH : AC.assumptions()) {
9516     if (!AssumeVH)
9517       continue;
9518     auto *CI = cast<CallInst>(AssumeVH);
9519     if (!DT.dominates(CI, Latch->getTerminator()))
9520       continue;
9521 
9522     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9523       return true;
9524   }
9525 
9526   // If the loop is not reachable from the entry block, we risk running into an
9527   // infinite loop as we walk up into the dom tree.  These loops do not matter
9528   // anyway, so we just return a conservative answer when we see them.
9529   if (!DT.isReachableFromEntry(L->getHeader()))
9530     return false;
9531 
9532   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9533     return true;
9534 
9535   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9536        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9537     assert(DTN && "should reach the loop header before reaching the root!");
9538 
9539     BasicBlock *BB = DTN->getBlock();
9540     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9541       return true;
9542 
9543     BasicBlock *PBB = BB->getSinglePredecessor();
9544     if (!PBB)
9545       continue;
9546 
9547     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9548     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9549       continue;
9550 
9551     Value *Condition = ContinuePredicate->getCondition();
9552 
9553     // If we have an edge `E` within the loop body that dominates the only
9554     // latch, the condition guarding `E` also guards the backedge.  This
9555     // reasoning works only for loops with a single latch.
9556 
9557     BasicBlockEdge DominatingEdge(PBB, BB);
9558     if (DominatingEdge.isSingleEdge()) {
9559       // We're constructively (and conservatively) enumerating edges within the
9560       // loop body that dominate the latch.  The dominator tree better agree
9561       // with us on this:
9562       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9563 
9564       if (isImpliedCond(Pred, LHS, RHS, Condition,
9565                         BB != ContinuePredicate->getSuccessor(0)))
9566         return true;
9567     }
9568   }
9569 
9570   return false;
9571 }
9572 
9573 bool
9574 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9575                                           ICmpInst::Predicate Pred,
9576                                           const SCEV *LHS, const SCEV *RHS) {
9577   // Interpret a null as meaning no loop, where there is obviously no guard
9578   // (interprocedural conditions notwithstanding).
9579   if (!L) return false;
9580 
9581   if (VerifyIR)
9582     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9583            "This cannot be done on broken IR!");
9584 
9585   // Both LHS and RHS must be available at loop entry.
9586   assert(isAvailableAtLoopEntry(LHS, L) &&
9587          "LHS is not available at Loop Entry");
9588   assert(isAvailableAtLoopEntry(RHS, L) &&
9589          "RHS is not available at Loop Entry");
9590 
9591   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9592     return true;
9593 
9594   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9595   // the facts (a >= b && a != b) separately. A typical situation is when the
9596   // non-strict comparison is known from ranges and non-equality is known from
9597   // dominating predicates. If we are proving strict comparison, we always try
9598   // to prove non-equality and non-strict comparison separately.
9599   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9600   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9601   bool ProvedNonStrictComparison = false;
9602   bool ProvedNonEquality = false;
9603 
9604   if (ProvingStrictComparison) {
9605     ProvedNonStrictComparison =
9606         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9607     ProvedNonEquality =
9608         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9609     if (ProvedNonStrictComparison && ProvedNonEquality)
9610       return true;
9611   }
9612 
9613   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9614   auto ProveViaGuard = [&](BasicBlock *Block) {
9615     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9616       return true;
9617     if (ProvingStrictComparison) {
9618       if (!ProvedNonStrictComparison)
9619         ProvedNonStrictComparison =
9620             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9621       if (!ProvedNonEquality)
9622         ProvedNonEquality =
9623             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9624       if (ProvedNonStrictComparison && ProvedNonEquality)
9625         return true;
9626     }
9627     return false;
9628   };
9629 
9630   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9631   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9632     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9633       return true;
9634     if (ProvingStrictComparison) {
9635       if (!ProvedNonStrictComparison)
9636         ProvedNonStrictComparison =
9637             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9638       if (!ProvedNonEquality)
9639         ProvedNonEquality =
9640             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9641       if (ProvedNonStrictComparison && ProvedNonEquality)
9642         return true;
9643     }
9644     return false;
9645   };
9646 
9647   // Starting at the loop predecessor, climb up the predecessor chain, as long
9648   // as there are predecessors that can be found that have unique successors
9649   // leading to the original header.
9650   for (std::pair<BasicBlock *, BasicBlock *>
9651          Pair(L->getLoopPredecessor(), L->getHeader());
9652        Pair.first;
9653        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9654 
9655     if (ProveViaGuard(Pair.first))
9656       return true;
9657 
9658     BranchInst *LoopEntryPredicate =
9659       dyn_cast<BranchInst>(Pair.first->getTerminator());
9660     if (!LoopEntryPredicate ||
9661         LoopEntryPredicate->isUnconditional())
9662       continue;
9663 
9664     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9665                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9666       return true;
9667   }
9668 
9669   // Check conditions due to any @llvm.assume intrinsics.
9670   for (auto &AssumeVH : AC.assumptions()) {
9671     if (!AssumeVH)
9672       continue;
9673     auto *CI = cast<CallInst>(AssumeVH);
9674     if (!DT.dominates(CI, L->getHeader()))
9675       continue;
9676 
9677     if (ProveViaCond(CI->getArgOperand(0), false))
9678       return true;
9679   }
9680 
9681   return false;
9682 }
9683 
9684 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9685                                     const SCEV *LHS, const SCEV *RHS,
9686                                     Value *FoundCondValue,
9687                                     bool Inverse) {
9688   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9689     return false;
9690 
9691   auto ClearOnExit =
9692       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9693 
9694   // Recursively handle And and Or conditions.
9695   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9696     if (BO->getOpcode() == Instruction::And) {
9697       if (!Inverse)
9698         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9699                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9700     } else if (BO->getOpcode() == Instruction::Or) {
9701       if (Inverse)
9702         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9703                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9704     }
9705   }
9706 
9707   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9708   if (!ICI) return false;
9709 
9710   // Now that we found a conditional branch that dominates the loop or controls
9711   // the loop latch. Check to see if it is the comparison we are looking for.
9712   ICmpInst::Predicate FoundPred;
9713   if (Inverse)
9714     FoundPred = ICI->getInversePredicate();
9715   else
9716     FoundPred = ICI->getPredicate();
9717 
9718   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9719   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9720 
9721   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9722 }
9723 
9724 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9725                                     const SCEV *RHS,
9726                                     ICmpInst::Predicate FoundPred,
9727                                     const SCEV *FoundLHS,
9728                                     const SCEV *FoundRHS) {
9729   // Balance the types.
9730   if (getTypeSizeInBits(LHS->getType()) <
9731       getTypeSizeInBits(FoundLHS->getType())) {
9732     if (CmpInst::isSigned(Pred)) {
9733       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9734       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9735     } else {
9736       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9737       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9738     }
9739   } else if (getTypeSizeInBits(LHS->getType()) >
9740       getTypeSizeInBits(FoundLHS->getType())) {
9741     if (CmpInst::isSigned(FoundPred)) {
9742       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9743       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9744     } else {
9745       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9746       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9747     }
9748   }
9749 
9750   // Canonicalize the query to match the way instcombine will have
9751   // canonicalized the comparison.
9752   if (SimplifyICmpOperands(Pred, LHS, RHS))
9753     if (LHS == RHS)
9754       return CmpInst::isTrueWhenEqual(Pred);
9755   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9756     if (FoundLHS == FoundRHS)
9757       return CmpInst::isFalseWhenEqual(FoundPred);
9758 
9759   // Check to see if we can make the LHS or RHS match.
9760   if (LHS == FoundRHS || RHS == FoundLHS) {
9761     if (isa<SCEVConstant>(RHS)) {
9762       std::swap(FoundLHS, FoundRHS);
9763       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9764     } else {
9765       std::swap(LHS, RHS);
9766       Pred = ICmpInst::getSwappedPredicate(Pred);
9767     }
9768   }
9769 
9770   // Check whether the found predicate is the same as the desired predicate.
9771   if (FoundPred == Pred)
9772     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9773 
9774   // Check whether swapping the found predicate makes it the same as the
9775   // desired predicate.
9776   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9777     if (isa<SCEVConstant>(RHS))
9778       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9779     else
9780       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9781                                    RHS, LHS, FoundLHS, FoundRHS);
9782   }
9783 
9784   // Unsigned comparison is the same as signed comparison when both the operands
9785   // are non-negative.
9786   if (CmpInst::isUnsigned(FoundPred) &&
9787       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9788       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9789     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9790 
9791   // Check if we can make progress by sharpening ranges.
9792   if (FoundPred == ICmpInst::ICMP_NE &&
9793       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9794 
9795     const SCEVConstant *C = nullptr;
9796     const SCEV *V = nullptr;
9797 
9798     if (isa<SCEVConstant>(FoundLHS)) {
9799       C = cast<SCEVConstant>(FoundLHS);
9800       V = FoundRHS;
9801     } else {
9802       C = cast<SCEVConstant>(FoundRHS);
9803       V = FoundLHS;
9804     }
9805 
9806     // The guarding predicate tells us that C != V. If the known range
9807     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9808     // range we consider has to correspond to same signedness as the
9809     // predicate we're interested in folding.
9810 
9811     APInt Min = ICmpInst::isSigned(Pred) ?
9812         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9813 
9814     if (Min == C->getAPInt()) {
9815       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9816       // This is true even if (Min + 1) wraps around -- in case of
9817       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9818 
9819       APInt SharperMin = Min + 1;
9820 
9821       switch (Pred) {
9822         case ICmpInst::ICMP_SGE:
9823         case ICmpInst::ICMP_UGE:
9824           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9825           // RHS, we're done.
9826           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9827                                     getConstant(SharperMin)))
9828             return true;
9829           LLVM_FALLTHROUGH;
9830 
9831         case ICmpInst::ICMP_SGT:
9832         case ICmpInst::ICMP_UGT:
9833           // We know from the range information that (V `Pred` Min ||
9834           // V == Min).  We know from the guarding condition that !(V
9835           // == Min).  This gives us
9836           //
9837           //       V `Pred` Min || V == Min && !(V == Min)
9838           //   =>  V `Pred` Min
9839           //
9840           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9841 
9842           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9843             return true;
9844           LLVM_FALLTHROUGH;
9845 
9846         default:
9847           // No change
9848           break;
9849       }
9850     }
9851   }
9852 
9853   // Check whether the actual condition is beyond sufficient.
9854   if (FoundPred == ICmpInst::ICMP_EQ)
9855     if (ICmpInst::isTrueWhenEqual(Pred))
9856       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9857         return true;
9858   if (Pred == ICmpInst::ICMP_NE)
9859     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9860       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9861         return true;
9862 
9863   // Otherwise assume the worst.
9864   return false;
9865 }
9866 
9867 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9868                                      const SCEV *&L, const SCEV *&R,
9869                                      SCEV::NoWrapFlags &Flags) {
9870   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9871   if (!AE || AE->getNumOperands() != 2)
9872     return false;
9873 
9874   L = AE->getOperand(0);
9875   R = AE->getOperand(1);
9876   Flags = AE->getNoWrapFlags();
9877   return true;
9878 }
9879 
9880 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9881                                                            const SCEV *Less) {
9882   // We avoid subtracting expressions here because this function is usually
9883   // fairly deep in the call stack (i.e. is called many times).
9884 
9885   // X - X = 0.
9886   if (More == Less)
9887     return APInt(getTypeSizeInBits(More->getType()), 0);
9888 
9889   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9890     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9891     const auto *MAR = cast<SCEVAddRecExpr>(More);
9892 
9893     if (LAR->getLoop() != MAR->getLoop())
9894       return None;
9895 
9896     // We look at affine expressions only; not for correctness but to keep
9897     // getStepRecurrence cheap.
9898     if (!LAR->isAffine() || !MAR->isAffine())
9899       return None;
9900 
9901     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9902       return None;
9903 
9904     Less = LAR->getStart();
9905     More = MAR->getStart();
9906 
9907     // fall through
9908   }
9909 
9910   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9911     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9912     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9913     return M - L;
9914   }
9915 
9916   SCEV::NoWrapFlags Flags;
9917   const SCEV *LLess = nullptr, *RLess = nullptr;
9918   const SCEV *LMore = nullptr, *RMore = nullptr;
9919   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9920   // Compare (X + C1) vs X.
9921   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9922     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9923       if (RLess == More)
9924         return -(C1->getAPInt());
9925 
9926   // Compare X vs (X + C2).
9927   if (splitBinaryAdd(More, LMore, RMore, Flags))
9928     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9929       if (RMore == Less)
9930         return C2->getAPInt();
9931 
9932   // Compare (X + C1) vs (X + C2).
9933   if (C1 && C2 && RLess == RMore)
9934     return C2->getAPInt() - C1->getAPInt();
9935 
9936   return None;
9937 }
9938 
9939 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9940     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9941     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9942   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9943     return false;
9944 
9945   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9946   if (!AddRecLHS)
9947     return false;
9948 
9949   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9950   if (!AddRecFoundLHS)
9951     return false;
9952 
9953   // We'd like to let SCEV reason about control dependencies, so we constrain
9954   // both the inequalities to be about add recurrences on the same loop.  This
9955   // way we can use isLoopEntryGuardedByCond later.
9956 
9957   const Loop *L = AddRecFoundLHS->getLoop();
9958   if (L != AddRecLHS->getLoop())
9959     return false;
9960 
9961   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9962   //
9963   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9964   //                                                                  ... (2)
9965   //
9966   // Informal proof for (2), assuming (1) [*]:
9967   //
9968   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9969   //
9970   // Then
9971   //
9972   //       FoundLHS s< FoundRHS s< INT_MIN - C
9973   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9974   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9975   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9976   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9977   // <=>  FoundLHS + C s< FoundRHS + C
9978   //
9979   // [*]: (1) can be proved by ruling out overflow.
9980   //
9981   // [**]: This can be proved by analyzing all the four possibilities:
9982   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9983   //    (A s>= 0, B s>= 0).
9984   //
9985   // Note:
9986   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9987   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9988   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9989   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9990   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9991   // C)".
9992 
9993   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9994   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9995   if (!LDiff || !RDiff || *LDiff != *RDiff)
9996     return false;
9997 
9998   if (LDiff->isMinValue())
9999     return true;
10000 
10001   APInt FoundRHSLimit;
10002 
10003   if (Pred == CmpInst::ICMP_ULT) {
10004     FoundRHSLimit = -(*RDiff);
10005   } else {
10006     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10007     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10008   }
10009 
10010   // Try to prove (1) or (2), as needed.
10011   return isAvailableAtLoopEntry(FoundRHS, L) &&
10012          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10013                                   getConstant(FoundRHSLimit));
10014 }
10015 
10016 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10017                                         const SCEV *LHS, const SCEV *RHS,
10018                                         const SCEV *FoundLHS,
10019                                         const SCEV *FoundRHS, unsigned Depth) {
10020   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10021 
10022   auto ClearOnExit = make_scope_exit([&]() {
10023     if (LPhi) {
10024       bool Erased = PendingMerges.erase(LPhi);
10025       assert(Erased && "Failed to erase LPhi!");
10026       (void)Erased;
10027     }
10028     if (RPhi) {
10029       bool Erased = PendingMerges.erase(RPhi);
10030       assert(Erased && "Failed to erase RPhi!");
10031       (void)Erased;
10032     }
10033   });
10034 
10035   // Find respective Phis and check that they are not being pending.
10036   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10037     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10038       if (!PendingMerges.insert(Phi).second)
10039         return false;
10040       LPhi = Phi;
10041     }
10042   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10043     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10044       // If we detect a loop of Phi nodes being processed by this method, for
10045       // example:
10046       //
10047       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10048       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10049       //
10050       // we don't want to deal with a case that complex, so return conservative
10051       // answer false.
10052       if (!PendingMerges.insert(Phi).second)
10053         return false;
10054       RPhi = Phi;
10055     }
10056 
10057   // If none of LHS, RHS is a Phi, nothing to do here.
10058   if (!LPhi && !RPhi)
10059     return false;
10060 
10061   // If there is a SCEVUnknown Phi we are interested in, make it left.
10062   if (!LPhi) {
10063     std::swap(LHS, RHS);
10064     std::swap(FoundLHS, FoundRHS);
10065     std::swap(LPhi, RPhi);
10066     Pred = ICmpInst::getSwappedPredicate(Pred);
10067   }
10068 
10069   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10070   const BasicBlock *LBB = LPhi->getParent();
10071   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10072 
10073   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10074     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10075            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10076            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10077   };
10078 
10079   if (RPhi && RPhi->getParent() == LBB) {
10080     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10081     // If we compare two Phis from the same block, and for each entry block
10082     // the predicate is true for incoming values from this block, then the
10083     // predicate is also true for the Phis.
10084     for (const BasicBlock *IncBB : predecessors(LBB)) {
10085       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10086       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10087       if (!ProvedEasily(L, R))
10088         return false;
10089     }
10090   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10091     // Case two: RHS is also a Phi from the same basic block, and it is an
10092     // AddRec. It means that there is a loop which has both AddRec and Unknown
10093     // PHIs, for it we can compare incoming values of AddRec from above the loop
10094     // and latch with their respective incoming values of LPhi.
10095     // TODO: Generalize to handle loops with many inputs in a header.
10096     if (LPhi->getNumIncomingValues() != 2) return false;
10097 
10098     auto *RLoop = RAR->getLoop();
10099     auto *Predecessor = RLoop->getLoopPredecessor();
10100     assert(Predecessor && "Loop with AddRec with no predecessor?");
10101     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10102     if (!ProvedEasily(L1, RAR->getStart()))
10103       return false;
10104     auto *Latch = RLoop->getLoopLatch();
10105     assert(Latch && "Loop with AddRec with no latch?");
10106     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10107     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10108       return false;
10109   } else {
10110     // In all other cases go over inputs of LHS and compare each of them to RHS,
10111     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10112     // At this point RHS is either a non-Phi, or it is a Phi from some block
10113     // different from LBB.
10114     for (const BasicBlock *IncBB : predecessors(LBB)) {
10115       // Check that RHS is available in this block.
10116       if (!dominates(RHS, IncBB))
10117         return false;
10118       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10119       if (!ProvedEasily(L, RHS))
10120         return false;
10121     }
10122   }
10123   return true;
10124 }
10125 
10126 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10127                                             const SCEV *LHS, const SCEV *RHS,
10128                                             const SCEV *FoundLHS,
10129                                             const SCEV *FoundRHS) {
10130   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10131     return true;
10132 
10133   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10134     return true;
10135 
10136   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10137                                      FoundLHS, FoundRHS) ||
10138          // ~x < ~y --> x > y
10139          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10140                                      getNotSCEV(FoundRHS),
10141                                      getNotSCEV(FoundLHS));
10142 }
10143 
10144 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10145 template <typename MinMaxExprType>
10146 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10147                                  const SCEV *Candidate) {
10148   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10149   if (!MinMaxExpr)
10150     return false;
10151 
10152   return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10153 }
10154 
10155 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10156                                            ICmpInst::Predicate Pred,
10157                                            const SCEV *LHS, const SCEV *RHS) {
10158   // If both sides are affine addrecs for the same loop, with equal
10159   // steps, and we know the recurrences don't wrap, then we only
10160   // need to check the predicate on the starting values.
10161 
10162   if (!ICmpInst::isRelational(Pred))
10163     return false;
10164 
10165   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10166   if (!LAR)
10167     return false;
10168   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10169   if (!RAR)
10170     return false;
10171   if (LAR->getLoop() != RAR->getLoop())
10172     return false;
10173   if (!LAR->isAffine() || !RAR->isAffine())
10174     return false;
10175 
10176   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10177     return false;
10178 
10179   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10180                          SCEV::FlagNSW : SCEV::FlagNUW;
10181   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10182     return false;
10183 
10184   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10185 }
10186 
10187 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10188 /// expression?
10189 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10190                                         ICmpInst::Predicate Pred,
10191                                         const SCEV *LHS, const SCEV *RHS) {
10192   switch (Pred) {
10193   default:
10194     return false;
10195 
10196   case ICmpInst::ICMP_SGE:
10197     std::swap(LHS, RHS);
10198     LLVM_FALLTHROUGH;
10199   case ICmpInst::ICMP_SLE:
10200     return
10201         // min(A, ...) <= A
10202         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10203         // A <= max(A, ...)
10204         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10205 
10206   case ICmpInst::ICMP_UGE:
10207     std::swap(LHS, RHS);
10208     LLVM_FALLTHROUGH;
10209   case ICmpInst::ICMP_ULE:
10210     return
10211         // min(A, ...) <= A
10212         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10213         // A <= max(A, ...)
10214         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10215   }
10216 
10217   llvm_unreachable("covered switch fell through?!");
10218 }
10219 
10220 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10221                                              const SCEV *LHS, const SCEV *RHS,
10222                                              const SCEV *FoundLHS,
10223                                              const SCEV *FoundRHS,
10224                                              unsigned Depth) {
10225   assert(getTypeSizeInBits(LHS->getType()) ==
10226              getTypeSizeInBits(RHS->getType()) &&
10227          "LHS and RHS have different sizes?");
10228   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10229              getTypeSizeInBits(FoundRHS->getType()) &&
10230          "FoundLHS and FoundRHS have different sizes?");
10231   // We want to avoid hurting the compile time with analysis of too big trees.
10232   if (Depth > MaxSCEVOperationsImplicationDepth)
10233     return false;
10234   // We only want to work with ICMP_SGT comparison so far.
10235   // TODO: Extend to ICMP_UGT?
10236   if (Pred == ICmpInst::ICMP_SLT) {
10237     Pred = ICmpInst::ICMP_SGT;
10238     std::swap(LHS, RHS);
10239     std::swap(FoundLHS, FoundRHS);
10240   }
10241   if (Pred != ICmpInst::ICMP_SGT)
10242     return false;
10243 
10244   auto GetOpFromSExt = [&](const SCEV *S) {
10245     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10246       return Ext->getOperand();
10247     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10248     // the constant in some cases.
10249     return S;
10250   };
10251 
10252   // Acquire values from extensions.
10253   auto *OrigLHS = LHS;
10254   auto *OrigFoundLHS = FoundLHS;
10255   LHS = GetOpFromSExt(LHS);
10256   FoundLHS = GetOpFromSExt(FoundLHS);
10257 
10258   // Is the SGT predicate can be proved trivially or using the found context.
10259   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10260     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10261            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10262                                   FoundRHS, Depth + 1);
10263   };
10264 
10265   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10266     // We want to avoid creation of any new non-constant SCEV. Since we are
10267     // going to compare the operands to RHS, we should be certain that we don't
10268     // need any size extensions for this. So let's decline all cases when the
10269     // sizes of types of LHS and RHS do not match.
10270     // TODO: Maybe try to get RHS from sext to catch more cases?
10271     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10272       return false;
10273 
10274     // Should not overflow.
10275     if (!LHSAddExpr->hasNoSignedWrap())
10276       return false;
10277 
10278     auto *LL = LHSAddExpr->getOperand(0);
10279     auto *LR = LHSAddExpr->getOperand(1);
10280     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
10281 
10282     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10283     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10284       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10285     };
10286     // Try to prove the following rule:
10287     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10288     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10289     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10290       return true;
10291   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10292     Value *LL, *LR;
10293     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10294 
10295     using namespace llvm::PatternMatch;
10296 
10297     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10298       // Rules for division.
10299       // We are going to perform some comparisons with Denominator and its
10300       // derivative expressions. In general case, creating a SCEV for it may
10301       // lead to a complex analysis of the entire graph, and in particular it
10302       // can request trip count recalculation for the same loop. This would
10303       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10304       // this, we only want to create SCEVs that are constants in this section.
10305       // So we bail if Denominator is not a constant.
10306       if (!isa<ConstantInt>(LR))
10307         return false;
10308 
10309       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10310 
10311       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10312       // then a SCEV for the numerator already exists and matches with FoundLHS.
10313       auto *Numerator = getExistingSCEV(LL);
10314       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10315         return false;
10316 
10317       // Make sure that the numerator matches with FoundLHS and the denominator
10318       // is positive.
10319       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10320         return false;
10321 
10322       auto *DTy = Denominator->getType();
10323       auto *FRHSTy = FoundRHS->getType();
10324       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10325         // One of types is a pointer and another one is not. We cannot extend
10326         // them properly to a wider type, so let us just reject this case.
10327         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10328         // to avoid this check.
10329         return false;
10330 
10331       // Given that:
10332       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10333       auto *WTy = getWiderType(DTy, FRHSTy);
10334       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10335       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10336 
10337       // Try to prove the following rule:
10338       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10339       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10340       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10341       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10342       if (isKnownNonPositive(RHS) &&
10343           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10344         return true;
10345 
10346       // Try to prove the following rule:
10347       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10348       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10349       // If we divide it by Denominator > 2, then:
10350       // 1. If FoundLHS is negative, then the result is 0.
10351       // 2. If FoundLHS is non-negative, then the result is non-negative.
10352       // Anyways, the result is non-negative.
10353       auto *MinusOne = getNegativeSCEV(getOne(WTy));
10354       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10355       if (isKnownNegative(RHS) &&
10356           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10357         return true;
10358     }
10359   }
10360 
10361   // If our expression contained SCEVUnknown Phis, and we split it down and now
10362   // need to prove something for them, try to prove the predicate for every
10363   // possible incoming values of those Phis.
10364   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10365     return true;
10366 
10367   return false;
10368 }
10369 
10370 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10371                                         const SCEV *LHS, const SCEV *RHS) {
10372   // zext x u<= sext x, sext x s<= zext x
10373   switch (Pred) {
10374   case ICmpInst::ICMP_SGE:
10375     std::swap(LHS, RHS);
10376     LLVM_FALLTHROUGH;
10377   case ICmpInst::ICMP_SLE: {
10378     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
10379     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10380     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10381     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10382       return true;
10383     break;
10384   }
10385   case ICmpInst::ICMP_UGE:
10386     std::swap(LHS, RHS);
10387     LLVM_FALLTHROUGH;
10388   case ICmpInst::ICMP_ULE: {
10389     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
10390     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10391     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10392     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10393       return true;
10394     break;
10395   }
10396   default:
10397     break;
10398   };
10399   return false;
10400 }
10401 
10402 bool
10403 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10404                                            const SCEV *LHS, const SCEV *RHS) {
10405   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10406          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10407          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10408          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10409          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10410 }
10411 
10412 bool
10413 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10414                                              const SCEV *LHS, const SCEV *RHS,
10415                                              const SCEV *FoundLHS,
10416                                              const SCEV *FoundRHS) {
10417   switch (Pred) {
10418   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10419   case ICmpInst::ICMP_EQ:
10420   case ICmpInst::ICMP_NE:
10421     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10422       return true;
10423     break;
10424   case ICmpInst::ICMP_SLT:
10425   case ICmpInst::ICMP_SLE:
10426     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10427         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10428       return true;
10429     break;
10430   case ICmpInst::ICMP_SGT:
10431   case ICmpInst::ICMP_SGE:
10432     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10433         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10434       return true;
10435     break;
10436   case ICmpInst::ICMP_ULT:
10437   case ICmpInst::ICMP_ULE:
10438     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10439         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10440       return true;
10441     break;
10442   case ICmpInst::ICMP_UGT:
10443   case ICmpInst::ICMP_UGE:
10444     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10445         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10446       return true;
10447     break;
10448   }
10449 
10450   // Maybe it can be proved via operations?
10451   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10452     return true;
10453 
10454   return false;
10455 }
10456 
10457 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10458                                                      const SCEV *LHS,
10459                                                      const SCEV *RHS,
10460                                                      const SCEV *FoundLHS,
10461                                                      const SCEV *FoundRHS) {
10462   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10463     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10464     // reduce the compile time impact of this optimization.
10465     return false;
10466 
10467   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10468   if (!Addend)
10469     return false;
10470 
10471   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10472 
10473   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10474   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10475   ConstantRange FoundLHSRange =
10476       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10477 
10478   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10479   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10480 
10481   // We can also compute the range of values for `LHS` that satisfy the
10482   // consequent, "`LHS` `Pred` `RHS`":
10483   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10484   ConstantRange SatisfyingLHSRange =
10485       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10486 
10487   // The antecedent implies the consequent if every value of `LHS` that
10488   // satisfies the antecedent also satisfies the consequent.
10489   return SatisfyingLHSRange.contains(LHSRange);
10490 }
10491 
10492 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10493                                          bool IsSigned, bool NoWrap) {
10494   assert(isKnownPositive(Stride) && "Positive stride expected!");
10495 
10496   if (NoWrap) return false;
10497 
10498   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10499   const SCEV *One = getOne(Stride->getType());
10500 
10501   if (IsSigned) {
10502     APInt MaxRHS = getSignedRangeMax(RHS);
10503     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10504     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10505 
10506     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10507     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10508   }
10509 
10510   APInt MaxRHS = getUnsignedRangeMax(RHS);
10511   APInt MaxValue = APInt::getMaxValue(BitWidth);
10512   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10513 
10514   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10515   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10516 }
10517 
10518 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10519                                          bool IsSigned, bool NoWrap) {
10520   if (NoWrap) return false;
10521 
10522   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10523   const SCEV *One = getOne(Stride->getType());
10524 
10525   if (IsSigned) {
10526     APInt MinRHS = getSignedRangeMin(RHS);
10527     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10528     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10529 
10530     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10531     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10532   }
10533 
10534   APInt MinRHS = getUnsignedRangeMin(RHS);
10535   APInt MinValue = APInt::getMinValue(BitWidth);
10536   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10537 
10538   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10539   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10540 }
10541 
10542 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10543                                             bool Equality) {
10544   const SCEV *One = getOne(Step->getType());
10545   Delta = Equality ? getAddExpr(Delta, Step)
10546                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10547   return getUDivExpr(Delta, Step);
10548 }
10549 
10550 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10551                                                     const SCEV *Stride,
10552                                                     const SCEV *End,
10553                                                     unsigned BitWidth,
10554                                                     bool IsSigned) {
10555 
10556   assert(!isKnownNonPositive(Stride) &&
10557          "Stride is expected strictly positive!");
10558   // Calculate the maximum backedge count based on the range of values
10559   // permitted by Start, End, and Stride.
10560   const SCEV *MaxBECount;
10561   APInt MinStart =
10562       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10563 
10564   APInt StrideForMaxBECount =
10565       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10566 
10567   // We already know that the stride is positive, so we paper over conservatism
10568   // in our range computation by forcing StrideForMaxBECount to be at least one.
10569   // In theory this is unnecessary, but we expect MaxBECount to be a
10570   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10571   // is nothing to constant fold it to).
10572   APInt One(BitWidth, 1, IsSigned);
10573   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10574 
10575   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10576                             : APInt::getMaxValue(BitWidth);
10577   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10578 
10579   // Although End can be a MAX expression we estimate MaxEnd considering only
10580   // the case End = RHS of the loop termination condition. This is safe because
10581   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10582   // taken count.
10583   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10584                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10585 
10586   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10587                               getConstant(StrideForMaxBECount) /* Step */,
10588                               false /* Equality */);
10589 
10590   return MaxBECount;
10591 }
10592 
10593 ScalarEvolution::ExitLimit
10594 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10595                                   const Loop *L, bool IsSigned,
10596                                   bool ControlsExit, bool AllowPredicates) {
10597   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10598 
10599   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10600   bool PredicatedIV = false;
10601 
10602   if (!IV && AllowPredicates) {
10603     // Try to make this an AddRec using runtime tests, in the first X
10604     // iterations of this loop, where X is the SCEV expression found by the
10605     // algorithm below.
10606     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10607     PredicatedIV = true;
10608   }
10609 
10610   // Avoid weird loops
10611   if (!IV || IV->getLoop() != L || !IV->isAffine())
10612     return getCouldNotCompute();
10613 
10614   bool NoWrap = ControlsExit &&
10615                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10616 
10617   const SCEV *Stride = IV->getStepRecurrence(*this);
10618 
10619   bool PositiveStride = isKnownPositive(Stride);
10620 
10621   // Avoid negative or zero stride values.
10622   if (!PositiveStride) {
10623     // We can compute the correct backedge taken count for loops with unknown
10624     // strides if we can prove that the loop is not an infinite loop with side
10625     // effects. Here's the loop structure we are trying to handle -
10626     //
10627     // i = start
10628     // do {
10629     //   A[i] = i;
10630     //   i += s;
10631     // } while (i < end);
10632     //
10633     // The backedge taken count for such loops is evaluated as -
10634     // (max(end, start + stride) - start - 1) /u stride
10635     //
10636     // The additional preconditions that we need to check to prove correctness
10637     // of the above formula is as follows -
10638     //
10639     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10640     //    NoWrap flag).
10641     // b) loop is single exit with no side effects.
10642     //
10643     //
10644     // Precondition a) implies that if the stride is negative, this is a single
10645     // trip loop. The backedge taken count formula reduces to zero in this case.
10646     //
10647     // Precondition b) implies that the unknown stride cannot be zero otherwise
10648     // we have UB.
10649     //
10650     // The positive stride case is the same as isKnownPositive(Stride) returning
10651     // true (original behavior of the function).
10652     //
10653     // We want to make sure that the stride is truly unknown as there are edge
10654     // cases where ScalarEvolution propagates no wrap flags to the
10655     // post-increment/decrement IV even though the increment/decrement operation
10656     // itself is wrapping. The computed backedge taken count may be wrong in
10657     // such cases. This is prevented by checking that the stride is not known to
10658     // be either positive or non-positive. For example, no wrap flags are
10659     // propagated to the post-increment IV of this loop with a trip count of 2 -
10660     //
10661     // unsigned char i;
10662     // for(i=127; i<128; i+=129)
10663     //   A[i] = i;
10664     //
10665     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10666         !loopHasNoSideEffects(L))
10667       return getCouldNotCompute();
10668   } else if (!Stride->isOne() &&
10669              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10670     // Avoid proven overflow cases: this will ensure that the backedge taken
10671     // count will not generate any unsigned overflow. Relaxed no-overflow
10672     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10673     // undefined behaviors like the case of C language.
10674     return getCouldNotCompute();
10675 
10676   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10677                                       : ICmpInst::ICMP_ULT;
10678   const SCEV *Start = IV->getStart();
10679   const SCEV *End = RHS;
10680   // When the RHS is not invariant, we do not know the end bound of the loop and
10681   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10682   // calculate the MaxBECount, given the start, stride and max value for the end
10683   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10684   // checked above).
10685   if (!isLoopInvariant(RHS, L)) {
10686     const SCEV *MaxBECount = computeMaxBECountForLT(
10687         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10688     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10689                      false /*MaxOrZero*/, Predicates);
10690   }
10691   // If the backedge is taken at least once, then it will be taken
10692   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10693   // is the LHS value of the less-than comparison the first time it is evaluated
10694   // and End is the RHS.
10695   const SCEV *BECountIfBackedgeTaken =
10696     computeBECount(getMinusSCEV(End, Start), Stride, false);
10697   // If the loop entry is guarded by the result of the backedge test of the
10698   // first loop iteration, then we know the backedge will be taken at least
10699   // once and so the backedge taken count is as above. If not then we use the
10700   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10701   // as if the backedge is taken at least once max(End,Start) is End and so the
10702   // result is as above, and if not max(End,Start) is Start so we get a backedge
10703   // count of zero.
10704   const SCEV *BECount;
10705   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10706     BECount = BECountIfBackedgeTaken;
10707   else {
10708     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10709     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10710   }
10711 
10712   const SCEV *MaxBECount;
10713   bool MaxOrZero = false;
10714   if (isa<SCEVConstant>(BECount))
10715     MaxBECount = BECount;
10716   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10717     // If we know exactly how many times the backedge will be taken if it's
10718     // taken at least once, then the backedge count will either be that or
10719     // zero.
10720     MaxBECount = BECountIfBackedgeTaken;
10721     MaxOrZero = true;
10722   } else {
10723     MaxBECount = computeMaxBECountForLT(
10724         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10725   }
10726 
10727   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10728       !isa<SCEVCouldNotCompute>(BECount))
10729     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10730 
10731   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10732 }
10733 
10734 ScalarEvolution::ExitLimit
10735 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10736                                      const Loop *L, bool IsSigned,
10737                                      bool ControlsExit, bool AllowPredicates) {
10738   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10739   // We handle only IV > Invariant
10740   if (!isLoopInvariant(RHS, L))
10741     return getCouldNotCompute();
10742 
10743   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10744   if (!IV && AllowPredicates)
10745     // Try to make this an AddRec using runtime tests, in the first X
10746     // iterations of this loop, where X is the SCEV expression found by the
10747     // algorithm below.
10748     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10749 
10750   // Avoid weird loops
10751   if (!IV || IV->getLoop() != L || !IV->isAffine())
10752     return getCouldNotCompute();
10753 
10754   bool NoWrap = ControlsExit &&
10755                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10756 
10757   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10758 
10759   // Avoid negative or zero stride values
10760   if (!isKnownPositive(Stride))
10761     return getCouldNotCompute();
10762 
10763   // Avoid proven overflow cases: this will ensure that the backedge taken count
10764   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10765   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10766   // behaviors like the case of C language.
10767   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10768     return getCouldNotCompute();
10769 
10770   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10771                                       : ICmpInst::ICMP_UGT;
10772 
10773   const SCEV *Start = IV->getStart();
10774   const SCEV *End = RHS;
10775   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10776     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10777 
10778   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10779 
10780   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10781                             : getUnsignedRangeMax(Start);
10782 
10783   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10784                              : getUnsignedRangeMin(Stride);
10785 
10786   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10787   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10788                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10789 
10790   // Although End can be a MIN expression we estimate MinEnd considering only
10791   // the case End = RHS. This is safe because in the other case (Start - End)
10792   // is zero, leading to a zero maximum backedge taken count.
10793   APInt MinEnd =
10794     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10795              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10796 
10797   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
10798                                ? BECount
10799                                : computeBECount(getConstant(MaxStart - MinEnd),
10800                                                 getConstant(MinStride), false);
10801 
10802   if (isa<SCEVCouldNotCompute>(MaxBECount))
10803     MaxBECount = BECount;
10804 
10805   return ExitLimit(BECount, MaxBECount, false, Predicates);
10806 }
10807 
10808 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10809                                                     ScalarEvolution &SE) const {
10810   if (Range.isFullSet())  // Infinite loop.
10811     return SE.getCouldNotCompute();
10812 
10813   // If the start is a non-zero constant, shift the range to simplify things.
10814   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10815     if (!SC->getValue()->isZero()) {
10816       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10817       Operands[0] = SE.getZero(SC->getType());
10818       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10819                                              getNoWrapFlags(FlagNW));
10820       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10821         return ShiftedAddRec->getNumIterationsInRange(
10822             Range.subtract(SC->getAPInt()), SE);
10823       // This is strange and shouldn't happen.
10824       return SE.getCouldNotCompute();
10825     }
10826 
10827   // The only time we can solve this is when we have all constant indices.
10828   // Otherwise, we cannot determine the overflow conditions.
10829   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10830     return SE.getCouldNotCompute();
10831 
10832   // Okay at this point we know that all elements of the chrec are constants and
10833   // that the start element is zero.
10834 
10835   // First check to see if the range contains zero.  If not, the first
10836   // iteration exits.
10837   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10838   if (!Range.contains(APInt(BitWidth, 0)))
10839     return SE.getZero(getType());
10840 
10841   if (isAffine()) {
10842     // If this is an affine expression then we have this situation:
10843     //   Solve {0,+,A} in Range  ===  Ax in Range
10844 
10845     // We know that zero is in the range.  If A is positive then we know that
10846     // the upper value of the range must be the first possible exit value.
10847     // If A is negative then the lower of the range is the last possible loop
10848     // value.  Also note that we already checked for a full range.
10849     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10850     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10851 
10852     // The exit value should be (End+A)/A.
10853     APInt ExitVal = (End + A).udiv(A);
10854     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10855 
10856     // Evaluate at the exit value.  If we really did fall out of the valid
10857     // range, then we computed our trip count, otherwise wrap around or other
10858     // things must have happened.
10859     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10860     if (Range.contains(Val->getValue()))
10861       return SE.getCouldNotCompute();  // Something strange happened
10862 
10863     // Ensure that the previous value is in the range.  This is a sanity check.
10864     assert(Range.contains(
10865            EvaluateConstantChrecAtConstant(this,
10866            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10867            "Linear scev computation is off in a bad way!");
10868     return SE.getConstant(ExitValue);
10869   }
10870 
10871   if (isQuadratic()) {
10872     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
10873       return SE.getConstant(S.getValue());
10874   }
10875 
10876   return SE.getCouldNotCompute();
10877 }
10878 
10879 const SCEVAddRecExpr *
10880 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10881   assert(getNumOperands() > 1 && "AddRec with zero step?");
10882   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10883   // but in this case we cannot guarantee that the value returned will be an
10884   // AddRec because SCEV does not have a fixed point where it stops
10885   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10886   // may happen if we reach arithmetic depth limit while simplifying. So we
10887   // construct the returned value explicitly.
10888   SmallVector<const SCEV *, 3> Ops;
10889   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10890   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10891   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10892     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10893   // We know that the last operand is not a constant zero (otherwise it would
10894   // have been popped out earlier). This guarantees us that if the result has
10895   // the same last operand, then it will also not be popped out, meaning that
10896   // the returned value will be an AddRec.
10897   const SCEV *Last = getOperand(getNumOperands() - 1);
10898   assert(!Last->isZero() && "Recurrency with zero step?");
10899   Ops.push_back(Last);
10900   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10901                                                SCEV::FlagAnyWrap));
10902 }
10903 
10904 // Return true when S contains at least an undef value.
10905 static inline bool containsUndefs(const SCEV *S) {
10906   return SCEVExprContains(S, [](const SCEV *S) {
10907     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10908       return isa<UndefValue>(SU->getValue());
10909     return false;
10910   });
10911 }
10912 
10913 namespace {
10914 
10915 // Collect all steps of SCEV expressions.
10916 struct SCEVCollectStrides {
10917   ScalarEvolution &SE;
10918   SmallVectorImpl<const SCEV *> &Strides;
10919 
10920   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10921       : SE(SE), Strides(S) {}
10922 
10923   bool follow(const SCEV *S) {
10924     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10925       Strides.push_back(AR->getStepRecurrence(SE));
10926     return true;
10927   }
10928 
10929   bool isDone() const { return false; }
10930 };
10931 
10932 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10933 struct SCEVCollectTerms {
10934   SmallVectorImpl<const SCEV *> &Terms;
10935 
10936   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10937 
10938   bool follow(const SCEV *S) {
10939     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10940         isa<SCEVSignExtendExpr>(S)) {
10941       if (!containsUndefs(S))
10942         Terms.push_back(S);
10943 
10944       // Stop recursion: once we collected a term, do not walk its operands.
10945       return false;
10946     }
10947 
10948     // Keep looking.
10949     return true;
10950   }
10951 
10952   bool isDone() const { return false; }
10953 };
10954 
10955 // Check if a SCEV contains an AddRecExpr.
10956 struct SCEVHasAddRec {
10957   bool &ContainsAddRec;
10958 
10959   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10960     ContainsAddRec = false;
10961   }
10962 
10963   bool follow(const SCEV *S) {
10964     if (isa<SCEVAddRecExpr>(S)) {
10965       ContainsAddRec = true;
10966 
10967       // Stop recursion: once we collected a term, do not walk its operands.
10968       return false;
10969     }
10970 
10971     // Keep looking.
10972     return true;
10973   }
10974 
10975   bool isDone() const { return false; }
10976 };
10977 
10978 // Find factors that are multiplied with an expression that (possibly as a
10979 // subexpression) contains an AddRecExpr. In the expression:
10980 //
10981 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10982 //
10983 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10984 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10985 // parameters as they form a product with an induction variable.
10986 //
10987 // This collector expects all array size parameters to be in the same MulExpr.
10988 // It might be necessary to later add support for collecting parameters that are
10989 // spread over different nested MulExpr.
10990 struct SCEVCollectAddRecMultiplies {
10991   SmallVectorImpl<const SCEV *> &Terms;
10992   ScalarEvolution &SE;
10993 
10994   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10995       : Terms(T), SE(SE) {}
10996 
10997   bool follow(const SCEV *S) {
10998     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10999       bool HasAddRec = false;
11000       SmallVector<const SCEV *, 0> Operands;
11001       for (auto Op : Mul->operands()) {
11002         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11003         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11004           Operands.push_back(Op);
11005         } else if (Unknown) {
11006           HasAddRec = true;
11007         } else {
11008           bool ContainsAddRec = false;
11009           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11010           visitAll(Op, ContiansAddRec);
11011           HasAddRec |= ContainsAddRec;
11012         }
11013       }
11014       if (Operands.size() == 0)
11015         return true;
11016 
11017       if (!HasAddRec)
11018         return false;
11019 
11020       Terms.push_back(SE.getMulExpr(Operands));
11021       // Stop recursion: once we collected a term, do not walk its operands.
11022       return false;
11023     }
11024 
11025     // Keep looking.
11026     return true;
11027   }
11028 
11029   bool isDone() const { return false; }
11030 };
11031 
11032 } // end anonymous namespace
11033 
11034 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11035 /// two places:
11036 ///   1) The strides of AddRec expressions.
11037 ///   2) Unknowns that are multiplied with AddRec expressions.
11038 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11039     SmallVectorImpl<const SCEV *> &Terms) {
11040   SmallVector<const SCEV *, 4> Strides;
11041   SCEVCollectStrides StrideCollector(*this, Strides);
11042   visitAll(Expr, StrideCollector);
11043 
11044   LLVM_DEBUG({
11045     dbgs() << "Strides:\n";
11046     for (const SCEV *S : Strides)
11047       dbgs() << *S << "\n";
11048   });
11049 
11050   for (const SCEV *S : Strides) {
11051     SCEVCollectTerms TermCollector(Terms);
11052     visitAll(S, TermCollector);
11053   }
11054 
11055   LLVM_DEBUG({
11056     dbgs() << "Terms:\n";
11057     for (const SCEV *T : Terms)
11058       dbgs() << *T << "\n";
11059   });
11060 
11061   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11062   visitAll(Expr, MulCollector);
11063 }
11064 
11065 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11066                                    SmallVectorImpl<const SCEV *> &Terms,
11067                                    SmallVectorImpl<const SCEV *> &Sizes) {
11068   int Last = Terms.size() - 1;
11069   const SCEV *Step = Terms[Last];
11070 
11071   // End of recursion.
11072   if (Last == 0) {
11073     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11074       SmallVector<const SCEV *, 2> Qs;
11075       for (const SCEV *Op : M->operands())
11076         if (!isa<SCEVConstant>(Op))
11077           Qs.push_back(Op);
11078 
11079       Step = SE.getMulExpr(Qs);
11080     }
11081 
11082     Sizes.push_back(Step);
11083     return true;
11084   }
11085 
11086   for (const SCEV *&Term : Terms) {
11087     // Normalize the terms before the next call to findArrayDimensionsRec.
11088     const SCEV *Q, *R;
11089     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11090 
11091     // Bail out when GCD does not evenly divide one of the terms.
11092     if (!R->isZero())
11093       return false;
11094 
11095     Term = Q;
11096   }
11097 
11098   // Remove all SCEVConstants.
11099   Terms.erase(
11100       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11101       Terms.end());
11102 
11103   if (Terms.size() > 0)
11104     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11105       return false;
11106 
11107   Sizes.push_back(Step);
11108   return true;
11109 }
11110 
11111 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11112 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11113   for (const SCEV *T : Terms)
11114     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
11115       return true;
11116   return false;
11117 }
11118 
11119 // Return the number of product terms in S.
11120 static inline int numberOfTerms(const SCEV *S) {
11121   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11122     return Expr->getNumOperands();
11123   return 1;
11124 }
11125 
11126 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11127   if (isa<SCEVConstant>(T))
11128     return nullptr;
11129 
11130   if (isa<SCEVUnknown>(T))
11131     return T;
11132 
11133   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11134     SmallVector<const SCEV *, 2> Factors;
11135     for (const SCEV *Op : M->operands())
11136       if (!isa<SCEVConstant>(Op))
11137         Factors.push_back(Op);
11138 
11139     return SE.getMulExpr(Factors);
11140   }
11141 
11142   return T;
11143 }
11144 
11145 /// Return the size of an element read or written by Inst.
11146 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11147   Type *Ty;
11148   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11149     Ty = Store->getValueOperand()->getType();
11150   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11151     Ty = Load->getType();
11152   else
11153     return nullptr;
11154 
11155   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11156   return getSizeOfExpr(ETy, Ty);
11157 }
11158 
11159 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11160                                           SmallVectorImpl<const SCEV *> &Sizes,
11161                                           const SCEV *ElementSize) {
11162   if (Terms.size() < 1 || !ElementSize)
11163     return;
11164 
11165   // Early return when Terms do not contain parameters: we do not delinearize
11166   // non parametric SCEVs.
11167   if (!containsParameters(Terms))
11168     return;
11169 
11170   LLVM_DEBUG({
11171     dbgs() << "Terms:\n";
11172     for (const SCEV *T : Terms)
11173       dbgs() << *T << "\n";
11174   });
11175 
11176   // Remove duplicates.
11177   array_pod_sort(Terms.begin(), Terms.end());
11178   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11179 
11180   // Put larger terms first.
11181   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11182     return numberOfTerms(LHS) > numberOfTerms(RHS);
11183   });
11184 
11185   // Try to divide all terms by the element size. If term is not divisible by
11186   // element size, proceed with the original term.
11187   for (const SCEV *&Term : Terms) {
11188     const SCEV *Q, *R;
11189     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11190     if (!Q->isZero())
11191       Term = Q;
11192   }
11193 
11194   SmallVector<const SCEV *, 4> NewTerms;
11195 
11196   // Remove constant factors.
11197   for (const SCEV *T : Terms)
11198     if (const SCEV *NewT = removeConstantFactors(*this, T))
11199       NewTerms.push_back(NewT);
11200 
11201   LLVM_DEBUG({
11202     dbgs() << "Terms after sorting:\n";
11203     for (const SCEV *T : NewTerms)
11204       dbgs() << *T << "\n";
11205   });
11206 
11207   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11208     Sizes.clear();
11209     return;
11210   }
11211 
11212   // The last element to be pushed into Sizes is the size of an element.
11213   Sizes.push_back(ElementSize);
11214 
11215   LLVM_DEBUG({
11216     dbgs() << "Sizes:\n";
11217     for (const SCEV *S : Sizes)
11218       dbgs() << *S << "\n";
11219   });
11220 }
11221 
11222 void ScalarEvolution::computeAccessFunctions(
11223     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11224     SmallVectorImpl<const SCEV *> &Sizes) {
11225   // Early exit in case this SCEV is not an affine multivariate function.
11226   if (Sizes.empty())
11227     return;
11228 
11229   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11230     if (!AR->isAffine())
11231       return;
11232 
11233   const SCEV *Res = Expr;
11234   int Last = Sizes.size() - 1;
11235   for (int i = Last; i >= 0; i--) {
11236     const SCEV *Q, *R;
11237     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11238 
11239     LLVM_DEBUG({
11240       dbgs() << "Res: " << *Res << "\n";
11241       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11242       dbgs() << "Res divided by Sizes[i]:\n";
11243       dbgs() << "Quotient: " << *Q << "\n";
11244       dbgs() << "Remainder: " << *R << "\n";
11245     });
11246 
11247     Res = Q;
11248 
11249     // Do not record the last subscript corresponding to the size of elements in
11250     // the array.
11251     if (i == Last) {
11252 
11253       // Bail out if the remainder is too complex.
11254       if (isa<SCEVAddRecExpr>(R)) {
11255         Subscripts.clear();
11256         Sizes.clear();
11257         return;
11258       }
11259 
11260       continue;
11261     }
11262 
11263     // Record the access function for the current subscript.
11264     Subscripts.push_back(R);
11265   }
11266 
11267   // Also push in last position the remainder of the last division: it will be
11268   // the access function of the innermost dimension.
11269   Subscripts.push_back(Res);
11270 
11271   std::reverse(Subscripts.begin(), Subscripts.end());
11272 
11273   LLVM_DEBUG({
11274     dbgs() << "Subscripts:\n";
11275     for (const SCEV *S : Subscripts)
11276       dbgs() << *S << "\n";
11277   });
11278 }
11279 
11280 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11281 /// sizes of an array access. Returns the remainder of the delinearization that
11282 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11283 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11284 /// expressions in the stride and base of a SCEV corresponding to the
11285 /// computation of a GCD (greatest common divisor) of base and stride.  When
11286 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11287 ///
11288 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11289 ///
11290 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11291 ///
11292 ///    for (long i = 0; i < n; i++)
11293 ///      for (long j = 0; j < m; j++)
11294 ///        for (long k = 0; k < o; k++)
11295 ///          A[i][j][k] = 1.0;
11296 ///  }
11297 ///
11298 /// the delinearization input is the following AddRec SCEV:
11299 ///
11300 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11301 ///
11302 /// From this SCEV, we are able to say that the base offset of the access is %A
11303 /// because it appears as an offset that does not divide any of the strides in
11304 /// the loops:
11305 ///
11306 ///  CHECK: Base offset: %A
11307 ///
11308 /// and then SCEV->delinearize determines the size of some of the dimensions of
11309 /// the array as these are the multiples by which the strides are happening:
11310 ///
11311 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11312 ///
11313 /// Note that the outermost dimension remains of UnknownSize because there are
11314 /// no strides that would help identifying the size of the last dimension: when
11315 /// the array has been statically allocated, one could compute the size of that
11316 /// dimension by dividing the overall size of the array by the size of the known
11317 /// dimensions: %m * %o * 8.
11318 ///
11319 /// Finally delinearize provides the access functions for the array reference
11320 /// that does correspond to A[i][j][k] of the above C testcase:
11321 ///
11322 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11323 ///
11324 /// The testcases are checking the output of a function pass:
11325 /// DelinearizationPass that walks through all loads and stores of a function
11326 /// asking for the SCEV of the memory access with respect to all enclosing
11327 /// loops, calling SCEV->delinearize on that and printing the results.
11328 void ScalarEvolution::delinearize(const SCEV *Expr,
11329                                  SmallVectorImpl<const SCEV *> &Subscripts,
11330                                  SmallVectorImpl<const SCEV *> &Sizes,
11331                                  const SCEV *ElementSize) {
11332   // First step: collect parametric terms.
11333   SmallVector<const SCEV *, 4> Terms;
11334   collectParametricTerms(Expr, Terms);
11335 
11336   if (Terms.empty())
11337     return;
11338 
11339   // Second step: find subscript sizes.
11340   findArrayDimensions(Terms, Sizes, ElementSize);
11341 
11342   if (Sizes.empty())
11343     return;
11344 
11345   // Third step: compute the access functions for each subscript.
11346   computeAccessFunctions(Expr, Subscripts, Sizes);
11347 
11348   if (Subscripts.empty())
11349     return;
11350 
11351   LLVM_DEBUG({
11352     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11353     dbgs() << "ArrayDecl[UnknownSize]";
11354     for (const SCEV *S : Sizes)
11355       dbgs() << "[" << *S << "]";
11356 
11357     dbgs() << "\nArrayRef";
11358     for (const SCEV *S : Subscripts)
11359       dbgs() << "[" << *S << "]";
11360     dbgs() << "\n";
11361   });
11362 }
11363 
11364 //===----------------------------------------------------------------------===//
11365 //                   SCEVCallbackVH Class Implementation
11366 //===----------------------------------------------------------------------===//
11367 
11368 void ScalarEvolution::SCEVCallbackVH::deleted() {
11369   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11370   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11371     SE->ConstantEvolutionLoopExitValue.erase(PN);
11372   SE->eraseValueFromMap(getValPtr());
11373   // this now dangles!
11374 }
11375 
11376 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11377   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11378 
11379   // Forget all the expressions associated with users of the old value,
11380   // so that future queries will recompute the expressions using the new
11381   // value.
11382   Value *Old = getValPtr();
11383   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11384   SmallPtrSet<User *, 8> Visited;
11385   while (!Worklist.empty()) {
11386     User *U = Worklist.pop_back_val();
11387     // Deleting the Old value will cause this to dangle. Postpone
11388     // that until everything else is done.
11389     if (U == Old)
11390       continue;
11391     if (!Visited.insert(U).second)
11392       continue;
11393     if (PHINode *PN = dyn_cast<PHINode>(U))
11394       SE->ConstantEvolutionLoopExitValue.erase(PN);
11395     SE->eraseValueFromMap(U);
11396     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11397   }
11398   // Delete the Old value.
11399   if (PHINode *PN = dyn_cast<PHINode>(Old))
11400     SE->ConstantEvolutionLoopExitValue.erase(PN);
11401   SE->eraseValueFromMap(Old);
11402   // this now dangles!
11403 }
11404 
11405 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11406   : CallbackVH(V), SE(se) {}
11407 
11408 //===----------------------------------------------------------------------===//
11409 //                   ScalarEvolution Class Implementation
11410 //===----------------------------------------------------------------------===//
11411 
11412 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11413                                  AssumptionCache &AC, DominatorTree &DT,
11414                                  LoopInfo &LI)
11415     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11416       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11417       LoopDispositions(64), BlockDispositions(64) {
11418   // To use guards for proving predicates, we need to scan every instruction in
11419   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11420   // time if the IR does not actually contain any calls to
11421   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11422   //
11423   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11424   // to _add_ guards to the module when there weren't any before, and wants
11425   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11426   // efficient in lieu of being smart in that rather obscure case.
11427 
11428   auto *GuardDecl = F.getParent()->getFunction(
11429       Intrinsic::getName(Intrinsic::experimental_guard));
11430   HasGuards = GuardDecl && !GuardDecl->use_empty();
11431 }
11432 
11433 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11434     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11435       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11436       ValueExprMap(std::move(Arg.ValueExprMap)),
11437       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11438       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11439       PendingMerges(std::move(Arg.PendingMerges)),
11440       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11441       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11442       PredicatedBackedgeTakenCounts(
11443           std::move(Arg.PredicatedBackedgeTakenCounts)),
11444       ConstantEvolutionLoopExitValue(
11445           std::move(Arg.ConstantEvolutionLoopExitValue)),
11446       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11447       LoopDispositions(std::move(Arg.LoopDispositions)),
11448       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11449       BlockDispositions(std::move(Arg.BlockDispositions)),
11450       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11451       SignedRanges(std::move(Arg.SignedRanges)),
11452       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11453       UniquePreds(std::move(Arg.UniquePreds)),
11454       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11455       LoopUsers(std::move(Arg.LoopUsers)),
11456       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11457       FirstUnknown(Arg.FirstUnknown) {
11458   Arg.FirstUnknown = nullptr;
11459 }
11460 
11461 ScalarEvolution::~ScalarEvolution() {
11462   // Iterate through all the SCEVUnknown instances and call their
11463   // destructors, so that they release their references to their values.
11464   for (SCEVUnknown *U = FirstUnknown; U;) {
11465     SCEVUnknown *Tmp = U;
11466     U = U->Next;
11467     Tmp->~SCEVUnknown();
11468   }
11469   FirstUnknown = nullptr;
11470 
11471   ExprValueMap.clear();
11472   ValueExprMap.clear();
11473   HasRecMap.clear();
11474 
11475   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11476   // that a loop had multiple computable exits.
11477   for (auto &BTCI : BackedgeTakenCounts)
11478     BTCI.second.clear();
11479   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11480     BTCI.second.clear();
11481 
11482   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11483   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11484   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11485   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11486   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11487 }
11488 
11489 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11490   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11491 }
11492 
11493 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11494                           const Loop *L) {
11495   // Print all inner loops first
11496   for (Loop *I : *L)
11497     PrintLoopInfo(OS, SE, I);
11498 
11499   OS << "Loop ";
11500   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11501   OS << ": ";
11502 
11503   SmallVector<BasicBlock *, 8> ExitingBlocks;
11504   L->getExitingBlocks(ExitingBlocks);
11505   if (ExitingBlocks.size() != 1)
11506     OS << "<multiple exits> ";
11507 
11508   if (SE->hasLoopInvariantBackedgeTakenCount(L))
11509     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
11510   else
11511     OS << "Unpredictable backedge-taken count.\n";
11512 
11513   if (ExitingBlocks.size() > 1)
11514     for (BasicBlock *ExitingBlock : ExitingBlocks) {
11515       OS << "  exit count for " << ExitingBlock->getName() << ": "
11516          << *SE->getExitCount(L, ExitingBlock) << "\n";
11517     }
11518 
11519   OS << "Loop ";
11520   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11521   OS << ": ";
11522 
11523   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
11524     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
11525     if (SE->isBackedgeTakenCountMaxOrZero(L))
11526       OS << ", actual taken count either this or zero.";
11527   } else {
11528     OS << "Unpredictable max backedge-taken count. ";
11529   }
11530 
11531   OS << "\n"
11532         "Loop ";
11533   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11534   OS << ": ";
11535 
11536   SCEVUnionPredicate Pred;
11537   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11538   if (!isa<SCEVCouldNotCompute>(PBT)) {
11539     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11540     OS << " Predicates:\n";
11541     Pred.print(OS, 4);
11542   } else {
11543     OS << "Unpredictable predicated backedge-taken count. ";
11544   }
11545   OS << "\n";
11546 
11547   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11548     OS << "Loop ";
11549     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11550     OS << ": ";
11551     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11552   }
11553 }
11554 
11555 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11556   switch (LD) {
11557   case ScalarEvolution::LoopVariant:
11558     return "Variant";
11559   case ScalarEvolution::LoopInvariant:
11560     return "Invariant";
11561   case ScalarEvolution::LoopComputable:
11562     return "Computable";
11563   }
11564   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11565 }
11566 
11567 void ScalarEvolution::print(raw_ostream &OS) const {
11568   // ScalarEvolution's implementation of the print method is to print
11569   // out SCEV values of all instructions that are interesting. Doing
11570   // this potentially causes it to create new SCEV objects though,
11571   // which technically conflicts with the const qualifier. This isn't
11572   // observable from outside the class though, so casting away the
11573   // const isn't dangerous.
11574   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11575 
11576   OS << "Classifying expressions for: ";
11577   F.printAsOperand(OS, /*PrintType=*/false);
11578   OS << "\n";
11579   for (Instruction &I : instructions(F))
11580     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11581       OS << I << '\n';
11582       OS << "  -->  ";
11583       const SCEV *SV = SE.getSCEV(&I);
11584       SV->print(OS);
11585       if (!isa<SCEVCouldNotCompute>(SV)) {
11586         OS << " U: ";
11587         SE.getUnsignedRange(SV).print(OS);
11588         OS << " S: ";
11589         SE.getSignedRange(SV).print(OS);
11590       }
11591 
11592       const Loop *L = LI.getLoopFor(I.getParent());
11593 
11594       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11595       if (AtUse != SV) {
11596         OS << "  -->  ";
11597         AtUse->print(OS);
11598         if (!isa<SCEVCouldNotCompute>(AtUse)) {
11599           OS << " U: ";
11600           SE.getUnsignedRange(AtUse).print(OS);
11601           OS << " S: ";
11602           SE.getSignedRange(AtUse).print(OS);
11603         }
11604       }
11605 
11606       if (L) {
11607         OS << "\t\t" "Exits: ";
11608         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11609         if (!SE.isLoopInvariant(ExitValue, L)) {
11610           OS << "<<Unknown>>";
11611         } else {
11612           OS << *ExitValue;
11613         }
11614 
11615         bool First = true;
11616         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11617           if (First) {
11618             OS << "\t\t" "LoopDispositions: { ";
11619             First = false;
11620           } else {
11621             OS << ", ";
11622           }
11623 
11624           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11625           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11626         }
11627 
11628         for (auto *InnerL : depth_first(L)) {
11629           if (InnerL == L)
11630             continue;
11631           if (First) {
11632             OS << "\t\t" "LoopDispositions: { ";
11633             First = false;
11634           } else {
11635             OS << ", ";
11636           }
11637 
11638           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11639           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11640         }
11641 
11642         OS << " }";
11643       }
11644 
11645       OS << "\n";
11646     }
11647 
11648   OS << "Determining loop execution counts for: ";
11649   F.printAsOperand(OS, /*PrintType=*/false);
11650   OS << "\n";
11651   for (Loop *I : LI)
11652     PrintLoopInfo(OS, &SE, I);
11653 }
11654 
11655 ScalarEvolution::LoopDisposition
11656 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11657   auto &Values = LoopDispositions[S];
11658   for (auto &V : Values) {
11659     if (V.getPointer() == L)
11660       return V.getInt();
11661   }
11662   Values.emplace_back(L, LoopVariant);
11663   LoopDisposition D = computeLoopDisposition(S, L);
11664   auto &Values2 = LoopDispositions[S];
11665   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11666     if (V.getPointer() == L) {
11667       V.setInt(D);
11668       break;
11669     }
11670   }
11671   return D;
11672 }
11673 
11674 ScalarEvolution::LoopDisposition
11675 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11676   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11677   case scConstant:
11678     return LoopInvariant;
11679   case scTruncate:
11680   case scZeroExtend:
11681   case scSignExtend:
11682     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11683   case scAddRecExpr: {
11684     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11685 
11686     // If L is the addrec's loop, it's computable.
11687     if (AR->getLoop() == L)
11688       return LoopComputable;
11689 
11690     // Add recurrences are never invariant in the function-body (null loop).
11691     if (!L)
11692       return LoopVariant;
11693 
11694     // Everything that is not defined at loop entry is variant.
11695     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11696       return LoopVariant;
11697     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11698            " dominate the contained loop's header?");
11699 
11700     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11701     if (AR->getLoop()->contains(L))
11702       return LoopInvariant;
11703 
11704     // This recurrence is variant w.r.t. L if any of its operands
11705     // are variant.
11706     for (auto *Op : AR->operands())
11707       if (!isLoopInvariant(Op, L))
11708         return LoopVariant;
11709 
11710     // Otherwise it's loop-invariant.
11711     return LoopInvariant;
11712   }
11713   case scAddExpr:
11714   case scMulExpr:
11715   case scUMaxExpr:
11716   case scSMaxExpr:
11717   case scUMinExpr:
11718   case scSMinExpr: {
11719     bool HasVarying = false;
11720     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11721       LoopDisposition D = getLoopDisposition(Op, L);
11722       if (D == LoopVariant)
11723         return LoopVariant;
11724       if (D == LoopComputable)
11725         HasVarying = true;
11726     }
11727     return HasVarying ? LoopComputable : LoopInvariant;
11728   }
11729   case scUDivExpr: {
11730     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11731     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11732     if (LD == LoopVariant)
11733       return LoopVariant;
11734     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11735     if (RD == LoopVariant)
11736       return LoopVariant;
11737     return (LD == LoopInvariant && RD == LoopInvariant) ?
11738            LoopInvariant : LoopComputable;
11739   }
11740   case scUnknown:
11741     // All non-instruction values are loop invariant.  All instructions are loop
11742     // invariant if they are not contained in the specified loop.
11743     // Instructions are never considered invariant in the function body
11744     // (null loop) because they are defined within the "loop".
11745     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11746       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11747     return LoopInvariant;
11748   case scCouldNotCompute:
11749     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11750   }
11751   llvm_unreachable("Unknown SCEV kind!");
11752 }
11753 
11754 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11755   return getLoopDisposition(S, L) == LoopInvariant;
11756 }
11757 
11758 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11759   return getLoopDisposition(S, L) == LoopComputable;
11760 }
11761 
11762 ScalarEvolution::BlockDisposition
11763 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11764   auto &Values = BlockDispositions[S];
11765   for (auto &V : Values) {
11766     if (V.getPointer() == BB)
11767       return V.getInt();
11768   }
11769   Values.emplace_back(BB, DoesNotDominateBlock);
11770   BlockDisposition D = computeBlockDisposition(S, BB);
11771   auto &Values2 = BlockDispositions[S];
11772   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11773     if (V.getPointer() == BB) {
11774       V.setInt(D);
11775       break;
11776     }
11777   }
11778   return D;
11779 }
11780 
11781 ScalarEvolution::BlockDisposition
11782 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11783   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11784   case scConstant:
11785     return ProperlyDominatesBlock;
11786   case scTruncate:
11787   case scZeroExtend:
11788   case scSignExtend:
11789     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11790   case scAddRecExpr: {
11791     // This uses a "dominates" query instead of "properly dominates" query
11792     // to test for proper dominance too, because the instruction which
11793     // produces the addrec's value is a PHI, and a PHI effectively properly
11794     // dominates its entire containing block.
11795     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11796     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11797       return DoesNotDominateBlock;
11798 
11799     // Fall through into SCEVNAryExpr handling.
11800     LLVM_FALLTHROUGH;
11801   }
11802   case scAddExpr:
11803   case scMulExpr:
11804   case scUMaxExpr:
11805   case scSMaxExpr:
11806   case scUMinExpr:
11807   case scSMinExpr: {
11808     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11809     bool Proper = true;
11810     for (const SCEV *NAryOp : NAry->operands()) {
11811       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11812       if (D == DoesNotDominateBlock)
11813         return DoesNotDominateBlock;
11814       if (D == DominatesBlock)
11815         Proper = false;
11816     }
11817     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11818   }
11819   case scUDivExpr: {
11820     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11821     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11822     BlockDisposition LD = getBlockDisposition(LHS, BB);
11823     if (LD == DoesNotDominateBlock)
11824       return DoesNotDominateBlock;
11825     BlockDisposition RD = getBlockDisposition(RHS, BB);
11826     if (RD == DoesNotDominateBlock)
11827       return DoesNotDominateBlock;
11828     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11829       ProperlyDominatesBlock : DominatesBlock;
11830   }
11831   case scUnknown:
11832     if (Instruction *I =
11833           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11834       if (I->getParent() == BB)
11835         return DominatesBlock;
11836       if (DT.properlyDominates(I->getParent(), BB))
11837         return ProperlyDominatesBlock;
11838       return DoesNotDominateBlock;
11839     }
11840     return ProperlyDominatesBlock;
11841   case scCouldNotCompute:
11842     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11843   }
11844   llvm_unreachable("Unknown SCEV kind!");
11845 }
11846 
11847 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11848   return getBlockDisposition(S, BB) >= DominatesBlock;
11849 }
11850 
11851 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11852   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11853 }
11854 
11855 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11856   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11857 }
11858 
11859 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11860   auto IsS = [&](const SCEV *X) { return S == X; };
11861   auto ContainsS = [&](const SCEV *X) {
11862     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11863   };
11864   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11865 }
11866 
11867 void
11868 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11869   ValuesAtScopes.erase(S);
11870   LoopDispositions.erase(S);
11871   BlockDispositions.erase(S);
11872   UnsignedRanges.erase(S);
11873   SignedRanges.erase(S);
11874   ExprValueMap.erase(S);
11875   HasRecMap.erase(S);
11876   MinTrailingZerosCache.erase(S);
11877 
11878   for (auto I = PredicatedSCEVRewrites.begin();
11879        I != PredicatedSCEVRewrites.end();) {
11880     std::pair<const SCEV *, const Loop *> Entry = I->first;
11881     if (Entry.first == S)
11882       PredicatedSCEVRewrites.erase(I++);
11883     else
11884       ++I;
11885   }
11886 
11887   auto RemoveSCEVFromBackedgeMap =
11888       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11889         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11890           BackedgeTakenInfo &BEInfo = I->second;
11891           if (BEInfo.hasOperand(S, this)) {
11892             BEInfo.clear();
11893             Map.erase(I++);
11894           } else
11895             ++I;
11896         }
11897       };
11898 
11899   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11900   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11901 }
11902 
11903 void
11904 ScalarEvolution::getUsedLoops(const SCEV *S,
11905                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11906   struct FindUsedLoops {
11907     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11908         : LoopsUsed(LoopsUsed) {}
11909     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11910     bool follow(const SCEV *S) {
11911       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11912         LoopsUsed.insert(AR->getLoop());
11913       return true;
11914     }
11915 
11916     bool isDone() const { return false; }
11917   };
11918 
11919   FindUsedLoops F(LoopsUsed);
11920   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11921 }
11922 
11923 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11924   SmallPtrSet<const Loop *, 8> LoopsUsed;
11925   getUsedLoops(S, LoopsUsed);
11926   for (auto *L : LoopsUsed)
11927     LoopUsers[L].push_back(S);
11928 }
11929 
11930 void ScalarEvolution::verify() const {
11931   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11932   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11933 
11934   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11935 
11936   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11937   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11938     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11939 
11940     const SCEV *visitConstant(const SCEVConstant *Constant) {
11941       return SE.getConstant(Constant->getAPInt());
11942     }
11943 
11944     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11945       return SE.getUnknown(Expr->getValue());
11946     }
11947 
11948     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11949       return SE.getCouldNotCompute();
11950     }
11951   };
11952 
11953   SCEVMapper SCM(SE2);
11954 
11955   while (!LoopStack.empty()) {
11956     auto *L = LoopStack.pop_back_val();
11957     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11958 
11959     auto *CurBECount = SCM.visit(
11960         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11961     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11962 
11963     if (CurBECount == SE2.getCouldNotCompute() ||
11964         NewBECount == SE2.getCouldNotCompute()) {
11965       // NB! This situation is legal, but is very suspicious -- whatever pass
11966       // change the loop to make a trip count go from could not compute to
11967       // computable or vice-versa *should have* invalidated SCEV.  However, we
11968       // choose not to assert here (for now) since we don't want false
11969       // positives.
11970       continue;
11971     }
11972 
11973     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11974       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11975       // not propagate undef aggressively).  This means we can (and do) fail
11976       // verification in cases where a transform makes the trip count of a loop
11977       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11978       // both cases the loop iterates "undef" times, but SCEV thinks we
11979       // increased the trip count of the loop by 1 incorrectly.
11980       continue;
11981     }
11982 
11983     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11984         SE.getTypeSizeInBits(NewBECount->getType()))
11985       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11986     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11987              SE.getTypeSizeInBits(NewBECount->getType()))
11988       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11989 
11990     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
11991 
11992     // Unless VerifySCEVStrict is set, we only compare constant deltas.
11993     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
11994       dbgs() << "Trip Count for " << *L << " Changed!\n";
11995       dbgs() << "Old: " << *CurBECount << "\n";
11996       dbgs() << "New: " << *NewBECount << "\n";
11997       dbgs() << "Delta: " << *Delta << "\n";
11998       std::abort();
11999     }
12000   }
12001 }
12002 
12003 bool ScalarEvolution::invalidate(
12004     Function &F, const PreservedAnalyses &PA,
12005     FunctionAnalysisManager::Invalidator &Inv) {
12006   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12007   // of its dependencies is invalidated.
12008   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12009   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12010          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12011          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12012          Inv.invalidate<LoopAnalysis>(F, PA);
12013 }
12014 
12015 AnalysisKey ScalarEvolutionAnalysis::Key;
12016 
12017 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12018                                              FunctionAnalysisManager &AM) {
12019   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12020                          AM.getResult<AssumptionAnalysis>(F),
12021                          AM.getResult<DominatorTreeAnalysis>(F),
12022                          AM.getResult<LoopAnalysis>(F));
12023 }
12024 
12025 PreservedAnalyses
12026 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12027   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12028   return PreservedAnalyses::all();
12029 }
12030 
12031 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12032                       "Scalar Evolution Analysis", false, true)
12033 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12034 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12035 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12036 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12037 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12038                     "Scalar Evolution Analysis", false, true)
12039 
12040 char ScalarEvolutionWrapperPass::ID = 0;
12041 
12042 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12043   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12044 }
12045 
12046 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12047   SE.reset(new ScalarEvolution(
12048       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12049       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12050       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12051       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12052   return false;
12053 }
12054 
12055 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12056 
12057 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12058   SE->print(OS);
12059 }
12060 
12061 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12062   if (!VerifySCEV)
12063     return;
12064 
12065   SE->verify();
12066 }
12067 
12068 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12069   AU.setPreservesAll();
12070   AU.addRequiredTransitive<AssumptionCacheTracker>();
12071   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12072   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12073   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12074 }
12075 
12076 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12077                                                         const SCEV *RHS) {
12078   FoldingSetNodeID ID;
12079   assert(LHS->getType() == RHS->getType() &&
12080          "Type mismatch between LHS and RHS");
12081   // Unique this node based on the arguments
12082   ID.AddInteger(SCEVPredicate::P_Equal);
12083   ID.AddPointer(LHS);
12084   ID.AddPointer(RHS);
12085   void *IP = nullptr;
12086   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12087     return S;
12088   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12089       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12090   UniquePreds.InsertNode(Eq, IP);
12091   return Eq;
12092 }
12093 
12094 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12095     const SCEVAddRecExpr *AR,
12096     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12097   FoldingSetNodeID ID;
12098   // Unique this node based on the arguments
12099   ID.AddInteger(SCEVPredicate::P_Wrap);
12100   ID.AddPointer(AR);
12101   ID.AddInteger(AddedFlags);
12102   void *IP = nullptr;
12103   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12104     return S;
12105   auto *OF = new (SCEVAllocator)
12106       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12107   UniquePreds.InsertNode(OF, IP);
12108   return OF;
12109 }
12110 
12111 namespace {
12112 
12113 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12114 public:
12115 
12116   /// Rewrites \p S in the context of a loop L and the SCEV predication
12117   /// infrastructure.
12118   ///
12119   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12120   /// equivalences present in \p Pred.
12121   ///
12122   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12123   /// \p NewPreds such that the result will be an AddRecExpr.
12124   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12125                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12126                              SCEVUnionPredicate *Pred) {
12127     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12128     return Rewriter.visit(S);
12129   }
12130 
12131   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12132     if (Pred) {
12133       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12134       for (auto *Pred : ExprPreds)
12135         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12136           if (IPred->getLHS() == Expr)
12137             return IPred->getRHS();
12138     }
12139     return convertToAddRecWithPreds(Expr);
12140   }
12141 
12142   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12143     const SCEV *Operand = visit(Expr->getOperand());
12144     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12145     if (AR && AR->getLoop() == L && AR->isAffine()) {
12146       // This couldn't be folded because the operand didn't have the nuw
12147       // flag. Add the nusw flag as an assumption that we could make.
12148       const SCEV *Step = AR->getStepRecurrence(SE);
12149       Type *Ty = Expr->getType();
12150       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12151         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12152                                 SE.getSignExtendExpr(Step, Ty), L,
12153                                 AR->getNoWrapFlags());
12154     }
12155     return SE.getZeroExtendExpr(Operand, Expr->getType());
12156   }
12157 
12158   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12159     const SCEV *Operand = visit(Expr->getOperand());
12160     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12161     if (AR && AR->getLoop() == L && AR->isAffine()) {
12162       // This couldn't be folded because the operand didn't have the nsw
12163       // flag. Add the nssw flag as an assumption that we could make.
12164       const SCEV *Step = AR->getStepRecurrence(SE);
12165       Type *Ty = Expr->getType();
12166       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12167         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12168                                 SE.getSignExtendExpr(Step, Ty), L,
12169                                 AR->getNoWrapFlags());
12170     }
12171     return SE.getSignExtendExpr(Operand, Expr->getType());
12172   }
12173 
12174 private:
12175   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12176                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12177                         SCEVUnionPredicate *Pred)
12178       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12179 
12180   bool addOverflowAssumption(const SCEVPredicate *P) {
12181     if (!NewPreds) {
12182       // Check if we've already made this assumption.
12183       return Pred && Pred->implies(P);
12184     }
12185     NewPreds->insert(P);
12186     return true;
12187   }
12188 
12189   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12190                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12191     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12192     return addOverflowAssumption(A);
12193   }
12194 
12195   // If \p Expr represents a PHINode, we try to see if it can be represented
12196   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12197   // to add this predicate as a runtime overflow check, we return the AddRec.
12198   // If \p Expr does not meet these conditions (is not a PHI node, or we
12199   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12200   // return \p Expr.
12201   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12202     if (!isa<PHINode>(Expr->getValue()))
12203       return Expr;
12204     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12205     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12206     if (!PredicatedRewrite)
12207       return Expr;
12208     for (auto *P : PredicatedRewrite->second){
12209       // Wrap predicates from outer loops are not supported.
12210       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12211         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12212         if (L != AR->getLoop())
12213           return Expr;
12214       }
12215       if (!addOverflowAssumption(P))
12216         return Expr;
12217     }
12218     return PredicatedRewrite->first;
12219   }
12220 
12221   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12222   SCEVUnionPredicate *Pred;
12223   const Loop *L;
12224 };
12225 
12226 } // end anonymous namespace
12227 
12228 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12229                                                    SCEVUnionPredicate &Preds) {
12230   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12231 }
12232 
12233 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12234     const SCEV *S, const Loop *L,
12235     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12236   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12237   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12238   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12239 
12240   if (!AddRec)
12241     return nullptr;
12242 
12243   // Since the transformation was successful, we can now transfer the SCEV
12244   // predicates.
12245   for (auto *P : TransformPreds)
12246     Preds.insert(P);
12247 
12248   return AddRec;
12249 }
12250 
12251 /// SCEV predicates
12252 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12253                              SCEVPredicateKind Kind)
12254     : FastID(ID), Kind(Kind) {}
12255 
12256 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12257                                        const SCEV *LHS, const SCEV *RHS)
12258     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12259   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12260   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12261 }
12262 
12263 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12264   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12265 
12266   if (!Op)
12267     return false;
12268 
12269   return Op->LHS == LHS && Op->RHS == RHS;
12270 }
12271 
12272 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12273 
12274 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12275 
12276 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12277   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12278 }
12279 
12280 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12281                                      const SCEVAddRecExpr *AR,
12282                                      IncrementWrapFlags Flags)
12283     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12284 
12285 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12286 
12287 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12288   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12289 
12290   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12291 }
12292 
12293 bool SCEVWrapPredicate::isAlwaysTrue() const {
12294   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12295   IncrementWrapFlags IFlags = Flags;
12296 
12297   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12298     IFlags = clearFlags(IFlags, IncrementNSSW);
12299 
12300   return IFlags == IncrementAnyWrap;
12301 }
12302 
12303 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12304   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12305   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12306     OS << "<nusw>";
12307   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12308     OS << "<nssw>";
12309   OS << "\n";
12310 }
12311 
12312 SCEVWrapPredicate::IncrementWrapFlags
12313 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12314                                    ScalarEvolution &SE) {
12315   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12316   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12317 
12318   // We can safely transfer the NSW flag as NSSW.
12319   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12320     ImpliedFlags = IncrementNSSW;
12321 
12322   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12323     // If the increment is positive, the SCEV NUW flag will also imply the
12324     // WrapPredicate NUSW flag.
12325     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12326       if (Step->getValue()->getValue().isNonNegative())
12327         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12328   }
12329 
12330   return ImpliedFlags;
12331 }
12332 
12333 /// Union predicates don't get cached so create a dummy set ID for it.
12334 SCEVUnionPredicate::SCEVUnionPredicate()
12335     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12336 
12337 bool SCEVUnionPredicate::isAlwaysTrue() const {
12338   return all_of(Preds,
12339                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12340 }
12341 
12342 ArrayRef<const SCEVPredicate *>
12343 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12344   auto I = SCEVToPreds.find(Expr);
12345   if (I == SCEVToPreds.end())
12346     return ArrayRef<const SCEVPredicate *>();
12347   return I->second;
12348 }
12349 
12350 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12351   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12352     return all_of(Set->Preds,
12353                   [this](const SCEVPredicate *I) { return this->implies(I); });
12354 
12355   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12356   if (ScevPredsIt == SCEVToPreds.end())
12357     return false;
12358   auto &SCEVPreds = ScevPredsIt->second;
12359 
12360   return any_of(SCEVPreds,
12361                 [N](const SCEVPredicate *I) { return I->implies(N); });
12362 }
12363 
12364 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12365 
12366 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12367   for (auto Pred : Preds)
12368     Pred->print(OS, Depth);
12369 }
12370 
12371 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12372   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12373     for (auto Pred : Set->Preds)
12374       add(Pred);
12375     return;
12376   }
12377 
12378   if (implies(N))
12379     return;
12380 
12381   const SCEV *Key = N->getExpr();
12382   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12383                 " associated expression!");
12384 
12385   SCEVToPreds[Key].push_back(N);
12386   Preds.push_back(N);
12387 }
12388 
12389 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12390                                                      Loop &L)
12391     : SE(SE), L(L) {}
12392 
12393 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12394   const SCEV *Expr = SE.getSCEV(V);
12395   RewriteEntry &Entry = RewriteMap[Expr];
12396 
12397   // If we already have an entry and the version matches, return it.
12398   if (Entry.second && Generation == Entry.first)
12399     return Entry.second;
12400 
12401   // We found an entry but it's stale. Rewrite the stale entry
12402   // according to the current predicate.
12403   if (Entry.second)
12404     Expr = Entry.second;
12405 
12406   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12407   Entry = {Generation, NewSCEV};
12408 
12409   return NewSCEV;
12410 }
12411 
12412 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12413   if (!BackedgeCount) {
12414     SCEVUnionPredicate BackedgePred;
12415     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12416     addPredicate(BackedgePred);
12417   }
12418   return BackedgeCount;
12419 }
12420 
12421 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12422   if (Preds.implies(&Pred))
12423     return;
12424   Preds.add(&Pred);
12425   updateGeneration();
12426 }
12427 
12428 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12429   return Preds;
12430 }
12431 
12432 void PredicatedScalarEvolution::updateGeneration() {
12433   // If the generation number wrapped recompute everything.
12434   if (++Generation == 0) {
12435     for (auto &II : RewriteMap) {
12436       const SCEV *Rewritten = II.second.second;
12437       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12438     }
12439   }
12440 }
12441 
12442 void PredicatedScalarEvolution::setNoOverflow(
12443     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12444   const SCEV *Expr = getSCEV(V);
12445   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12446 
12447   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12448 
12449   // Clear the statically implied flags.
12450   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12451   addPredicate(*SE.getWrapPredicate(AR, Flags));
12452 
12453   auto II = FlagsMap.insert({V, Flags});
12454   if (!II.second)
12455     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12456 }
12457 
12458 bool PredicatedScalarEvolution::hasNoOverflow(
12459     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12460   const SCEV *Expr = getSCEV(V);
12461   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12462 
12463   Flags = SCEVWrapPredicate::clearFlags(
12464       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12465 
12466   auto II = FlagsMap.find(V);
12467 
12468   if (II != FlagsMap.end())
12469     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12470 
12471   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12472 }
12473 
12474 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12475   const SCEV *Expr = this->getSCEV(V);
12476   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12477   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12478 
12479   if (!New)
12480     return nullptr;
12481 
12482   for (auto *P : NewPreds)
12483     Preds.add(P);
12484 
12485   updateGeneration();
12486   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12487   return New;
12488 }
12489 
12490 PredicatedScalarEvolution::PredicatedScalarEvolution(
12491     const PredicatedScalarEvolution &Init)
12492     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12493       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12494   for (const auto &I : Init.FlagsMap)
12495     FlagsMap.insert(I);
12496 }
12497 
12498 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12499   // For each block.
12500   for (auto *BB : L.getBlocks())
12501     for (auto &I : *BB) {
12502       if (!SE.isSCEVable(I.getType()))
12503         continue;
12504 
12505       auto *Expr = SE.getSCEV(&I);
12506       auto II = RewriteMap.find(Expr);
12507 
12508       if (II == RewriteMap.end())
12509         continue;
12510 
12511       // Don't print things that are not interesting.
12512       if (II->second.second == Expr)
12513         continue;
12514 
12515       OS.indent(Depth) << "[PSE]" << I << ":\n";
12516       OS.indent(Depth + 2) << *Expr << "\n";
12517       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12518     }
12519 }
12520 
12521 // Match the mathematical pattern A - (A / B) * B, where A and B can be
12522 // arbitrary expressions.
12523 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12524 // 4, A / B becomes X / 8).
12525 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
12526                                 const SCEV *&RHS) {
12527   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
12528   if (Add == nullptr || Add->getNumOperands() != 2)
12529     return false;
12530 
12531   const SCEV *A = Add->getOperand(1);
12532   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
12533 
12534   if (Mul == nullptr)
12535     return false;
12536 
12537   const auto MatchURemWithDivisor = [&](const SCEV *B) {
12538     // (SomeExpr + (-(SomeExpr / B) * B)).
12539     if (Expr == getURemExpr(A, B)) {
12540       LHS = A;
12541       RHS = B;
12542       return true;
12543     }
12544     return false;
12545   };
12546 
12547   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12548   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12549     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12550            MatchURemWithDivisor(Mul->getOperand(2));
12551 
12552   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12553   if (Mul->getNumOperands() == 2)
12554     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12555            MatchURemWithDivisor(Mul->getOperand(0)) ||
12556            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12557            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
12558   return false;
12559 }
12560