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/ScalarEvolutionDivision.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/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 static cl::opt<bool>
225 ClassifyExpressions("scalar-evolution-classify-expressions",
226     cl::Hidden, cl::init(true),
227     cl::desc("When printing analysis, include information on every instruction"));
228 
229 static cl::opt<bool> UseExpensiveRangeSharpening(
230     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
231     cl::init(false),
232     cl::desc("Use more powerful methods of sharpening expression ranges. May "
233              "be costly in terms of compile time"));
234 
235 //===----------------------------------------------------------------------===//
236 //                           SCEV class definitions
237 //===----------------------------------------------------------------------===//
238 
239 //===----------------------------------------------------------------------===//
240 // Implementation of the SCEV class.
241 //
242 
243 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
244 LLVM_DUMP_METHOD void SCEV::dump() const {
245   print(dbgs());
246   dbgs() << '\n';
247 }
248 #endif
249 
250 void SCEV::print(raw_ostream &OS) const {
251   switch (getSCEVType()) {
252   case scConstant:
253     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
254     return;
255   case scPtrToInt: {
256     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
257     const SCEV *Op = PtrToInt->getOperand();
258     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
259        << *PtrToInt->getType() << ")";
260     return;
261   }
262   case scTruncate: {
263     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
264     const SCEV *Op = Trunc->getOperand();
265     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
266        << *Trunc->getType() << ")";
267     return;
268   }
269   case scZeroExtend: {
270     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
271     const SCEV *Op = ZExt->getOperand();
272     OS << "(zext " << *Op->getType() << " " << *Op << " to "
273        << *ZExt->getType() << ")";
274     return;
275   }
276   case scSignExtend: {
277     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
278     const SCEV *Op = SExt->getOperand();
279     OS << "(sext " << *Op->getType() << " " << *Op << " to "
280        << *SExt->getType() << ")";
281     return;
282   }
283   case scAddRecExpr: {
284     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
285     OS << "{" << *AR->getOperand(0);
286     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
287       OS << ",+," << *AR->getOperand(i);
288     OS << "}<";
289     if (AR->hasNoUnsignedWrap())
290       OS << "nuw><";
291     if (AR->hasNoSignedWrap())
292       OS << "nsw><";
293     if (AR->hasNoSelfWrap() &&
294         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
295       OS << "nw><";
296     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
297     OS << ">";
298     return;
299   }
300   case scAddExpr:
301   case scMulExpr:
302   case scUMaxExpr:
303   case scSMaxExpr:
304   case scUMinExpr:
305   case scSMinExpr: {
306     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
307     const char *OpStr = nullptr;
308     switch (NAry->getSCEVType()) {
309     case scAddExpr: OpStr = " + "; break;
310     case scMulExpr: OpStr = " * "; break;
311     case scUMaxExpr: OpStr = " umax "; break;
312     case scSMaxExpr: OpStr = " smax "; break;
313     case scUMinExpr:
314       OpStr = " umin ";
315       break;
316     case scSMinExpr:
317       OpStr = " smin ";
318       break;
319     default:
320       llvm_unreachable("There are no other nary expression types.");
321     }
322     OS << "(";
323     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
324          I != E; ++I) {
325       OS << **I;
326       if (std::next(I) != E)
327         OS << OpStr;
328     }
329     OS << ")";
330     switch (NAry->getSCEVType()) {
331     case scAddExpr:
332     case scMulExpr:
333       if (NAry->hasNoUnsignedWrap())
334         OS << "<nuw>";
335       if (NAry->hasNoSignedWrap())
336         OS << "<nsw>";
337       break;
338     default:
339       // Nothing to print for other nary expressions.
340       break;
341     }
342     return;
343   }
344   case scUDivExpr: {
345     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
346     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
347     return;
348   }
349   case scUnknown: {
350     const SCEVUnknown *U = cast<SCEVUnknown>(this);
351     Type *AllocTy;
352     if (U->isSizeOf(AllocTy)) {
353       OS << "sizeof(" << *AllocTy << ")";
354       return;
355     }
356     if (U->isAlignOf(AllocTy)) {
357       OS << "alignof(" << *AllocTy << ")";
358       return;
359     }
360 
361     Type *CTy;
362     Constant *FieldNo;
363     if (U->isOffsetOf(CTy, FieldNo)) {
364       OS << "offsetof(" << *CTy << ", ";
365       FieldNo->printAsOperand(OS, false);
366       OS << ")";
367       return;
368     }
369 
370     // Otherwise just print it normally.
371     U->getValue()->printAsOperand(OS, false);
372     return;
373   }
374   case scCouldNotCompute:
375     OS << "***COULDNOTCOMPUTE***";
376     return;
377   }
378   llvm_unreachable("Unknown SCEV kind!");
379 }
380 
381 Type *SCEV::getType() const {
382   switch (getSCEVType()) {
383   case scConstant:
384     return cast<SCEVConstant>(this)->getType();
385   case scPtrToInt:
386   case scTruncate:
387   case scZeroExtend:
388   case scSignExtend:
389     return cast<SCEVCastExpr>(this)->getType();
390   case scAddRecExpr:
391   case scMulExpr:
392   case scUMaxExpr:
393   case scSMaxExpr:
394   case scUMinExpr:
395   case scSMinExpr:
396     return cast<SCEVNAryExpr>(this)->getType();
397   case scAddExpr:
398     return cast<SCEVAddExpr>(this)->getType();
399   case scUDivExpr:
400     return cast<SCEVUDivExpr>(this)->getType();
401   case scUnknown:
402     return cast<SCEVUnknown>(this)->getType();
403   case scCouldNotCompute:
404     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
405   }
406   llvm_unreachable("Unknown SCEV kind!");
407 }
408 
409 bool SCEV::isZero() const {
410   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
411     return SC->getValue()->isZero();
412   return false;
413 }
414 
415 bool SCEV::isOne() const {
416   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
417     return SC->getValue()->isOne();
418   return false;
419 }
420 
421 bool SCEV::isAllOnesValue() const {
422   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
423     return SC->getValue()->isMinusOne();
424   return false;
425 }
426 
427 bool SCEV::isNonConstantNegative() const {
428   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
429   if (!Mul) return false;
430 
431   // If there is a constant factor, it will be first.
432   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
433   if (!SC) return false;
434 
435   // Return true if the value is negative, this matches things like (-42 * V).
436   return SC->getAPInt().isNegative();
437 }
438 
439 SCEVCouldNotCompute::SCEVCouldNotCompute() :
440   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
441 
442 bool SCEVCouldNotCompute::classof(const SCEV *S) {
443   return S->getSCEVType() == scCouldNotCompute;
444 }
445 
446 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
447   FoldingSetNodeID ID;
448   ID.AddInteger(scConstant);
449   ID.AddPointer(V);
450   void *IP = nullptr;
451   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
452   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
453   UniqueSCEVs.InsertNode(S, IP);
454   return S;
455 }
456 
457 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
458   return getConstant(ConstantInt::get(getContext(), Val));
459 }
460 
461 const SCEV *
462 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
463   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
464   return getConstant(ConstantInt::get(ITy, V, isSigned));
465 }
466 
467 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
468                            const SCEV *op, Type *ty)
469     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
470   Operands[0] = op;
471 }
472 
473 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
474                                    Type *ITy)
475     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
476   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
477          "Must be a non-bit-width-changing pointer-to-integer cast!");
478 }
479 
480 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
481                                            SCEVTypes SCEVTy, const SCEV *op,
482                                            Type *ty)
483     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
484 
485 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
486                                    Type *ty)
487     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
488   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
489          "Cannot truncate non-integer value!");
490 }
491 
492 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
493                                        const SCEV *op, Type *ty)
494     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
495   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
496          "Cannot zero extend non-integer value!");
497 }
498 
499 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
500                                        const SCEV *op, Type *ty)
501     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
502   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
503          "Cannot sign extend non-integer value!");
504 }
505 
506 void SCEVUnknown::deleted() {
507   // Clear this SCEVUnknown from various maps.
508   SE->forgetMemoizedResults(this);
509 
510   // Remove this SCEVUnknown from the uniquing map.
511   SE->UniqueSCEVs.RemoveNode(this);
512 
513   // Release the value.
514   setValPtr(nullptr);
515 }
516 
517 void SCEVUnknown::allUsesReplacedWith(Value *New) {
518   // Remove this SCEVUnknown from the uniquing map.
519   SE->UniqueSCEVs.RemoveNode(this);
520 
521   // Update this SCEVUnknown to point to the new value. This is needed
522   // because there may still be outstanding SCEVs which still point to
523   // this SCEVUnknown.
524   setValPtr(New);
525 }
526 
527 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
528   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
529     if (VCE->getOpcode() == Instruction::PtrToInt)
530       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
531         if (CE->getOpcode() == Instruction::GetElementPtr &&
532             CE->getOperand(0)->isNullValue() &&
533             CE->getNumOperands() == 2)
534           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
535             if (CI->isOne()) {
536               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
537                                  ->getElementType();
538               return true;
539             }
540 
541   return false;
542 }
543 
544 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
545   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
546     if (VCE->getOpcode() == Instruction::PtrToInt)
547       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
548         if (CE->getOpcode() == Instruction::GetElementPtr &&
549             CE->getOperand(0)->isNullValue()) {
550           Type *Ty =
551             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
552           if (StructType *STy = dyn_cast<StructType>(Ty))
553             if (!STy->isPacked() &&
554                 CE->getNumOperands() == 3 &&
555                 CE->getOperand(1)->isNullValue()) {
556               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
557                 if (CI->isOne() &&
558                     STy->getNumElements() == 2 &&
559                     STy->getElementType(0)->isIntegerTy(1)) {
560                   AllocTy = STy->getElementType(1);
561                   return true;
562                 }
563             }
564         }
565 
566   return false;
567 }
568 
569 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
570   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
571     if (VCE->getOpcode() == Instruction::PtrToInt)
572       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
573         if (CE->getOpcode() == Instruction::GetElementPtr &&
574             CE->getNumOperands() == 3 &&
575             CE->getOperand(0)->isNullValue() &&
576             CE->getOperand(1)->isNullValue()) {
577           Type *Ty =
578             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
579           // Ignore vector types here so that ScalarEvolutionExpander doesn't
580           // emit getelementptrs that index into vectors.
581           if (Ty->isStructTy() || Ty->isArrayTy()) {
582             CTy = Ty;
583             FieldNo = CE->getOperand(2);
584             return true;
585           }
586         }
587 
588   return false;
589 }
590 
591 //===----------------------------------------------------------------------===//
592 //                               SCEV Utilities
593 //===----------------------------------------------------------------------===//
594 
595 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
596 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
597 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
598 /// have been previously deemed to be "equally complex" by this routine.  It is
599 /// intended to avoid exponential time complexity in cases like:
600 ///
601 ///   %a = f(%x, %y)
602 ///   %b = f(%a, %a)
603 ///   %c = f(%b, %b)
604 ///
605 ///   %d = f(%x, %y)
606 ///   %e = f(%d, %d)
607 ///   %f = f(%e, %e)
608 ///
609 ///   CompareValueComplexity(%f, %c)
610 ///
611 /// Since we do not continue running this routine on expression trees once we
612 /// have seen unequal values, there is no need to track them in the cache.
613 static int
614 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
615                        const LoopInfo *const LI, Value *LV, Value *RV,
616                        unsigned Depth) {
617   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
618     return 0;
619 
620   // Order pointer values after integer values. This helps SCEVExpander form
621   // GEPs.
622   bool LIsPointer = LV->getType()->isPointerTy(),
623        RIsPointer = RV->getType()->isPointerTy();
624   if (LIsPointer != RIsPointer)
625     return (int)LIsPointer - (int)RIsPointer;
626 
627   // Compare getValueID values.
628   unsigned LID = LV->getValueID(), RID = RV->getValueID();
629   if (LID != RID)
630     return (int)LID - (int)RID;
631 
632   // Sort arguments by their position.
633   if (const auto *LA = dyn_cast<Argument>(LV)) {
634     const auto *RA = cast<Argument>(RV);
635     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
636     return (int)LArgNo - (int)RArgNo;
637   }
638 
639   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
640     const auto *RGV = cast<GlobalValue>(RV);
641 
642     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
643       auto LT = GV->getLinkage();
644       return !(GlobalValue::isPrivateLinkage(LT) ||
645                GlobalValue::isInternalLinkage(LT));
646     };
647 
648     // Use the names to distinguish the two values, but only if the
649     // names are semantically important.
650     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
651       return LGV->getName().compare(RGV->getName());
652   }
653 
654   // For instructions, compare their loop depth, and their operand count.  This
655   // is pretty loose.
656   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
657     const auto *RInst = cast<Instruction>(RV);
658 
659     // Compare loop depths.
660     const BasicBlock *LParent = LInst->getParent(),
661                      *RParent = RInst->getParent();
662     if (LParent != RParent) {
663       unsigned LDepth = LI->getLoopDepth(LParent),
664                RDepth = LI->getLoopDepth(RParent);
665       if (LDepth != RDepth)
666         return (int)LDepth - (int)RDepth;
667     }
668 
669     // Compare the number of operands.
670     unsigned LNumOps = LInst->getNumOperands(),
671              RNumOps = RInst->getNumOperands();
672     if (LNumOps != RNumOps)
673       return (int)LNumOps - (int)RNumOps;
674 
675     for (unsigned Idx : seq(0u, LNumOps)) {
676       int Result =
677           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
678                                  RInst->getOperand(Idx), Depth + 1);
679       if (Result != 0)
680         return Result;
681     }
682   }
683 
684   EqCacheValue.unionSets(LV, RV);
685   return 0;
686 }
687 
688 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
689 // than RHS, respectively. A three-way result allows recursive comparisons to be
690 // more efficient.
691 static int CompareSCEVComplexity(
692     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
693     EquivalenceClasses<const Value *> &EqCacheValue,
694     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
695     DominatorTree &DT, unsigned Depth = 0) {
696   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
697   if (LHS == RHS)
698     return 0;
699 
700   // Primarily, sort the SCEVs by their getSCEVType().
701   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
702   if (LType != RType)
703     return (int)LType - (int)RType;
704 
705   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
706     return 0;
707   // Aside from the getSCEVType() ordering, the particular ordering
708   // isn't very important except that it's beneficial to be consistent,
709   // so that (a + b) and (b + a) don't end up as different expressions.
710   switch (LType) {
711   case scUnknown: {
712     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
713     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
714 
715     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
716                                    RU->getValue(), Depth + 1);
717     if (X == 0)
718       EqCacheSCEV.unionSets(LHS, RHS);
719     return X;
720   }
721 
722   case scConstant: {
723     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
724     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
725 
726     // Compare constant values.
727     const APInt &LA = LC->getAPInt();
728     const APInt &RA = RC->getAPInt();
729     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
730     if (LBitWidth != RBitWidth)
731       return (int)LBitWidth - (int)RBitWidth;
732     return LA.ult(RA) ? -1 : 1;
733   }
734 
735   case scAddRecExpr: {
736     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
737     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
738 
739     // There is always a dominance between two recs that are used by one SCEV,
740     // so we can safely sort recs by loop header dominance. We require such
741     // order in getAddExpr.
742     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
743     if (LLoop != RLoop) {
744       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
745       assert(LHead != RHead && "Two loops share the same header?");
746       if (DT.dominates(LHead, RHead))
747         return 1;
748       else
749         assert(DT.dominates(RHead, LHead) &&
750                "No dominance between recurrences used by one SCEV?");
751       return -1;
752     }
753 
754     // Addrec complexity grows with operand count.
755     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
756     if (LNumOps != RNumOps)
757       return (int)LNumOps - (int)RNumOps;
758 
759     // Lexicographically compare.
760     for (unsigned i = 0; i != LNumOps; ++i) {
761       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
762                                     LA->getOperand(i), RA->getOperand(i), DT,
763                                     Depth + 1);
764       if (X != 0)
765         return X;
766     }
767     EqCacheSCEV.unionSets(LHS, RHS);
768     return 0;
769   }
770 
771   case scAddExpr:
772   case scMulExpr:
773   case scSMaxExpr:
774   case scUMaxExpr:
775   case scSMinExpr:
776   case scUMinExpr: {
777     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
778     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
779 
780     // Lexicographically compare n-ary expressions.
781     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
782     if (LNumOps != RNumOps)
783       return (int)LNumOps - (int)RNumOps;
784 
785     for (unsigned i = 0; i != LNumOps; ++i) {
786       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
787                                     LC->getOperand(i), RC->getOperand(i), DT,
788                                     Depth + 1);
789       if (X != 0)
790         return X;
791     }
792     EqCacheSCEV.unionSets(LHS, RHS);
793     return 0;
794   }
795 
796   case scUDivExpr: {
797     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
798     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
799 
800     // Lexicographically compare udiv expressions.
801     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
802                                   RC->getLHS(), DT, Depth + 1);
803     if (X != 0)
804       return X;
805     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
806                               RC->getRHS(), DT, Depth + 1);
807     if (X == 0)
808       EqCacheSCEV.unionSets(LHS, RHS);
809     return X;
810   }
811 
812   case scPtrToInt:
813   case scTruncate:
814   case scZeroExtend:
815   case scSignExtend: {
816     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
817     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
818 
819     // Compare cast expressions by operand.
820     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
821                                   LC->getOperand(), RC->getOperand(), DT,
822                                   Depth + 1);
823     if (X == 0)
824       EqCacheSCEV.unionSets(LHS, RHS);
825     return X;
826   }
827 
828   case scCouldNotCompute:
829     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
830   }
831   llvm_unreachable("Unknown SCEV kind!");
832 }
833 
834 /// Given a list of SCEV objects, order them by their complexity, and group
835 /// objects of the same complexity together by value.  When this routine is
836 /// finished, we know that any duplicates in the vector are consecutive and that
837 /// complexity is monotonically increasing.
838 ///
839 /// Note that we go take special precautions to ensure that we get deterministic
840 /// results from this routine.  In other words, we don't want the results of
841 /// this to depend on where the addresses of various SCEV objects happened to
842 /// land in memory.
843 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
844                               LoopInfo *LI, DominatorTree &DT) {
845   if (Ops.size() < 2) return;  // Noop
846 
847   EquivalenceClasses<const SCEV *> EqCacheSCEV;
848   EquivalenceClasses<const Value *> EqCacheValue;
849   if (Ops.size() == 2) {
850     // This is the common case, which also happens to be trivially simple.
851     // Special case it.
852     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
853     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
854       std::swap(LHS, RHS);
855     return;
856   }
857 
858   // Do the rough sort by complexity.
859   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
860     return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
861            0;
862   });
863 
864   // Now that we are sorted by complexity, group elements of the same
865   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
866   // be extremely short in practice.  Note that we take this approach because we
867   // do not want to depend on the addresses of the objects we are grouping.
868   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
869     const SCEV *S = Ops[i];
870     unsigned Complexity = S->getSCEVType();
871 
872     // If there are any objects of the same complexity and same value as this
873     // one, group them.
874     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
875       if (Ops[j] == S) { // Found a duplicate.
876         // Move it to immediately after i'th element.
877         std::swap(Ops[i+1], Ops[j]);
878         ++i;   // no need to rescan it.
879         if (i == e-2) return;  // Done!
880       }
881     }
882   }
883 }
884 
885 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
886 /// least HugeExprThreshold nodes).
887 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
888   return any_of(Ops, [](const SCEV *S) {
889     return S->getExpressionSize() >= HugeExprThreshold;
890   });
891 }
892 
893 //===----------------------------------------------------------------------===//
894 //                      Simple SCEV method implementations
895 //===----------------------------------------------------------------------===//
896 
897 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
898 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
899                                        ScalarEvolution &SE,
900                                        Type *ResultTy) {
901   // Handle the simplest case efficiently.
902   if (K == 1)
903     return SE.getTruncateOrZeroExtend(It, ResultTy);
904 
905   // We are using the following formula for BC(It, K):
906   //
907   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
908   //
909   // Suppose, W is the bitwidth of the return value.  We must be prepared for
910   // overflow.  Hence, we must assure that the result of our computation is
911   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
912   // safe in modular arithmetic.
913   //
914   // However, this code doesn't use exactly that formula; the formula it uses
915   // is something like the following, where T is the number of factors of 2 in
916   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
917   // exponentiation:
918   //
919   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
920   //
921   // This formula is trivially equivalent to the previous formula.  However,
922   // this formula can be implemented much more efficiently.  The trick is that
923   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
924   // arithmetic.  To do exact division in modular arithmetic, all we have
925   // to do is multiply by the inverse.  Therefore, this step can be done at
926   // width W.
927   //
928   // The next issue is how to safely do the division by 2^T.  The way this
929   // is done is by doing the multiplication step at a width of at least W + T
930   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
931   // when we perform the division by 2^T (which is equivalent to a right shift
932   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
933   // truncated out after the division by 2^T.
934   //
935   // In comparison to just directly using the first formula, this technique
936   // is much more efficient; using the first formula requires W * K bits,
937   // but this formula less than W + K bits. Also, the first formula requires
938   // a division step, whereas this formula only requires multiplies and shifts.
939   //
940   // It doesn't matter whether the subtraction step is done in the calculation
941   // width or the input iteration count's width; if the subtraction overflows,
942   // the result must be zero anyway.  We prefer here to do it in the width of
943   // the induction variable because it helps a lot for certain cases; CodeGen
944   // isn't smart enough to ignore the overflow, which leads to much less
945   // efficient code if the width of the subtraction is wider than the native
946   // register width.
947   //
948   // (It's possible to not widen at all by pulling out factors of 2 before
949   // the multiplication; for example, K=2 can be calculated as
950   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
951   // extra arithmetic, so it's not an obvious win, and it gets
952   // much more complicated for K > 3.)
953 
954   // Protection from insane SCEVs; this bound is conservative,
955   // but it probably doesn't matter.
956   if (K > 1000)
957     return SE.getCouldNotCompute();
958 
959   unsigned W = SE.getTypeSizeInBits(ResultTy);
960 
961   // Calculate K! / 2^T and T; we divide out the factors of two before
962   // multiplying for calculating K! / 2^T to avoid overflow.
963   // Other overflow doesn't matter because we only care about the bottom
964   // W bits of the result.
965   APInt OddFactorial(W, 1);
966   unsigned T = 1;
967   for (unsigned i = 3; i <= K; ++i) {
968     APInt Mult(W, i);
969     unsigned TwoFactors = Mult.countTrailingZeros();
970     T += TwoFactors;
971     Mult.lshrInPlace(TwoFactors);
972     OddFactorial *= Mult;
973   }
974 
975   // We need at least W + T bits for the multiplication step
976   unsigned CalculationBits = W + T;
977 
978   // Calculate 2^T, at width T+W.
979   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
980 
981   // Calculate the multiplicative inverse of K! / 2^T;
982   // this multiplication factor will perform the exact division by
983   // K! / 2^T.
984   APInt Mod = APInt::getSignedMinValue(W+1);
985   APInt MultiplyFactor = OddFactorial.zext(W+1);
986   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
987   MultiplyFactor = MultiplyFactor.trunc(W);
988 
989   // Calculate the product, at width T+W
990   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
991                                                       CalculationBits);
992   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
993   for (unsigned i = 1; i != K; ++i) {
994     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
995     Dividend = SE.getMulExpr(Dividend,
996                              SE.getTruncateOrZeroExtend(S, CalculationTy));
997   }
998 
999   // Divide by 2^T
1000   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1001 
1002   // Truncate the result, and divide by K! / 2^T.
1003 
1004   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1005                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1006 }
1007 
1008 /// Return the value of this chain of recurrences at the specified iteration
1009 /// number.  We can evaluate this recurrence by multiplying each element in the
1010 /// chain by the binomial coefficient corresponding to it.  In other words, we
1011 /// can evaluate {A,+,B,+,C,+,D} as:
1012 ///
1013 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1014 ///
1015 /// where BC(It, k) stands for binomial coefficient.
1016 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1017                                                 ScalarEvolution &SE) const {
1018   const SCEV *Result = getStart();
1019   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1020     // The computation is correct in the face of overflow provided that the
1021     // multiplication is performed _after_ the evaluation of the binomial
1022     // coefficient.
1023     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1024     if (isa<SCEVCouldNotCompute>(Coeff))
1025       return Coeff;
1026 
1027     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1028   }
1029   return Result;
1030 }
1031 
1032 //===----------------------------------------------------------------------===//
1033 //                    SCEV Expression folder implementations
1034 //===----------------------------------------------------------------------===//
1035 
1036 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty,
1037                                              unsigned Depth) {
1038   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1039   assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once.");
1040 
1041   // We could be called with an integer-typed operands during SCEV rewrites.
1042   // Since the operand is an integer already, just perform zext/trunc/self cast.
1043   if (!Op->getType()->isPointerTy())
1044     return getTruncateOrZeroExtend(Op, Ty);
1045 
1046   // What would be an ID for such a SCEV cast expression?
1047   FoldingSetNodeID ID;
1048   ID.AddInteger(scPtrToInt);
1049   ID.AddPointer(Op);
1050 
1051   void *IP = nullptr;
1052 
1053   // Is there already an expression for such a cast?
1054   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1055     return getTruncateOrZeroExtend(S, Ty);
1056 
1057   // If not, is this expression something we can't reduce any further?
1058   if (isa<SCEVUnknown>(Op)) {
1059     // Create an explicit cast node.
1060     // We can reuse the existing insert position since if we get here,
1061     // we won't have made any changes which would invalidate it.
1062     Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1063     assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(
1064                Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
1065            "We can only model ptrtoint if SCEV's effective (integer) type is "
1066            "sufficiently wide to represent all possible pointer values.");
1067     SCEV *S = new (SCEVAllocator)
1068         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1069     UniqueSCEVs.InsertNode(S, IP);
1070     addToLoopUseLists(S);
1071     return getTruncateOrZeroExtend(S, Ty);
1072   }
1073 
1074   assert(Depth == 0 &&
1075          "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.");
1076 
1077   // Otherwise, we've got some expression that is more complex than just a
1078   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1079   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1080   // only, and the expressions must otherwise be integer-typed.
1081   // So sink the cast down to the SCEVUnknown's.
1082 
1083   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1084   /// which computes a pointer-typed value, and rewrites the whole expression
1085   /// tree so that *all* the computations are done on integers, and the only
1086   /// pointer-typed operands in the expression are SCEVUnknown.
1087   class SCEVPtrToIntSinkingRewriter
1088       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1089     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1090 
1091   public:
1092     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1093 
1094     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1095       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1096       return Rewriter.visit(Scev);
1097     }
1098 
1099     const SCEV *visit(const SCEV *S) {
1100       Type *STy = S->getType();
1101       // If the expression is not pointer-typed, just keep it as-is.
1102       if (!STy->isPointerTy())
1103         return S;
1104       // Else, recursively sink the cast down into it.
1105       return Base::visit(S);
1106     }
1107 
1108     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1109       SmallVector<const SCEV *, 2> Operands;
1110       bool Changed = false;
1111       for (auto *Op : Expr->operands()) {
1112         Operands.push_back(visit(Op));
1113         Changed |= Op != Operands.back();
1114       }
1115       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1116     }
1117 
1118     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1119       SmallVector<const SCEV *, 2> Operands;
1120       bool Changed = false;
1121       for (auto *Op : Expr->operands()) {
1122         Operands.push_back(visit(Op));
1123         Changed |= Op != Operands.back();
1124       }
1125       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1126     }
1127 
1128     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1129       Type *ExprPtrTy = Expr->getType();
1130       assert(ExprPtrTy->isPointerTy() &&
1131              "Should only reach pointer-typed SCEVUnknown's.");
1132       Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy);
1133       return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1);
1134     }
1135   };
1136 
1137   // And actually perform the cast sinking.
1138   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1139   assert(IntOp->getType()->isIntegerTy() &&
1140          "We must have succeeded in sinking the cast, "
1141          "and ending up with an integer-typed expression!");
1142   return getTruncateOrZeroExtend(IntOp, Ty);
1143 }
1144 
1145 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1146                                              unsigned Depth) {
1147   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1148          "This is not a truncating conversion!");
1149   assert(isSCEVable(Ty) &&
1150          "This is not a conversion to a SCEVable type!");
1151   Ty = getEffectiveSCEVType(Ty);
1152 
1153   FoldingSetNodeID ID;
1154   ID.AddInteger(scTruncate);
1155   ID.AddPointer(Op);
1156   ID.AddPointer(Ty);
1157   void *IP = nullptr;
1158   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1159 
1160   // Fold if the operand is constant.
1161   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1162     return getConstant(
1163       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1164 
1165   // trunc(trunc(x)) --> trunc(x)
1166   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1167     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1168 
1169   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1170   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1171     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1172 
1173   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1174   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1175     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1176 
1177   if (Depth > MaxCastDepth) {
1178     SCEV *S =
1179         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1180     UniqueSCEVs.InsertNode(S, IP);
1181     addToLoopUseLists(S);
1182     return S;
1183   }
1184 
1185   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1186   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1187   // if after transforming we have at most one truncate, not counting truncates
1188   // that replace other casts.
1189   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1190     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1191     SmallVector<const SCEV *, 4> Operands;
1192     unsigned numTruncs = 0;
1193     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1194          ++i) {
1195       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1196       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1197           isa<SCEVTruncateExpr>(S))
1198         numTruncs++;
1199       Operands.push_back(S);
1200     }
1201     if (numTruncs < 2) {
1202       if (isa<SCEVAddExpr>(Op))
1203         return getAddExpr(Operands);
1204       else if (isa<SCEVMulExpr>(Op))
1205         return getMulExpr(Operands);
1206       else
1207         llvm_unreachable("Unexpected SCEV type for Op.");
1208     }
1209     // Although we checked in the beginning that ID is not in the cache, it is
1210     // possible that during recursion and different modification ID was inserted
1211     // into the cache. So if we find it, just return it.
1212     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1213       return S;
1214   }
1215 
1216   // If the input value is a chrec scev, truncate the chrec's operands.
1217   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1218     SmallVector<const SCEV *, 4> Operands;
1219     for (const SCEV *Op : AddRec->operands())
1220       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1221     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1222   }
1223 
1224   // The cast wasn't folded; create an explicit cast node. We can reuse
1225   // the existing insert position since if we get here, we won't have
1226   // made any changes which would invalidate it.
1227   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1228                                                  Op, Ty);
1229   UniqueSCEVs.InsertNode(S, IP);
1230   addToLoopUseLists(S);
1231   return S;
1232 }
1233 
1234 // Get the limit of a recurrence such that incrementing by Step cannot cause
1235 // signed overflow as long as the value of the recurrence within the
1236 // loop does not exceed this limit before incrementing.
1237 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1238                                                  ICmpInst::Predicate *Pred,
1239                                                  ScalarEvolution *SE) {
1240   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1241   if (SE->isKnownPositive(Step)) {
1242     *Pred = ICmpInst::ICMP_SLT;
1243     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1244                            SE->getSignedRangeMax(Step));
1245   }
1246   if (SE->isKnownNegative(Step)) {
1247     *Pred = ICmpInst::ICMP_SGT;
1248     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1249                            SE->getSignedRangeMin(Step));
1250   }
1251   return nullptr;
1252 }
1253 
1254 // Get the limit of a recurrence such that incrementing by Step cannot cause
1255 // unsigned overflow as long as the value of the recurrence within the loop does
1256 // not exceed this limit before incrementing.
1257 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1258                                                    ICmpInst::Predicate *Pred,
1259                                                    ScalarEvolution *SE) {
1260   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1261   *Pred = ICmpInst::ICMP_ULT;
1262 
1263   return SE->getConstant(APInt::getMinValue(BitWidth) -
1264                          SE->getUnsignedRangeMax(Step));
1265 }
1266 
1267 namespace {
1268 
1269 struct ExtendOpTraitsBase {
1270   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1271                                                           unsigned);
1272 };
1273 
1274 // Used to make code generic over signed and unsigned overflow.
1275 template <typename ExtendOp> struct ExtendOpTraits {
1276   // Members present:
1277   //
1278   // static const SCEV::NoWrapFlags WrapType;
1279   //
1280   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1281   //
1282   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1283   //                                           ICmpInst::Predicate *Pred,
1284   //                                           ScalarEvolution *SE);
1285 };
1286 
1287 template <>
1288 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1289   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1290 
1291   static const GetExtendExprTy GetExtendExpr;
1292 
1293   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1294                                              ICmpInst::Predicate *Pred,
1295                                              ScalarEvolution *SE) {
1296     return getSignedOverflowLimitForStep(Step, Pred, SE);
1297   }
1298 };
1299 
1300 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1301     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1302 
1303 template <>
1304 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1305   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1306 
1307   static const GetExtendExprTy GetExtendExpr;
1308 
1309   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1310                                              ICmpInst::Predicate *Pred,
1311                                              ScalarEvolution *SE) {
1312     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1313   }
1314 };
1315 
1316 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1317     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1318 
1319 } // end anonymous namespace
1320 
1321 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1322 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1323 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1324 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1325 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1326 // expression "Step + sext/zext(PreIncAR)" is congruent with
1327 // "sext/zext(PostIncAR)"
1328 template <typename ExtendOpTy>
1329 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1330                                         ScalarEvolution *SE, unsigned Depth) {
1331   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1332   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1333 
1334   const Loop *L = AR->getLoop();
1335   const SCEV *Start = AR->getStart();
1336   const SCEV *Step = AR->getStepRecurrence(*SE);
1337 
1338   // Check for a simple looking step prior to loop entry.
1339   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1340   if (!SA)
1341     return nullptr;
1342 
1343   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1344   // subtraction is expensive. For this purpose, perform a quick and dirty
1345   // difference, by checking for Step in the operand list.
1346   SmallVector<const SCEV *, 4> DiffOps;
1347   for (const SCEV *Op : SA->operands())
1348     if (Op != Step)
1349       DiffOps.push_back(Op);
1350 
1351   if (DiffOps.size() == SA->getNumOperands())
1352     return nullptr;
1353 
1354   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1355   // `Step`:
1356 
1357   // 1. NSW/NUW flags on the step increment.
1358   auto PreStartFlags =
1359     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1360   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1361   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1362       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1363 
1364   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1365   // "S+X does not sign/unsign-overflow".
1366   //
1367 
1368   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1369   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1370       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1371     return PreStart;
1372 
1373   // 2. Direct overflow check on the step operation's expression.
1374   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1375   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1376   const SCEV *OperandExtendedStart =
1377       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1378                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1379   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1380     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1381       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1382       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1383       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1384       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1385     }
1386     return PreStart;
1387   }
1388 
1389   // 3. Loop precondition.
1390   ICmpInst::Predicate Pred;
1391   const SCEV *OverflowLimit =
1392       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1393 
1394   if (OverflowLimit &&
1395       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1396     return PreStart;
1397 
1398   return nullptr;
1399 }
1400 
1401 // Get the normalized zero or sign extended expression for this AddRec's Start.
1402 template <typename ExtendOpTy>
1403 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1404                                         ScalarEvolution *SE,
1405                                         unsigned Depth) {
1406   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1407 
1408   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1409   if (!PreStart)
1410     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1411 
1412   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1413                                              Depth),
1414                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1415 }
1416 
1417 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1418 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1419 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1420 //
1421 // Formally:
1422 //
1423 //     {S,+,X} == {S-T,+,X} + T
1424 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1425 //
1426 // If ({S-T,+,X} + T) does not overflow  ... (1)
1427 //
1428 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1429 //
1430 // If {S-T,+,X} does not overflow  ... (2)
1431 //
1432 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1433 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1434 //
1435 // If (S-T)+T does not overflow  ... (3)
1436 //
1437 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1438 //      == {Ext(S),+,Ext(X)} == LHS
1439 //
1440 // Thus, if (1), (2) and (3) are true for some T, then
1441 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1442 //
1443 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1444 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1445 // to check for (1) and (2).
1446 //
1447 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1448 // is `Delta` (defined below).
1449 template <typename ExtendOpTy>
1450 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1451                                                 const SCEV *Step,
1452                                                 const Loop *L) {
1453   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1454 
1455   // We restrict `Start` to a constant to prevent SCEV from spending too much
1456   // time here.  It is correct (but more expensive) to continue with a
1457   // non-constant `Start` and do a general SCEV subtraction to compute
1458   // `PreStart` below.
1459   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1460   if (!StartC)
1461     return false;
1462 
1463   APInt StartAI = StartC->getAPInt();
1464 
1465   for (unsigned Delta : {-2, -1, 1, 2}) {
1466     const SCEV *PreStart = getConstant(StartAI - Delta);
1467 
1468     FoldingSetNodeID ID;
1469     ID.AddInteger(scAddRecExpr);
1470     ID.AddPointer(PreStart);
1471     ID.AddPointer(Step);
1472     ID.AddPointer(L);
1473     void *IP = nullptr;
1474     const auto *PreAR =
1475       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1476 
1477     // Give up if we don't already have the add recurrence we need because
1478     // actually constructing an add recurrence is relatively expensive.
1479     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1480       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1481       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1482       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1483           DeltaS, &Pred, this);
1484       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1485         return true;
1486     }
1487   }
1488 
1489   return false;
1490 }
1491 
1492 // Finds an integer D for an expression (C + x + y + ...) such that the top
1493 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1494 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1495 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1496 // the (C + x + y + ...) expression is \p WholeAddExpr.
1497 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1498                                             const SCEVConstant *ConstantTerm,
1499                                             const SCEVAddExpr *WholeAddExpr) {
1500   const APInt &C = ConstantTerm->getAPInt();
1501   const unsigned BitWidth = C.getBitWidth();
1502   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1503   uint32_t TZ = BitWidth;
1504   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1505     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1506   if (TZ) {
1507     // Set D to be as many least significant bits of C as possible while still
1508     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1509     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1510   }
1511   return APInt(BitWidth, 0);
1512 }
1513 
1514 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1515 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1516 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1517 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1518 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1519                                             const APInt &ConstantStart,
1520                                             const SCEV *Step) {
1521   const unsigned BitWidth = ConstantStart.getBitWidth();
1522   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1523   if (TZ)
1524     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1525                          : ConstantStart;
1526   return APInt(BitWidth, 0);
1527 }
1528 
1529 const SCEV *
1530 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1531   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1532          "This is not an extending conversion!");
1533   assert(isSCEVable(Ty) &&
1534          "This is not a conversion to a SCEVable type!");
1535   Ty = getEffectiveSCEVType(Ty);
1536 
1537   // Fold if the operand is constant.
1538   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1539     return getConstant(
1540       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1541 
1542   // zext(zext(x)) --> zext(x)
1543   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1544     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1545 
1546   // Before doing any expensive analysis, check to see if we've already
1547   // computed a SCEV for this Op and Ty.
1548   FoldingSetNodeID ID;
1549   ID.AddInteger(scZeroExtend);
1550   ID.AddPointer(Op);
1551   ID.AddPointer(Ty);
1552   void *IP = nullptr;
1553   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1554   if (Depth > MaxCastDepth) {
1555     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1556                                                      Op, Ty);
1557     UniqueSCEVs.InsertNode(S, IP);
1558     addToLoopUseLists(S);
1559     return S;
1560   }
1561 
1562   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1563   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1564     // It's possible the bits taken off by the truncate were all zero bits. If
1565     // so, we should be able to simplify this further.
1566     const SCEV *X = ST->getOperand();
1567     ConstantRange CR = getUnsignedRange(X);
1568     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1569     unsigned NewBits = getTypeSizeInBits(Ty);
1570     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1571             CR.zextOrTrunc(NewBits)))
1572       return getTruncateOrZeroExtend(X, Ty, Depth);
1573   }
1574 
1575   // If the input value is a chrec scev, and we can prove that the value
1576   // did not overflow the old, smaller, value, we can zero extend all of the
1577   // operands (often constants).  This allows analysis of something like
1578   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1579   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1580     if (AR->isAffine()) {
1581       const SCEV *Start = AR->getStart();
1582       const SCEV *Step = AR->getStepRecurrence(*this);
1583       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1584       const Loop *L = AR->getLoop();
1585 
1586       if (!AR->hasNoUnsignedWrap()) {
1587         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1588         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1589       }
1590 
1591       // If we have special knowledge that this addrec won't overflow,
1592       // we don't need to do any further analysis.
1593       if (AR->hasNoUnsignedWrap())
1594         return getAddRecExpr(
1595             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1596             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1597 
1598       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1599       // Note that this serves two purposes: It filters out loops that are
1600       // simply not analyzable, and it covers the case where this code is
1601       // being called from within backedge-taken count analysis, such that
1602       // attempting to ask for the backedge-taken count would likely result
1603       // in infinite recursion. In the later case, the analysis code will
1604       // cope with a conservative value, and it will take care to purge
1605       // that value once it has finished.
1606       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1607       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1608         // Manually compute the final value for AR, checking for
1609         // overflow.
1610 
1611         // Check whether the backedge-taken count can be losslessly casted to
1612         // the addrec's type. The count is always unsigned.
1613         const SCEV *CastedMaxBECount =
1614             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1615         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1616             CastedMaxBECount, MaxBECount->getType(), Depth);
1617         if (MaxBECount == RecastedMaxBECount) {
1618           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1619           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1620           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1621                                         SCEV::FlagAnyWrap, Depth + 1);
1622           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1623                                                           SCEV::FlagAnyWrap,
1624                                                           Depth + 1),
1625                                                WideTy, Depth + 1);
1626           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1627           const SCEV *WideMaxBECount =
1628             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1629           const SCEV *OperandExtendedAdd =
1630             getAddExpr(WideStart,
1631                        getMulExpr(WideMaxBECount,
1632                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1633                                   SCEV::FlagAnyWrap, Depth + 1),
1634                        SCEV::FlagAnyWrap, Depth + 1);
1635           if (ZAdd == OperandExtendedAdd) {
1636             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1637             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1638             // Return the expression with the addrec on the outside.
1639             return getAddRecExpr(
1640                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1641                                                          Depth + 1),
1642                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1643                 AR->getNoWrapFlags());
1644           }
1645           // Similar to above, only this time treat the step value as signed.
1646           // This covers loops that count down.
1647           OperandExtendedAdd =
1648             getAddExpr(WideStart,
1649                        getMulExpr(WideMaxBECount,
1650                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1651                                   SCEV::FlagAnyWrap, Depth + 1),
1652                        SCEV::FlagAnyWrap, Depth + 1);
1653           if (ZAdd == OperandExtendedAdd) {
1654             // Cache knowledge of AR NW, which is propagated to this AddRec.
1655             // Negative step causes unsigned wrap, but it still can't self-wrap.
1656             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1657             // Return the expression with the addrec on the outside.
1658             return getAddRecExpr(
1659                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1660                                                          Depth + 1),
1661                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1662                 AR->getNoWrapFlags());
1663           }
1664         }
1665       }
1666 
1667       // Normally, in the cases we can prove no-overflow via a
1668       // backedge guarding condition, we can also compute a backedge
1669       // taken count for the loop.  The exceptions are assumptions and
1670       // guards present in the loop -- SCEV is not great at exploiting
1671       // these to compute max backedge taken counts, but can still use
1672       // these to prove lack of overflow.  Use this fact to avoid
1673       // doing extra work that may not pay off.
1674       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1675           !AC.assumptions().empty()) {
1676         // If the backedge is guarded by a comparison with the pre-inc
1677         // value the addrec is safe. Also, if the entry is guarded by
1678         // a comparison with the start value and the backedge is
1679         // guarded by a comparison with the post-inc value, the addrec
1680         // is safe.
1681         if (isKnownPositive(Step)) {
1682           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1683                                       getUnsignedRangeMax(Step));
1684           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1685               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1686             // Cache knowledge of AR NUW, which is propagated to this
1687             // AddRec.
1688             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1689             // Return the expression with the addrec on the outside.
1690             return getAddRecExpr(
1691                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1692                                                          Depth + 1),
1693                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1694                 AR->getNoWrapFlags());
1695           }
1696         } else if (isKnownNegative(Step)) {
1697           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1698                                       getSignedRangeMin(Step));
1699           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1700               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1701             // Cache knowledge of AR NW, which is propagated to this
1702             // AddRec.  Negative step causes unsigned wrap, but it
1703             // still can't self-wrap.
1704             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1705             // Return the expression with the addrec on the outside.
1706             return getAddRecExpr(
1707                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1708                                                          Depth + 1),
1709                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1710                 AR->getNoWrapFlags());
1711           }
1712         }
1713       }
1714 
1715       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1716       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1717       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1718       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1719         const APInt &C = SC->getAPInt();
1720         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1721         if (D != 0) {
1722           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1723           const SCEV *SResidual =
1724               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1725           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1726           return getAddExpr(SZExtD, SZExtR,
1727                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1728                             Depth + 1);
1729         }
1730       }
1731 
1732       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1733         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1734         return getAddRecExpr(
1735             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1736             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1737       }
1738     }
1739 
1740   // zext(A % B) --> zext(A) % zext(B)
1741   {
1742     const SCEV *LHS;
1743     const SCEV *RHS;
1744     if (matchURem(Op, LHS, RHS))
1745       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1746                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1747   }
1748 
1749   // zext(A / B) --> zext(A) / zext(B).
1750   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1751     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1752                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1753 
1754   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1755     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1756     if (SA->hasNoUnsignedWrap()) {
1757       // If the addition does not unsign overflow then we can, by definition,
1758       // commute the zero extension with the addition operation.
1759       SmallVector<const SCEV *, 4> Ops;
1760       for (const auto *Op : SA->operands())
1761         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1762       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1763     }
1764 
1765     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1766     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1767     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1768     //
1769     // Often address arithmetics contain expressions like
1770     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1771     // This transformation is useful while proving that such expressions are
1772     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1773     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1774       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1775       if (D != 0) {
1776         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1777         const SCEV *SResidual =
1778             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1779         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1780         return getAddExpr(SZExtD, SZExtR,
1781                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1782                           Depth + 1);
1783       }
1784     }
1785   }
1786 
1787   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1788     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1789     if (SM->hasNoUnsignedWrap()) {
1790       // If the multiply does not unsign overflow then we can, by definition,
1791       // commute the zero extension with the multiply operation.
1792       SmallVector<const SCEV *, 4> Ops;
1793       for (const auto *Op : SM->operands())
1794         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1795       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1796     }
1797 
1798     // zext(2^K * (trunc X to iN)) to iM ->
1799     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1800     //
1801     // Proof:
1802     //
1803     //     zext(2^K * (trunc X to iN)) to iM
1804     //   = zext((trunc X to iN) << K) to iM
1805     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1806     //     (because shl removes the top K bits)
1807     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1808     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1809     //
1810     if (SM->getNumOperands() == 2)
1811       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1812         if (MulLHS->getAPInt().isPowerOf2())
1813           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1814             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1815                                MulLHS->getAPInt().logBase2();
1816             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1817             return getMulExpr(
1818                 getZeroExtendExpr(MulLHS, Ty),
1819                 getZeroExtendExpr(
1820                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1821                 SCEV::FlagNUW, Depth + 1);
1822           }
1823   }
1824 
1825   // The cast wasn't folded; create an explicit cast node.
1826   // Recompute the insert position, as it may have been invalidated.
1827   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1828   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1829                                                    Op, Ty);
1830   UniqueSCEVs.InsertNode(S, IP);
1831   addToLoopUseLists(S);
1832   return S;
1833 }
1834 
1835 const SCEV *
1836 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1837   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1838          "This is not an extending conversion!");
1839   assert(isSCEVable(Ty) &&
1840          "This is not a conversion to a SCEVable type!");
1841   Ty = getEffectiveSCEVType(Ty);
1842 
1843   // Fold if the operand is constant.
1844   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1845     return getConstant(
1846       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1847 
1848   // sext(sext(x)) --> sext(x)
1849   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1850     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1851 
1852   // sext(zext(x)) --> zext(x)
1853   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1854     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1855 
1856   // Before doing any expensive analysis, check to see if we've already
1857   // computed a SCEV for this Op and Ty.
1858   FoldingSetNodeID ID;
1859   ID.AddInteger(scSignExtend);
1860   ID.AddPointer(Op);
1861   ID.AddPointer(Ty);
1862   void *IP = nullptr;
1863   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1864   // Limit recursion depth.
1865   if (Depth > MaxCastDepth) {
1866     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1867                                                      Op, Ty);
1868     UniqueSCEVs.InsertNode(S, IP);
1869     addToLoopUseLists(S);
1870     return S;
1871   }
1872 
1873   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1874   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1875     // It's possible the bits taken off by the truncate were all sign bits. If
1876     // so, we should be able to simplify this further.
1877     const SCEV *X = ST->getOperand();
1878     ConstantRange CR = getSignedRange(X);
1879     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1880     unsigned NewBits = getTypeSizeInBits(Ty);
1881     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1882             CR.sextOrTrunc(NewBits)))
1883       return getTruncateOrSignExtend(X, Ty, Depth);
1884   }
1885 
1886   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1887     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1888     if (SA->hasNoSignedWrap()) {
1889       // If the addition does not sign overflow then we can, by definition,
1890       // commute the sign extension with the addition operation.
1891       SmallVector<const SCEV *, 4> Ops;
1892       for (const auto *Op : SA->operands())
1893         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1894       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1895     }
1896 
1897     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1898     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1899     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1900     //
1901     // For instance, this will bring two seemingly different expressions:
1902     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1903     //         sext(6 + 20 * %x + 24 * %y)
1904     // to the same form:
1905     //     2 + sext(4 + 20 * %x + 24 * %y)
1906     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1907       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1908       if (D != 0) {
1909         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1910         const SCEV *SResidual =
1911             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1912         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1913         return getAddExpr(SSExtD, SSExtR,
1914                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1915                           Depth + 1);
1916       }
1917     }
1918   }
1919   // If the input value is a chrec scev, and we can prove that the value
1920   // did not overflow the old, smaller, value, we can sign extend all of the
1921   // operands (often constants).  This allows analysis of something like
1922   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1923   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1924     if (AR->isAffine()) {
1925       const SCEV *Start = AR->getStart();
1926       const SCEV *Step = AR->getStepRecurrence(*this);
1927       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1928       const Loop *L = AR->getLoop();
1929 
1930       if (!AR->hasNoSignedWrap()) {
1931         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1932         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1933       }
1934 
1935       // If we have special knowledge that this addrec won't overflow,
1936       // we don't need to do any further analysis.
1937       if (AR->hasNoSignedWrap())
1938         return getAddRecExpr(
1939             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1940             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1941 
1942       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1943       // Note that this serves two purposes: It filters out loops that are
1944       // simply not analyzable, and it covers the case where this code is
1945       // being called from within backedge-taken count analysis, such that
1946       // attempting to ask for the backedge-taken count would likely result
1947       // in infinite recursion. In the later case, the analysis code will
1948       // cope with a conservative value, and it will take care to purge
1949       // that value once it has finished.
1950       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1951       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1952         // Manually compute the final value for AR, checking for
1953         // overflow.
1954 
1955         // Check whether the backedge-taken count can be losslessly casted to
1956         // the addrec's type. The count is always unsigned.
1957         const SCEV *CastedMaxBECount =
1958             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1959         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1960             CastedMaxBECount, MaxBECount->getType(), Depth);
1961         if (MaxBECount == RecastedMaxBECount) {
1962           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1963           // Check whether Start+Step*MaxBECount has no signed overflow.
1964           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1965                                         SCEV::FlagAnyWrap, Depth + 1);
1966           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1967                                                           SCEV::FlagAnyWrap,
1968                                                           Depth + 1),
1969                                                WideTy, Depth + 1);
1970           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1971           const SCEV *WideMaxBECount =
1972             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1973           const SCEV *OperandExtendedAdd =
1974             getAddExpr(WideStart,
1975                        getMulExpr(WideMaxBECount,
1976                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1977                                   SCEV::FlagAnyWrap, Depth + 1),
1978                        SCEV::FlagAnyWrap, Depth + 1);
1979           if (SAdd == OperandExtendedAdd) {
1980             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1981             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1982             // Return the expression with the addrec on the outside.
1983             return getAddRecExpr(
1984                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1985                                                          Depth + 1),
1986                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1987                 AR->getNoWrapFlags());
1988           }
1989           // Similar to above, only this time treat the step value as unsigned.
1990           // This covers loops that count up with an unsigned step.
1991           OperandExtendedAdd =
1992             getAddExpr(WideStart,
1993                        getMulExpr(WideMaxBECount,
1994                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1995                                   SCEV::FlagAnyWrap, Depth + 1),
1996                        SCEV::FlagAnyWrap, Depth + 1);
1997           if (SAdd == OperandExtendedAdd) {
1998             // If AR wraps around then
1999             //
2000             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2001             // => SAdd != OperandExtendedAdd
2002             //
2003             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2004             // (SAdd == OperandExtendedAdd => AR is NW)
2005 
2006             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2007 
2008             // Return the expression with the addrec on the outside.
2009             return getAddRecExpr(
2010                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2011                                                          Depth + 1),
2012                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2013                 AR->getNoWrapFlags());
2014           }
2015         }
2016       }
2017 
2018       // Normally, in the cases we can prove no-overflow via a
2019       // backedge guarding condition, we can also compute a backedge
2020       // taken count for the loop.  The exceptions are assumptions and
2021       // guards present in the loop -- SCEV is not great at exploiting
2022       // these to compute max backedge taken counts, but can still use
2023       // these to prove lack of overflow.  Use this fact to avoid
2024       // doing extra work that may not pay off.
2025 
2026       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2027           !AC.assumptions().empty()) {
2028         // If the backedge is guarded by a comparison with the pre-inc
2029         // value the addrec is safe. Also, if the entry is guarded by
2030         // a comparison with the start value and the backedge is
2031         // guarded by a comparison with the post-inc value, the addrec
2032         // is safe.
2033         ICmpInst::Predicate Pred;
2034         const SCEV *OverflowLimit =
2035             getSignedOverflowLimitForStep(Step, &Pred, this);
2036         if (OverflowLimit &&
2037             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2038              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2039           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2040           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2041           return getAddRecExpr(
2042               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2043               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2044         }
2045       }
2046 
2047       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2048       // if D + (C - D + Step * n) could be proven to not signed wrap
2049       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2050       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2051         const APInt &C = SC->getAPInt();
2052         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2053         if (D != 0) {
2054           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2055           const SCEV *SResidual =
2056               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2057           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2058           return getAddExpr(SSExtD, SSExtR,
2059                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2060                             Depth + 1);
2061         }
2062       }
2063 
2064       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2065         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2066         return getAddRecExpr(
2067             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2068             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2069       }
2070     }
2071 
2072   // If the input value is provably positive and we could not simplify
2073   // away the sext build a zext instead.
2074   if (isKnownNonNegative(Op))
2075     return getZeroExtendExpr(Op, Ty, Depth + 1);
2076 
2077   // The cast wasn't folded; create an explicit cast node.
2078   // Recompute the insert position, as it may have been invalidated.
2079   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2080   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2081                                                    Op, Ty);
2082   UniqueSCEVs.InsertNode(S, IP);
2083   addToLoopUseLists(S);
2084   return S;
2085 }
2086 
2087 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2088 /// unspecified bits out to the given type.
2089 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2090                                               Type *Ty) {
2091   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2092          "This is not an extending conversion!");
2093   assert(isSCEVable(Ty) &&
2094          "This is not a conversion to a SCEVable type!");
2095   Ty = getEffectiveSCEVType(Ty);
2096 
2097   // Sign-extend negative constants.
2098   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2099     if (SC->getAPInt().isNegative())
2100       return getSignExtendExpr(Op, Ty);
2101 
2102   // Peel off a truncate cast.
2103   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2104     const SCEV *NewOp = T->getOperand();
2105     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2106       return getAnyExtendExpr(NewOp, Ty);
2107     return getTruncateOrNoop(NewOp, Ty);
2108   }
2109 
2110   // Next try a zext cast. If the cast is folded, use it.
2111   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2112   if (!isa<SCEVZeroExtendExpr>(ZExt))
2113     return ZExt;
2114 
2115   // Next try a sext cast. If the cast is folded, use it.
2116   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2117   if (!isa<SCEVSignExtendExpr>(SExt))
2118     return SExt;
2119 
2120   // Force the cast to be folded into the operands of an addrec.
2121   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2122     SmallVector<const SCEV *, 4> Ops;
2123     for (const SCEV *Op : AR->operands())
2124       Ops.push_back(getAnyExtendExpr(Op, Ty));
2125     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2126   }
2127 
2128   // If the expression is obviously signed, use the sext cast value.
2129   if (isa<SCEVSMaxExpr>(Op))
2130     return SExt;
2131 
2132   // Absent any other information, use the zext cast value.
2133   return ZExt;
2134 }
2135 
2136 /// Process the given Ops list, which is a list of operands to be added under
2137 /// the given scale, update the given map. This is a helper function for
2138 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2139 /// that would form an add expression like this:
2140 ///
2141 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2142 ///
2143 /// where A and B are constants, update the map with these values:
2144 ///
2145 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2146 ///
2147 /// and add 13 + A*B*29 to AccumulatedConstant.
2148 /// This will allow getAddRecExpr to produce this:
2149 ///
2150 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2151 ///
2152 /// This form often exposes folding opportunities that are hidden in
2153 /// the original operand list.
2154 ///
2155 /// Return true iff it appears that any interesting folding opportunities
2156 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2157 /// the common case where no interesting opportunities are present, and
2158 /// is also used as a check to avoid infinite recursion.
2159 static bool
2160 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2161                              SmallVectorImpl<const SCEV *> &NewOps,
2162                              APInt &AccumulatedConstant,
2163                              const SCEV *const *Ops, size_t NumOperands,
2164                              const APInt &Scale,
2165                              ScalarEvolution &SE) {
2166   bool Interesting = false;
2167 
2168   // Iterate over the add operands. They are sorted, with constants first.
2169   unsigned i = 0;
2170   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2171     ++i;
2172     // Pull a buried constant out to the outside.
2173     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2174       Interesting = true;
2175     AccumulatedConstant += Scale * C->getAPInt();
2176   }
2177 
2178   // Next comes everything else. We're especially interested in multiplies
2179   // here, but they're in the middle, so just visit the rest with one loop.
2180   for (; i != NumOperands; ++i) {
2181     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2182     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2183       APInt NewScale =
2184           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2185       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2186         // A multiplication of a constant with another add; recurse.
2187         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2188         Interesting |=
2189           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2190                                        Add->op_begin(), Add->getNumOperands(),
2191                                        NewScale, SE);
2192       } else {
2193         // A multiplication of a constant with some other value. Update
2194         // the map.
2195         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2196         const SCEV *Key = SE.getMulExpr(MulOps);
2197         auto Pair = M.insert({Key, NewScale});
2198         if (Pair.second) {
2199           NewOps.push_back(Pair.first->first);
2200         } else {
2201           Pair.first->second += NewScale;
2202           // The map already had an entry for this value, which may indicate
2203           // a folding opportunity.
2204           Interesting = true;
2205         }
2206       }
2207     } else {
2208       // An ordinary operand. Update the map.
2209       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2210           M.insert({Ops[i], Scale});
2211       if (Pair.second) {
2212         NewOps.push_back(Pair.first->first);
2213       } else {
2214         Pair.first->second += Scale;
2215         // The map already had an entry for this value, which may indicate
2216         // a folding opportunity.
2217         Interesting = true;
2218       }
2219     }
2220   }
2221 
2222   return Interesting;
2223 }
2224 
2225 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2226 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2227 // can't-overflow flags for the operation if possible.
2228 static SCEV::NoWrapFlags
2229 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2230                       const ArrayRef<const SCEV *> Ops,
2231                       SCEV::NoWrapFlags Flags) {
2232   using namespace std::placeholders;
2233 
2234   using OBO = OverflowingBinaryOperator;
2235 
2236   bool CanAnalyze =
2237       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2238   (void)CanAnalyze;
2239   assert(CanAnalyze && "don't call from other places!");
2240 
2241   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2242   SCEV::NoWrapFlags SignOrUnsignWrap =
2243       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2244 
2245   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2246   auto IsKnownNonNegative = [&](const SCEV *S) {
2247     return SE->isKnownNonNegative(S);
2248   };
2249 
2250   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2251     Flags =
2252         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2253 
2254   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2255 
2256   if (SignOrUnsignWrap != SignOrUnsignMask &&
2257       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2258       isa<SCEVConstant>(Ops[0])) {
2259 
2260     auto Opcode = [&] {
2261       switch (Type) {
2262       case scAddExpr:
2263         return Instruction::Add;
2264       case scMulExpr:
2265         return Instruction::Mul;
2266       default:
2267         llvm_unreachable("Unexpected SCEV op.");
2268       }
2269     }();
2270 
2271     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2272 
2273     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2274     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2275       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2276           Opcode, C, OBO::NoSignedWrap);
2277       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2278         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2279     }
2280 
2281     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2282     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2283       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2284           Opcode, C, OBO::NoUnsignedWrap);
2285       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2286         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2287     }
2288   }
2289 
2290   return Flags;
2291 }
2292 
2293 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2294   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2295 }
2296 
2297 /// Get a canonical add expression, or something simpler if possible.
2298 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2299                                         SCEV::NoWrapFlags OrigFlags,
2300                                         unsigned Depth) {
2301   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2302          "only nuw or nsw allowed");
2303   assert(!Ops.empty() && "Cannot get empty add!");
2304   if (Ops.size() == 1) return Ops[0];
2305 #ifndef NDEBUG
2306   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2307   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2308     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2309            "SCEVAddExpr operand types don't match!");
2310 #endif
2311 
2312   // Sort by complexity, this groups all similar expression types together.
2313   GroupByComplexity(Ops, &LI, DT);
2314 
2315   // If there are any constants, fold them together.
2316   unsigned Idx = 0;
2317   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2318     ++Idx;
2319     assert(Idx < Ops.size());
2320     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2321       // We found two constants, fold them together!
2322       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2323       if (Ops.size() == 2) return Ops[0];
2324       Ops.erase(Ops.begin()+1);  // Erase the folded element
2325       LHSC = cast<SCEVConstant>(Ops[0]);
2326     }
2327 
2328     // If we are left with a constant zero being added, strip it off.
2329     if (LHSC->getValue()->isZero()) {
2330       Ops.erase(Ops.begin());
2331       --Idx;
2332     }
2333 
2334     if (Ops.size() == 1) return Ops[0];
2335   }
2336 
2337   // Delay expensive flag strengthening until necessary.
2338   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2339     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2340   };
2341 
2342   // Limit recursion calls depth.
2343   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2344     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2345 
2346   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2347     // Don't strengthen flags if we have no new information.
2348     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2349     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2350       Add->setNoWrapFlags(ComputeFlags(Ops));
2351     return S;
2352   }
2353 
2354   // Okay, check to see if the same value occurs in the operand list more than
2355   // once.  If so, merge them together into an multiply expression.  Since we
2356   // sorted the list, these values are required to be adjacent.
2357   Type *Ty = Ops[0]->getType();
2358   bool FoundMatch = false;
2359   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2360     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2361       // Scan ahead to count how many equal operands there are.
2362       unsigned Count = 2;
2363       while (i+Count != e && Ops[i+Count] == Ops[i])
2364         ++Count;
2365       // Merge the values into a multiply.
2366       const SCEV *Scale = getConstant(Ty, Count);
2367       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2368       if (Ops.size() == Count)
2369         return Mul;
2370       Ops[i] = Mul;
2371       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2372       --i; e -= Count - 1;
2373       FoundMatch = true;
2374     }
2375   if (FoundMatch)
2376     return getAddExpr(Ops, OrigFlags, Depth + 1);
2377 
2378   // Check for truncates. If all the operands are truncated from the same
2379   // type, see if factoring out the truncate would permit the result to be
2380   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2381   // if the contents of the resulting outer trunc fold to something simple.
2382   auto FindTruncSrcType = [&]() -> Type * {
2383     // We're ultimately looking to fold an addrec of truncs and muls of only
2384     // constants and truncs, so if we find any other types of SCEV
2385     // as operands of the addrec then we bail and return nullptr here.
2386     // Otherwise, we return the type of the operand of a trunc that we find.
2387     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2388       return T->getOperand()->getType();
2389     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2390       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2391       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2392         return T->getOperand()->getType();
2393     }
2394     return nullptr;
2395   };
2396   if (auto *SrcType = FindTruncSrcType()) {
2397     SmallVector<const SCEV *, 8> LargeOps;
2398     bool Ok = true;
2399     // Check all the operands to see if they can be represented in the
2400     // source type of the truncate.
2401     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2402       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2403         if (T->getOperand()->getType() != SrcType) {
2404           Ok = false;
2405           break;
2406         }
2407         LargeOps.push_back(T->getOperand());
2408       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2409         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2410       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2411         SmallVector<const SCEV *, 8> LargeMulOps;
2412         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2413           if (const SCEVTruncateExpr *T =
2414                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2415             if (T->getOperand()->getType() != SrcType) {
2416               Ok = false;
2417               break;
2418             }
2419             LargeMulOps.push_back(T->getOperand());
2420           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2421             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2422           } else {
2423             Ok = false;
2424             break;
2425           }
2426         }
2427         if (Ok)
2428           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2429       } else {
2430         Ok = false;
2431         break;
2432       }
2433     }
2434     if (Ok) {
2435       // Evaluate the expression in the larger type.
2436       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2437       // If it folds to something simple, use it. Otherwise, don't.
2438       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2439         return getTruncateExpr(Fold, Ty);
2440     }
2441   }
2442 
2443   // Skip past any other cast SCEVs.
2444   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2445     ++Idx;
2446 
2447   // If there are add operands they would be next.
2448   if (Idx < Ops.size()) {
2449     bool DeletedAdd = false;
2450     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2451       if (Ops.size() > AddOpsInlineThreshold ||
2452           Add->getNumOperands() > AddOpsInlineThreshold)
2453         break;
2454       // If we have an add, expand the add operands onto the end of the operands
2455       // list.
2456       Ops.erase(Ops.begin()+Idx);
2457       Ops.append(Add->op_begin(), Add->op_end());
2458       DeletedAdd = true;
2459     }
2460 
2461     // If we deleted at least one add, we added operands to the end of the list,
2462     // and they are not necessarily sorted.  Recurse to resort and resimplify
2463     // any operands we just acquired.
2464     if (DeletedAdd)
2465       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2466   }
2467 
2468   // Skip over the add expression until we get to a multiply.
2469   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2470     ++Idx;
2471 
2472   // Check to see if there are any folding opportunities present with
2473   // operands multiplied by constant values.
2474   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2475     uint64_t BitWidth = getTypeSizeInBits(Ty);
2476     DenseMap<const SCEV *, APInt> M;
2477     SmallVector<const SCEV *, 8> NewOps;
2478     APInt AccumulatedConstant(BitWidth, 0);
2479     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2480                                      Ops.data(), Ops.size(),
2481                                      APInt(BitWidth, 1), *this)) {
2482       struct APIntCompare {
2483         bool operator()(const APInt &LHS, const APInt &RHS) const {
2484           return LHS.ult(RHS);
2485         }
2486       };
2487 
2488       // Some interesting folding opportunity is present, so its worthwhile to
2489       // re-generate the operands list. Group the operands by constant scale,
2490       // to avoid multiplying by the same constant scale multiple times.
2491       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2492       for (const SCEV *NewOp : NewOps)
2493         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2494       // Re-generate the operands list.
2495       Ops.clear();
2496       if (AccumulatedConstant != 0)
2497         Ops.push_back(getConstant(AccumulatedConstant));
2498       for (auto &MulOp : MulOpLists)
2499         if (MulOp.first != 0)
2500           Ops.push_back(getMulExpr(
2501               getConstant(MulOp.first),
2502               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2503               SCEV::FlagAnyWrap, Depth + 1));
2504       if (Ops.empty())
2505         return getZero(Ty);
2506       if (Ops.size() == 1)
2507         return Ops[0];
2508       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2509     }
2510   }
2511 
2512   // If we are adding something to a multiply expression, make sure the
2513   // something is not already an operand of the multiply.  If so, merge it into
2514   // the multiply.
2515   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2516     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2517     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2518       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2519       if (isa<SCEVConstant>(MulOpSCEV))
2520         continue;
2521       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2522         if (MulOpSCEV == Ops[AddOp]) {
2523           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2524           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2525           if (Mul->getNumOperands() != 2) {
2526             // If the multiply has more than two operands, we must get the
2527             // Y*Z term.
2528             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2529                                                 Mul->op_begin()+MulOp);
2530             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2531             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2532           }
2533           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2534           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2535           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2536                                             SCEV::FlagAnyWrap, Depth + 1);
2537           if (Ops.size() == 2) return OuterMul;
2538           if (AddOp < Idx) {
2539             Ops.erase(Ops.begin()+AddOp);
2540             Ops.erase(Ops.begin()+Idx-1);
2541           } else {
2542             Ops.erase(Ops.begin()+Idx);
2543             Ops.erase(Ops.begin()+AddOp-1);
2544           }
2545           Ops.push_back(OuterMul);
2546           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2547         }
2548 
2549       // Check this multiply against other multiplies being added together.
2550       for (unsigned OtherMulIdx = Idx+1;
2551            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2552            ++OtherMulIdx) {
2553         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2554         // If MulOp occurs in OtherMul, we can fold the two multiplies
2555         // together.
2556         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2557              OMulOp != e; ++OMulOp)
2558           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2559             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2560             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2561             if (Mul->getNumOperands() != 2) {
2562               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2563                                                   Mul->op_begin()+MulOp);
2564               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2565               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2566             }
2567             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2568             if (OtherMul->getNumOperands() != 2) {
2569               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2570                                                   OtherMul->op_begin()+OMulOp);
2571               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2572               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2573             }
2574             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2575             const SCEV *InnerMulSum =
2576                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2577             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2578                                               SCEV::FlagAnyWrap, Depth + 1);
2579             if (Ops.size() == 2) return OuterMul;
2580             Ops.erase(Ops.begin()+Idx);
2581             Ops.erase(Ops.begin()+OtherMulIdx-1);
2582             Ops.push_back(OuterMul);
2583             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2584           }
2585       }
2586     }
2587   }
2588 
2589   // If there are any add recurrences in the operands list, see if any other
2590   // added values are loop invariant.  If so, we can fold them into the
2591   // recurrence.
2592   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2593     ++Idx;
2594 
2595   // Scan over all recurrences, trying to fold loop invariants into them.
2596   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2597     // Scan all of the other operands to this add and add them to the vector if
2598     // they are loop invariant w.r.t. the recurrence.
2599     SmallVector<const SCEV *, 8> LIOps;
2600     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2601     const Loop *AddRecLoop = AddRec->getLoop();
2602     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2603       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2604         LIOps.push_back(Ops[i]);
2605         Ops.erase(Ops.begin()+i);
2606         --i; --e;
2607       }
2608 
2609     // If we found some loop invariants, fold them into the recurrence.
2610     if (!LIOps.empty()) {
2611       // Compute nowrap flags for the addition of the loop-invariant ops and
2612       // the addrec. Temporarily push it as an operand for that purpose.
2613       LIOps.push_back(AddRec);
2614       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2615       LIOps.pop_back();
2616 
2617       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2618       LIOps.push_back(AddRec->getStart());
2619 
2620       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2621                                              AddRec->op_end());
2622       // This follows from the fact that the no-wrap flags on the outer add
2623       // expression are applicable on the 0th iteration, when the add recurrence
2624       // will be equal to its start value.
2625       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2626 
2627       // Build the new addrec. Propagate the NUW and NSW flags if both the
2628       // outer add and the inner addrec are guaranteed to have no overflow.
2629       // Always propagate NW.
2630       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2631       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2632 
2633       // If all of the other operands were loop invariant, we are done.
2634       if (Ops.size() == 1) return NewRec;
2635 
2636       // Otherwise, add the folded AddRec by the non-invariant parts.
2637       for (unsigned i = 0;; ++i)
2638         if (Ops[i] == AddRec) {
2639           Ops[i] = NewRec;
2640           break;
2641         }
2642       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2643     }
2644 
2645     // Okay, if there weren't any loop invariants to be folded, check to see if
2646     // there are multiple AddRec's with the same loop induction variable being
2647     // added together.  If so, we can fold them.
2648     for (unsigned OtherIdx = Idx+1;
2649          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2650          ++OtherIdx) {
2651       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2652       // so that the 1st found AddRecExpr is dominated by all others.
2653       assert(DT.dominates(
2654            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2655            AddRec->getLoop()->getHeader()) &&
2656         "AddRecExprs are not sorted in reverse dominance order?");
2657       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2658         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2659         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2660                                                AddRec->op_end());
2661         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2662              ++OtherIdx) {
2663           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2664           if (OtherAddRec->getLoop() == AddRecLoop) {
2665             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2666                  i != e; ++i) {
2667               if (i >= AddRecOps.size()) {
2668                 AddRecOps.append(OtherAddRec->op_begin()+i,
2669                                  OtherAddRec->op_end());
2670                 break;
2671               }
2672               SmallVector<const SCEV *, 2> TwoOps = {
2673                   AddRecOps[i], OtherAddRec->getOperand(i)};
2674               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2675             }
2676             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2677           }
2678         }
2679         // Step size has changed, so we cannot guarantee no self-wraparound.
2680         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2681         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2682       }
2683     }
2684 
2685     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2686     // next one.
2687   }
2688 
2689   // Okay, it looks like we really DO need an add expr.  Check to see if we
2690   // already have one, otherwise create a new one.
2691   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2692 }
2693 
2694 const SCEV *
2695 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2696                                     SCEV::NoWrapFlags Flags) {
2697   FoldingSetNodeID ID;
2698   ID.AddInteger(scAddExpr);
2699   for (const SCEV *Op : Ops)
2700     ID.AddPointer(Op);
2701   void *IP = nullptr;
2702   SCEVAddExpr *S =
2703       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2704   if (!S) {
2705     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2706     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2707     S = new (SCEVAllocator)
2708         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2709     UniqueSCEVs.InsertNode(S, IP);
2710     addToLoopUseLists(S);
2711   }
2712   S->setNoWrapFlags(Flags);
2713   return S;
2714 }
2715 
2716 const SCEV *
2717 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2718                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2719   FoldingSetNodeID ID;
2720   ID.AddInteger(scAddRecExpr);
2721   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2722     ID.AddPointer(Ops[i]);
2723   ID.AddPointer(L);
2724   void *IP = nullptr;
2725   SCEVAddRecExpr *S =
2726       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2727   if (!S) {
2728     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2729     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2730     S = new (SCEVAllocator)
2731         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2732     UniqueSCEVs.InsertNode(S, IP);
2733     addToLoopUseLists(S);
2734   }
2735   S->setNoWrapFlags(Flags);
2736   return S;
2737 }
2738 
2739 const SCEV *
2740 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2741                                     SCEV::NoWrapFlags Flags) {
2742   FoldingSetNodeID ID;
2743   ID.AddInteger(scMulExpr);
2744   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2745     ID.AddPointer(Ops[i]);
2746   void *IP = nullptr;
2747   SCEVMulExpr *S =
2748     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2749   if (!S) {
2750     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2751     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2752     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2753                                         O, Ops.size());
2754     UniqueSCEVs.InsertNode(S, IP);
2755     addToLoopUseLists(S);
2756   }
2757   S->setNoWrapFlags(Flags);
2758   return S;
2759 }
2760 
2761 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2762   uint64_t k = i*j;
2763   if (j > 1 && k / j != i) Overflow = true;
2764   return k;
2765 }
2766 
2767 /// Compute the result of "n choose k", the binomial coefficient.  If an
2768 /// intermediate computation overflows, Overflow will be set and the return will
2769 /// be garbage. Overflow is not cleared on absence of overflow.
2770 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2771   // We use the multiplicative formula:
2772   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2773   // At each iteration, we take the n-th term of the numeral and divide by the
2774   // (k-n)th term of the denominator.  This division will always produce an
2775   // integral result, and helps reduce the chance of overflow in the
2776   // intermediate computations. However, we can still overflow even when the
2777   // final result would fit.
2778 
2779   if (n == 0 || n == k) return 1;
2780   if (k > n) return 0;
2781 
2782   if (k > n/2)
2783     k = n-k;
2784 
2785   uint64_t r = 1;
2786   for (uint64_t i = 1; i <= k; ++i) {
2787     r = umul_ov(r, n-(i-1), Overflow);
2788     r /= i;
2789   }
2790   return r;
2791 }
2792 
2793 /// Determine if any of the operands in this SCEV are a constant or if
2794 /// any of the add or multiply expressions in this SCEV contain a constant.
2795 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2796   struct FindConstantInAddMulChain {
2797     bool FoundConstant = false;
2798 
2799     bool follow(const SCEV *S) {
2800       FoundConstant |= isa<SCEVConstant>(S);
2801       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2802     }
2803 
2804     bool isDone() const {
2805       return FoundConstant;
2806     }
2807   };
2808 
2809   FindConstantInAddMulChain F;
2810   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2811   ST.visitAll(StartExpr);
2812   return F.FoundConstant;
2813 }
2814 
2815 /// Get a canonical multiply expression, or something simpler if possible.
2816 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2817                                         SCEV::NoWrapFlags OrigFlags,
2818                                         unsigned Depth) {
2819   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2820          "only nuw or nsw allowed");
2821   assert(!Ops.empty() && "Cannot get empty mul!");
2822   if (Ops.size() == 1) return Ops[0];
2823 #ifndef NDEBUG
2824   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2825   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2826     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2827            "SCEVMulExpr operand types don't match!");
2828 #endif
2829 
2830   // Sort by complexity, this groups all similar expression types together.
2831   GroupByComplexity(Ops, &LI, DT);
2832 
2833   // If there are any constants, fold them together.
2834   unsigned Idx = 0;
2835   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2836     ++Idx;
2837     assert(Idx < Ops.size());
2838     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2839       // We found two constants, fold them together!
2840       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2841       if (Ops.size() == 2) return Ops[0];
2842       Ops.erase(Ops.begin()+1);  // Erase the folded element
2843       LHSC = cast<SCEVConstant>(Ops[0]);
2844     }
2845 
2846     // If we have a multiply of zero, it will always be zero.
2847     if (LHSC->getValue()->isZero())
2848       return LHSC;
2849 
2850     // If we are left with a constant one being multiplied, strip it off.
2851     if (LHSC->getValue()->isOne()) {
2852       Ops.erase(Ops.begin());
2853       --Idx;
2854     }
2855 
2856     if (Ops.size() == 1)
2857       return Ops[0];
2858   }
2859 
2860   // Delay expensive flag strengthening until necessary.
2861   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2862     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2863   };
2864 
2865   // Limit recursion calls depth.
2866   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2867     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2868 
2869   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2870     // Don't strengthen flags if we have no new information.
2871     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2872     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2873       Mul->setNoWrapFlags(ComputeFlags(Ops));
2874     return S;
2875   }
2876 
2877   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2878     if (Ops.size() == 2) {
2879       // C1*(C2+V) -> C1*C2 + C1*V
2880       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2881         // If any of Add's ops are Adds or Muls with a constant, apply this
2882         // transformation as well.
2883         //
2884         // TODO: There are some cases where this transformation is not
2885         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2886         // this transformation should be narrowed down.
2887         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2888           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2889                                        SCEV::FlagAnyWrap, Depth + 1),
2890                             getMulExpr(LHSC, Add->getOperand(1),
2891                                        SCEV::FlagAnyWrap, Depth + 1),
2892                             SCEV::FlagAnyWrap, Depth + 1);
2893 
2894       if (Ops[0]->isAllOnesValue()) {
2895         // If we have a mul by -1 of an add, try distributing the -1 among the
2896         // add operands.
2897         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2898           SmallVector<const SCEV *, 4> NewOps;
2899           bool AnyFolded = false;
2900           for (const SCEV *AddOp : Add->operands()) {
2901             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2902                                          Depth + 1);
2903             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2904             NewOps.push_back(Mul);
2905           }
2906           if (AnyFolded)
2907             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2908         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2909           // Negation preserves a recurrence's no self-wrap property.
2910           SmallVector<const SCEV *, 4> Operands;
2911           for (const SCEV *AddRecOp : AddRec->operands())
2912             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2913                                           Depth + 1));
2914 
2915           return getAddRecExpr(Operands, AddRec->getLoop(),
2916                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2917         }
2918       }
2919     }
2920   }
2921 
2922   // Skip over the add expression until we get to a multiply.
2923   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2924     ++Idx;
2925 
2926   // If there are mul operands inline them all into this expression.
2927   if (Idx < Ops.size()) {
2928     bool DeletedMul = false;
2929     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2930       if (Ops.size() > MulOpsInlineThreshold)
2931         break;
2932       // If we have an mul, expand the mul operands onto the end of the
2933       // operands list.
2934       Ops.erase(Ops.begin()+Idx);
2935       Ops.append(Mul->op_begin(), Mul->op_end());
2936       DeletedMul = true;
2937     }
2938 
2939     // If we deleted at least one mul, we added operands to the end of the
2940     // list, and they are not necessarily sorted.  Recurse to resort and
2941     // resimplify any operands we just acquired.
2942     if (DeletedMul)
2943       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2944   }
2945 
2946   // If there are any add recurrences in the operands list, see if any other
2947   // added values are loop invariant.  If so, we can fold them into the
2948   // recurrence.
2949   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2950     ++Idx;
2951 
2952   // Scan over all recurrences, trying to fold loop invariants into them.
2953   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2954     // Scan all of the other operands to this mul and add them to the vector
2955     // if they are loop invariant w.r.t. the recurrence.
2956     SmallVector<const SCEV *, 8> LIOps;
2957     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2958     const Loop *AddRecLoop = AddRec->getLoop();
2959     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2960       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2961         LIOps.push_back(Ops[i]);
2962         Ops.erase(Ops.begin()+i);
2963         --i; --e;
2964       }
2965 
2966     // If we found some loop invariants, fold them into the recurrence.
2967     if (!LIOps.empty()) {
2968       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2969       SmallVector<const SCEV *, 4> NewOps;
2970       NewOps.reserve(AddRec->getNumOperands());
2971       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2972       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2973         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2974                                     SCEV::FlagAnyWrap, Depth + 1));
2975 
2976       // Build the new addrec. Propagate the NUW and NSW flags if both the
2977       // outer mul and the inner addrec are guaranteed to have no overflow.
2978       //
2979       // No self-wrap cannot be guaranteed after changing the step size, but
2980       // will be inferred if either NUW or NSW is true.
2981       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2982       const SCEV *NewRec = getAddRecExpr(
2983           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2984 
2985       // If all of the other operands were loop invariant, we are done.
2986       if (Ops.size() == 1) return NewRec;
2987 
2988       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2989       for (unsigned i = 0;; ++i)
2990         if (Ops[i] == AddRec) {
2991           Ops[i] = NewRec;
2992           break;
2993         }
2994       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2995     }
2996 
2997     // Okay, if there weren't any loop invariants to be folded, check to see
2998     // if there are multiple AddRec's with the same loop induction variable
2999     // being multiplied together.  If so, we can fold them.
3000 
3001     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3002     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3003     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3004     //   ]]],+,...up to x=2n}.
3005     // Note that the arguments to choose() are always integers with values
3006     // known at compile time, never SCEV objects.
3007     //
3008     // The implementation avoids pointless extra computations when the two
3009     // addrec's are of different length (mathematically, it's equivalent to
3010     // an infinite stream of zeros on the right).
3011     bool OpsModified = false;
3012     for (unsigned OtherIdx = Idx+1;
3013          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3014          ++OtherIdx) {
3015       const SCEVAddRecExpr *OtherAddRec =
3016         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3017       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3018         continue;
3019 
3020       // Limit max number of arguments to avoid creation of unreasonably big
3021       // SCEVAddRecs with very complex operands.
3022       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3023           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3024         continue;
3025 
3026       bool Overflow = false;
3027       Type *Ty = AddRec->getType();
3028       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3029       SmallVector<const SCEV*, 7> AddRecOps;
3030       for (int x = 0, xe = AddRec->getNumOperands() +
3031              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3032         SmallVector <const SCEV *, 7> SumOps;
3033         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3034           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3035           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3036                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3037                z < ze && !Overflow; ++z) {
3038             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3039             uint64_t Coeff;
3040             if (LargerThan64Bits)
3041               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3042             else
3043               Coeff = Coeff1*Coeff2;
3044             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3045             const SCEV *Term1 = AddRec->getOperand(y-z);
3046             const SCEV *Term2 = OtherAddRec->getOperand(z);
3047             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3048                                         SCEV::FlagAnyWrap, Depth + 1));
3049           }
3050         }
3051         if (SumOps.empty())
3052           SumOps.push_back(getZero(Ty));
3053         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3054       }
3055       if (!Overflow) {
3056         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3057                                               SCEV::FlagAnyWrap);
3058         if (Ops.size() == 2) return NewAddRec;
3059         Ops[Idx] = NewAddRec;
3060         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3061         OpsModified = true;
3062         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3063         if (!AddRec)
3064           break;
3065       }
3066     }
3067     if (OpsModified)
3068       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3069 
3070     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3071     // next one.
3072   }
3073 
3074   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3075   // already have one, otherwise create a new one.
3076   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3077 }
3078 
3079 /// Represents an unsigned remainder expression based on unsigned division.
3080 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3081                                          const SCEV *RHS) {
3082   assert(getEffectiveSCEVType(LHS->getType()) ==
3083          getEffectiveSCEVType(RHS->getType()) &&
3084          "SCEVURemExpr operand types don't match!");
3085 
3086   // Short-circuit easy cases
3087   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3088     // If constant is one, the result is trivial
3089     if (RHSC->getValue()->isOne())
3090       return getZero(LHS->getType()); // X urem 1 --> 0
3091 
3092     // If constant is a power of two, fold into a zext(trunc(LHS)).
3093     if (RHSC->getAPInt().isPowerOf2()) {
3094       Type *FullTy = LHS->getType();
3095       Type *TruncTy =
3096           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3097       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3098     }
3099   }
3100 
3101   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3102   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3103   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3104   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3105 }
3106 
3107 /// Get a canonical unsigned division expression, or something simpler if
3108 /// possible.
3109 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3110                                          const SCEV *RHS) {
3111   assert(getEffectiveSCEVType(LHS->getType()) ==
3112          getEffectiveSCEVType(RHS->getType()) &&
3113          "SCEVUDivExpr operand types don't match!");
3114 
3115   FoldingSetNodeID ID;
3116   ID.AddInteger(scUDivExpr);
3117   ID.AddPointer(LHS);
3118   ID.AddPointer(RHS);
3119   void *IP = nullptr;
3120   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3121     return S;
3122 
3123   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3124     if (RHSC->getValue()->isOne())
3125       return LHS;                               // X udiv 1 --> x
3126     // If the denominator is zero, the result of the udiv is undefined. Don't
3127     // try to analyze it, because the resolution chosen here may differ from
3128     // the resolution chosen in other parts of the compiler.
3129     if (!RHSC->getValue()->isZero()) {
3130       // Determine if the division can be folded into the operands of
3131       // its operands.
3132       // TODO: Generalize this to non-constants by using known-bits information.
3133       Type *Ty = LHS->getType();
3134       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3135       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3136       // For non-power-of-two values, effectively round the value up to the
3137       // nearest power of two.
3138       if (!RHSC->getAPInt().isPowerOf2())
3139         ++MaxShiftAmt;
3140       IntegerType *ExtTy =
3141         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3142       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3143         if (const SCEVConstant *Step =
3144             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3145           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3146           const APInt &StepInt = Step->getAPInt();
3147           const APInt &DivInt = RHSC->getAPInt();
3148           if (!StepInt.urem(DivInt) &&
3149               getZeroExtendExpr(AR, ExtTy) ==
3150               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3151                             getZeroExtendExpr(Step, ExtTy),
3152                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3153             SmallVector<const SCEV *, 4> Operands;
3154             for (const SCEV *Op : AR->operands())
3155               Operands.push_back(getUDivExpr(Op, RHS));
3156             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3157           }
3158           /// Get a canonical UDivExpr for a recurrence.
3159           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3160           // We can currently only fold X%N if X is constant.
3161           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3162           if (StartC && !DivInt.urem(StepInt) &&
3163               getZeroExtendExpr(AR, ExtTy) ==
3164               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3165                             getZeroExtendExpr(Step, ExtTy),
3166                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3167             const APInt &StartInt = StartC->getAPInt();
3168             const APInt &StartRem = StartInt.urem(StepInt);
3169             if (StartRem != 0) {
3170               const SCEV *NewLHS =
3171                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3172                                 AR->getLoop(), SCEV::FlagNW);
3173               if (LHS != NewLHS) {
3174                 LHS = NewLHS;
3175 
3176                 // Reset the ID to include the new LHS, and check if it is
3177                 // already cached.
3178                 ID.clear();
3179                 ID.AddInteger(scUDivExpr);
3180                 ID.AddPointer(LHS);
3181                 ID.AddPointer(RHS);
3182                 IP = nullptr;
3183                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3184                   return S;
3185               }
3186             }
3187           }
3188         }
3189       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3190       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3191         SmallVector<const SCEV *, 4> Operands;
3192         for (const SCEV *Op : M->operands())
3193           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3194         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3195           // Find an operand that's safely divisible.
3196           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3197             const SCEV *Op = M->getOperand(i);
3198             const SCEV *Div = getUDivExpr(Op, RHSC);
3199             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3200               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3201                                                       M->op_end());
3202               Operands[i] = Div;
3203               return getMulExpr(Operands);
3204             }
3205           }
3206       }
3207 
3208       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3209       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3210         if (auto *DivisorConstant =
3211                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3212           bool Overflow = false;
3213           APInt NewRHS =
3214               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3215           if (Overflow) {
3216             return getConstant(RHSC->getType(), 0, false);
3217           }
3218           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3219         }
3220       }
3221 
3222       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3223       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3224         SmallVector<const SCEV *, 4> Operands;
3225         for (const SCEV *Op : A->operands())
3226           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3227         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3228           Operands.clear();
3229           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3230             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3231             if (isa<SCEVUDivExpr>(Op) ||
3232                 getMulExpr(Op, RHS) != A->getOperand(i))
3233               break;
3234             Operands.push_back(Op);
3235           }
3236           if (Operands.size() == A->getNumOperands())
3237             return getAddExpr(Operands);
3238         }
3239       }
3240 
3241       // Fold if both operands are constant.
3242       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3243         Constant *LHSCV = LHSC->getValue();
3244         Constant *RHSCV = RHSC->getValue();
3245         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3246                                                                    RHSCV)));
3247       }
3248     }
3249   }
3250 
3251   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3252   // changes). Make sure we get a new one.
3253   IP = nullptr;
3254   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3255   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3256                                              LHS, RHS);
3257   UniqueSCEVs.InsertNode(S, IP);
3258   addToLoopUseLists(S);
3259   return S;
3260 }
3261 
3262 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3263   APInt A = C1->getAPInt().abs();
3264   APInt B = C2->getAPInt().abs();
3265   uint32_t ABW = A.getBitWidth();
3266   uint32_t BBW = B.getBitWidth();
3267 
3268   if (ABW > BBW)
3269     B = B.zext(ABW);
3270   else if (ABW < BBW)
3271     A = A.zext(BBW);
3272 
3273   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3274 }
3275 
3276 /// Get a canonical unsigned division expression, or something simpler if
3277 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3278 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3279 /// it's not exact because the udiv may be clearing bits.
3280 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3281                                               const SCEV *RHS) {
3282   // TODO: we could try to find factors in all sorts of things, but for now we
3283   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3284   // end of this file for inspiration.
3285 
3286   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3287   if (!Mul || !Mul->hasNoUnsignedWrap())
3288     return getUDivExpr(LHS, RHS);
3289 
3290   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3291     // If the mulexpr multiplies by a constant, then that constant must be the
3292     // first element of the mulexpr.
3293     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3294       if (LHSCst == RHSCst) {
3295         SmallVector<const SCEV *, 2> Operands;
3296         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3297         return getMulExpr(Operands);
3298       }
3299 
3300       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3301       // that there's a factor provided by one of the other terms. We need to
3302       // check.
3303       APInt Factor = gcd(LHSCst, RHSCst);
3304       if (!Factor.isIntN(1)) {
3305         LHSCst =
3306             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3307         RHSCst =
3308             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3309         SmallVector<const SCEV *, 2> Operands;
3310         Operands.push_back(LHSCst);
3311         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3312         LHS = getMulExpr(Operands);
3313         RHS = RHSCst;
3314         Mul = dyn_cast<SCEVMulExpr>(LHS);
3315         if (!Mul)
3316           return getUDivExactExpr(LHS, RHS);
3317       }
3318     }
3319   }
3320 
3321   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3322     if (Mul->getOperand(i) == RHS) {
3323       SmallVector<const SCEV *, 2> Operands;
3324       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3325       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3326       return getMulExpr(Operands);
3327     }
3328   }
3329 
3330   return getUDivExpr(LHS, RHS);
3331 }
3332 
3333 /// Get an add recurrence expression for the specified loop.  Simplify the
3334 /// expression as much as possible.
3335 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3336                                            const Loop *L,
3337                                            SCEV::NoWrapFlags Flags) {
3338   SmallVector<const SCEV *, 4> Operands;
3339   Operands.push_back(Start);
3340   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3341     if (StepChrec->getLoop() == L) {
3342       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3343       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3344     }
3345 
3346   Operands.push_back(Step);
3347   return getAddRecExpr(Operands, L, Flags);
3348 }
3349 
3350 /// Get an add recurrence expression for the specified loop.  Simplify the
3351 /// expression as much as possible.
3352 const SCEV *
3353 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3354                                const Loop *L, SCEV::NoWrapFlags Flags) {
3355   if (Operands.size() == 1) return Operands[0];
3356 #ifndef NDEBUG
3357   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3358   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3359     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3360            "SCEVAddRecExpr operand types don't match!");
3361   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3362     assert(isLoopInvariant(Operands[i], L) &&
3363            "SCEVAddRecExpr operand is not loop-invariant!");
3364 #endif
3365 
3366   if (Operands.back()->isZero()) {
3367     Operands.pop_back();
3368     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3369   }
3370 
3371   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3372   // use that information to infer NUW and NSW flags. However, computing a
3373   // BE count requires calling getAddRecExpr, so we may not yet have a
3374   // meaningful BE count at this point (and if we don't, we'd be stuck
3375   // with a SCEVCouldNotCompute as the cached BE count).
3376 
3377   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3378 
3379   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3380   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3381     const Loop *NestedLoop = NestedAR->getLoop();
3382     if (L->contains(NestedLoop)
3383             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3384             : (!NestedLoop->contains(L) &&
3385                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3386       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3387                                                   NestedAR->op_end());
3388       Operands[0] = NestedAR->getStart();
3389       // AddRecs require their operands be loop-invariant with respect to their
3390       // loops. Don't perform this transformation if it would break this
3391       // requirement.
3392       bool AllInvariant = all_of(
3393           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3394 
3395       if (AllInvariant) {
3396         // Create a recurrence for the outer loop with the same step size.
3397         //
3398         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3399         // inner recurrence has the same property.
3400         SCEV::NoWrapFlags OuterFlags =
3401           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3402 
3403         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3404         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3405           return isLoopInvariant(Op, NestedLoop);
3406         });
3407 
3408         if (AllInvariant) {
3409           // Ok, both add recurrences are valid after the transformation.
3410           //
3411           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3412           // the outer recurrence has the same property.
3413           SCEV::NoWrapFlags InnerFlags =
3414             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3415           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3416         }
3417       }
3418       // Reset Operands to its original state.
3419       Operands[0] = NestedAR;
3420     }
3421   }
3422 
3423   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3424   // already have one, otherwise create a new one.
3425   return getOrCreateAddRecExpr(Operands, L, Flags);
3426 }
3427 
3428 const SCEV *
3429 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3430                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3431   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3432   // getSCEV(Base)->getType() has the same address space as Base->getType()
3433   // because SCEV::getType() preserves the address space.
3434   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3435   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3436   // instruction to its SCEV, because the Instruction may be guarded by control
3437   // flow and the no-overflow bits may not be valid for the expression in any
3438   // context. This can be fixed similarly to how these flags are handled for
3439   // adds.
3440   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3441                                              : SCEV::FlagAnyWrap;
3442 
3443   Type *CurTy = GEP->getType();
3444   bool FirstIter = true;
3445   SmallVector<const SCEV *, 4> AddOps{BaseExpr};
3446   for (const SCEV *IndexExpr : IndexExprs) {
3447     // Compute the (potentially symbolic) offset in bytes for this index.
3448     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3449       // For a struct, add the member offset.
3450       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3451       unsigned FieldNo = Index->getZExtValue();
3452       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3453       AddOps.push_back(FieldOffset);
3454 
3455       // Update CurTy to the type of the field at Index.
3456       CurTy = STy->getTypeAtIndex(Index);
3457     } else {
3458       // Update CurTy to its element type.
3459       if (FirstIter) {
3460         assert(isa<PointerType>(CurTy) &&
3461                "The first index of a GEP indexes a pointer");
3462         CurTy = GEP->getSourceElementType();
3463         FirstIter = false;
3464       } else {
3465         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3466       }
3467       // For an array, add the element offset, explicitly scaled.
3468       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3469       // Getelementptr indices are signed.
3470       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3471 
3472       // Multiply the index by the element size to compute the element offset.
3473       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3474       AddOps.push_back(LocalOffset);
3475     }
3476   }
3477 
3478   // Add the base and all the offsets together.
3479   return getAddExpr(AddOps, Wrap);
3480 }
3481 
3482 std::tuple<SCEV *, FoldingSetNodeID, void *>
3483 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3484                                          ArrayRef<const SCEV *> Ops) {
3485   FoldingSetNodeID ID;
3486   void *IP = nullptr;
3487   ID.AddInteger(SCEVType);
3488   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3489     ID.AddPointer(Ops[i]);
3490   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3491       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3492 }
3493 
3494 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3495   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3496   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3497 }
3498 
3499 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) {
3500   Type *Ty = Op->getType();
3501   return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty));
3502 }
3503 
3504 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3505                                            SmallVectorImpl<const SCEV *> &Ops) {
3506   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3507   if (Ops.size() == 1) return Ops[0];
3508 #ifndef NDEBUG
3509   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3510   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3511     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3512            "Operand types don't match!");
3513 #endif
3514 
3515   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3516   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3517 
3518   // Sort by complexity, this groups all similar expression types together.
3519   GroupByComplexity(Ops, &LI, DT);
3520 
3521   // Check if we have created the same expression before.
3522   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3523     return S;
3524   }
3525 
3526   // If there are any constants, fold them together.
3527   unsigned Idx = 0;
3528   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3529     ++Idx;
3530     assert(Idx < Ops.size());
3531     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3532       if (Kind == scSMaxExpr)
3533         return APIntOps::smax(LHS, RHS);
3534       else if (Kind == scSMinExpr)
3535         return APIntOps::smin(LHS, RHS);
3536       else if (Kind == scUMaxExpr)
3537         return APIntOps::umax(LHS, RHS);
3538       else if (Kind == scUMinExpr)
3539         return APIntOps::umin(LHS, RHS);
3540       llvm_unreachable("Unknown SCEV min/max opcode");
3541     };
3542 
3543     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3544       // We found two constants, fold them together!
3545       ConstantInt *Fold = ConstantInt::get(
3546           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3547       Ops[0] = getConstant(Fold);
3548       Ops.erase(Ops.begin()+1);  // Erase the folded element
3549       if (Ops.size() == 1) return Ops[0];
3550       LHSC = cast<SCEVConstant>(Ops[0]);
3551     }
3552 
3553     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3554     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3555 
3556     if (IsMax ? IsMinV : IsMaxV) {
3557       // If we are left with a constant minimum(/maximum)-int, strip it off.
3558       Ops.erase(Ops.begin());
3559       --Idx;
3560     } else if (IsMax ? IsMaxV : IsMinV) {
3561       // If we have a max(/min) with a constant maximum(/minimum)-int,
3562       // it will always be the extremum.
3563       return LHSC;
3564     }
3565 
3566     if (Ops.size() == 1) return Ops[0];
3567   }
3568 
3569   // Find the first operation of the same kind
3570   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3571     ++Idx;
3572 
3573   // Check to see if one of the operands is of the same kind. If so, expand its
3574   // operands onto our operand list, and recurse to simplify.
3575   if (Idx < Ops.size()) {
3576     bool DeletedAny = false;
3577     while (Ops[Idx]->getSCEVType() == Kind) {
3578       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3579       Ops.erase(Ops.begin()+Idx);
3580       Ops.append(SMME->op_begin(), SMME->op_end());
3581       DeletedAny = true;
3582     }
3583 
3584     if (DeletedAny)
3585       return getMinMaxExpr(Kind, Ops);
3586   }
3587 
3588   // Okay, check to see if the same value occurs in the operand list twice.  If
3589   // so, delete one.  Since we sorted the list, these values are required to
3590   // be adjacent.
3591   llvm::CmpInst::Predicate GEPred =
3592       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3593   llvm::CmpInst::Predicate LEPred =
3594       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3595   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3596   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3597   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3598     if (Ops[i] == Ops[i + 1] ||
3599         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3600       //  X op Y op Y  -->  X op Y
3601       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3602       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3603       --i;
3604       --e;
3605     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3606                                                Ops[i + 1])) {
3607       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3608       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3609       --i;
3610       --e;
3611     }
3612   }
3613 
3614   if (Ops.size() == 1) return Ops[0];
3615 
3616   assert(!Ops.empty() && "Reduced smax down to nothing!");
3617 
3618   // Okay, it looks like we really DO need an expr.  Check to see if we
3619   // already have one, otherwise create a new one.
3620   const SCEV *ExistingSCEV;
3621   FoldingSetNodeID ID;
3622   void *IP;
3623   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3624   if (ExistingSCEV)
3625     return ExistingSCEV;
3626   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3627   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3628   SCEV *S = new (SCEVAllocator)
3629       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3630 
3631   UniqueSCEVs.InsertNode(S, IP);
3632   addToLoopUseLists(S);
3633   return S;
3634 }
3635 
3636 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3637   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3638   return getSMaxExpr(Ops);
3639 }
3640 
3641 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3642   return getMinMaxExpr(scSMaxExpr, Ops);
3643 }
3644 
3645 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3646   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3647   return getUMaxExpr(Ops);
3648 }
3649 
3650 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3651   return getMinMaxExpr(scUMaxExpr, Ops);
3652 }
3653 
3654 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3655                                          const SCEV *RHS) {
3656   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3657   return getSMinExpr(Ops);
3658 }
3659 
3660 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3661   return getMinMaxExpr(scSMinExpr, Ops);
3662 }
3663 
3664 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3665                                          const SCEV *RHS) {
3666   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3667   return getUMinExpr(Ops);
3668 }
3669 
3670 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3671   return getMinMaxExpr(scUMinExpr, Ops);
3672 }
3673 
3674 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3675   if (isa<ScalableVectorType>(AllocTy)) {
3676     Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo());
3677     Constant *One = ConstantInt::get(IntTy, 1);
3678     Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One);
3679     // Note that the expression we created is the final expression, we don't
3680     // want to simplify it any further Also, if we call a normal getSCEV(),
3681     // we'll end up in an endless recursion. So just create an SCEVUnknown.
3682     return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3683   }
3684   // We can bypass creating a target-independent
3685   // constant expression and then folding it back into a ConstantInt.
3686   // This is just a compile-time optimization.
3687   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3688 }
3689 
3690 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3691                                              StructType *STy,
3692                                              unsigned FieldNo) {
3693   // We can bypass creating a target-independent
3694   // constant expression and then folding it back into a ConstantInt.
3695   // This is just a compile-time optimization.
3696   return getConstant(
3697       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3698 }
3699 
3700 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3701   // Don't attempt to do anything other than create a SCEVUnknown object
3702   // here.  createSCEV only calls getUnknown after checking for all other
3703   // interesting possibilities, and any other code that calls getUnknown
3704   // is doing so in order to hide a value from SCEV canonicalization.
3705 
3706   FoldingSetNodeID ID;
3707   ID.AddInteger(scUnknown);
3708   ID.AddPointer(V);
3709   void *IP = nullptr;
3710   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3711     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3712            "Stale SCEVUnknown in uniquing map!");
3713     return S;
3714   }
3715   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3716                                             FirstUnknown);
3717   FirstUnknown = cast<SCEVUnknown>(S);
3718   UniqueSCEVs.InsertNode(S, IP);
3719   return S;
3720 }
3721 
3722 //===----------------------------------------------------------------------===//
3723 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3724 //
3725 
3726 /// Test if values of the given type are analyzable within the SCEV
3727 /// framework. This primarily includes integer types, and it can optionally
3728 /// include pointer types if the ScalarEvolution class has access to
3729 /// target-specific information.
3730 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3731   // Integers and pointers are always SCEVable.
3732   return Ty->isIntOrPtrTy();
3733 }
3734 
3735 /// Return the size in bits of the specified type, for which isSCEVable must
3736 /// return true.
3737 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3738   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3739   if (Ty->isPointerTy())
3740     return getDataLayout().getIndexTypeSizeInBits(Ty);
3741   return getDataLayout().getTypeSizeInBits(Ty);
3742 }
3743 
3744 /// Return a type with the same bitwidth as the given type and which represents
3745 /// how SCEV will treat the given type, for which isSCEVable must return
3746 /// true. For pointer types, this is the pointer index sized integer type.
3747 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3748   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3749 
3750   if (Ty->isIntegerTy())
3751     return Ty;
3752 
3753   // The only other support type is pointer.
3754   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3755   return getDataLayout().getIndexType(Ty);
3756 }
3757 
3758 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3759   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3760 }
3761 
3762 const SCEV *ScalarEvolution::getCouldNotCompute() {
3763   return CouldNotCompute.get();
3764 }
3765 
3766 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3767   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3768     auto *SU = dyn_cast<SCEVUnknown>(S);
3769     return SU && SU->getValue() == nullptr;
3770   });
3771 
3772   return !ContainsNulls;
3773 }
3774 
3775 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3776   HasRecMapType::iterator I = HasRecMap.find(S);
3777   if (I != HasRecMap.end())
3778     return I->second;
3779 
3780   bool FoundAddRec =
3781       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3782   HasRecMap.insert({S, FoundAddRec});
3783   return FoundAddRec;
3784 }
3785 
3786 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3787 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3788 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3789 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3790   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3791   if (!Add)
3792     return {S, nullptr};
3793 
3794   if (Add->getNumOperands() != 2)
3795     return {S, nullptr};
3796 
3797   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3798   if (!ConstOp)
3799     return {S, nullptr};
3800 
3801   return {Add->getOperand(1), ConstOp->getValue()};
3802 }
3803 
3804 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3805 /// by the value and offset from any ValueOffsetPair in the set.
3806 SetVector<ScalarEvolution::ValueOffsetPair> *
3807 ScalarEvolution::getSCEVValues(const SCEV *S) {
3808   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3809   if (SI == ExprValueMap.end())
3810     return nullptr;
3811 #ifndef NDEBUG
3812   if (VerifySCEVMap) {
3813     // Check there is no dangling Value in the set returned.
3814     for (const auto &VE : SI->second)
3815       assert(ValueExprMap.count(VE.first));
3816   }
3817 #endif
3818   return &SI->second;
3819 }
3820 
3821 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3822 /// cannot be used separately. eraseValueFromMap should be used to remove
3823 /// V from ValueExprMap and ExprValueMap at the same time.
3824 void ScalarEvolution::eraseValueFromMap(Value *V) {
3825   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3826   if (I != ValueExprMap.end()) {
3827     const SCEV *S = I->second;
3828     // Remove {V, 0} from the set of ExprValueMap[S]
3829     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3830       SV->remove({V, nullptr});
3831 
3832     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3833     const SCEV *Stripped;
3834     ConstantInt *Offset;
3835     std::tie(Stripped, Offset) = splitAddExpr(S);
3836     if (Offset != nullptr) {
3837       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3838         SV->remove({V, Offset});
3839     }
3840     ValueExprMap.erase(V);
3841   }
3842 }
3843 
3844 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3845 /// TODO: In reality it is better to check the poison recursively
3846 /// but this is better than nothing.
3847 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3848   if (auto *I = dyn_cast<Instruction>(V)) {
3849     if (isa<OverflowingBinaryOperator>(I)) {
3850       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3851         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3852           return true;
3853         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3854           return true;
3855       }
3856     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3857       return true;
3858   }
3859   return false;
3860 }
3861 
3862 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3863 /// create a new one.
3864 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3865   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3866 
3867   const SCEV *S = getExistingSCEV(V);
3868   if (S == nullptr) {
3869     S = createSCEV(V);
3870     // During PHI resolution, it is possible to create two SCEVs for the same
3871     // V, so it is needed to double check whether V->S is inserted into
3872     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3873     std::pair<ValueExprMapType::iterator, bool> Pair =
3874         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3875     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3876       ExprValueMap[S].insert({V, nullptr});
3877 
3878       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3879       // ExprValueMap.
3880       const SCEV *Stripped = S;
3881       ConstantInt *Offset = nullptr;
3882       std::tie(Stripped, Offset) = splitAddExpr(S);
3883       // If stripped is SCEVUnknown, don't bother to save
3884       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3885       // increase the complexity of the expansion code.
3886       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3887       // because it may generate add/sub instead of GEP in SCEV expansion.
3888       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3889           !isa<GetElementPtrInst>(V))
3890         ExprValueMap[Stripped].insert({V, Offset});
3891     }
3892   }
3893   return S;
3894 }
3895 
3896 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3897   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3898 
3899   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3900   if (I != ValueExprMap.end()) {
3901     const SCEV *S = I->second;
3902     if (checkValidity(S))
3903       return S;
3904     eraseValueFromMap(V);
3905     forgetMemoizedResults(S);
3906   }
3907   return nullptr;
3908 }
3909 
3910 /// Return a SCEV corresponding to -V = -1*V
3911 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3912                                              SCEV::NoWrapFlags Flags) {
3913   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3914     return getConstant(
3915                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3916 
3917   Type *Ty = V->getType();
3918   Ty = getEffectiveSCEVType(Ty);
3919   return getMulExpr(V, getMinusOne(Ty), Flags);
3920 }
3921 
3922 /// If Expr computes ~A, return A else return nullptr
3923 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3924   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3925   if (!Add || Add->getNumOperands() != 2 ||
3926       !Add->getOperand(0)->isAllOnesValue())
3927     return nullptr;
3928 
3929   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3930   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3931       !AddRHS->getOperand(0)->isAllOnesValue())
3932     return nullptr;
3933 
3934   return AddRHS->getOperand(1);
3935 }
3936 
3937 /// Return a SCEV corresponding to ~V = -1-V
3938 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3939   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3940     return getConstant(
3941                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3942 
3943   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3944   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3945     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3946       SmallVector<const SCEV *, 2> MatchedOperands;
3947       for (const SCEV *Operand : MME->operands()) {
3948         const SCEV *Matched = MatchNotExpr(Operand);
3949         if (!Matched)
3950           return (const SCEV *)nullptr;
3951         MatchedOperands.push_back(Matched);
3952       }
3953       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3954                            MatchedOperands);
3955     };
3956     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3957       return Replaced;
3958   }
3959 
3960   Type *Ty = V->getType();
3961   Ty = getEffectiveSCEVType(Ty);
3962   return getMinusSCEV(getMinusOne(Ty), V);
3963 }
3964 
3965 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3966                                           SCEV::NoWrapFlags Flags,
3967                                           unsigned Depth) {
3968   // Fast path: X - X --> 0.
3969   if (LHS == RHS)
3970     return getZero(LHS->getType());
3971 
3972   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3973   // makes it so that we cannot make much use of NUW.
3974   auto AddFlags = SCEV::FlagAnyWrap;
3975   const bool RHSIsNotMinSigned =
3976       !getSignedRangeMin(RHS).isMinSignedValue();
3977   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3978     // Let M be the minimum representable signed value. Then (-1)*RHS
3979     // signed-wraps if and only if RHS is M. That can happen even for
3980     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3981     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3982     // (-1)*RHS, we need to prove that RHS != M.
3983     //
3984     // If LHS is non-negative and we know that LHS - RHS does not
3985     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3986     // either by proving that RHS > M or that LHS >= 0.
3987     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3988       AddFlags = SCEV::FlagNSW;
3989     }
3990   }
3991 
3992   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3993   // RHS is NSW and LHS >= 0.
3994   //
3995   // The difficulty here is that the NSW flag may have been proven
3996   // relative to a loop that is to be found in a recurrence in LHS and
3997   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3998   // larger scope than intended.
3999   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4000 
4001   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4002 }
4003 
4004 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4005                                                      unsigned Depth) {
4006   Type *SrcTy = V->getType();
4007   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4008          "Cannot truncate or zero extend with non-integer arguments!");
4009   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4010     return V;  // No conversion
4011   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4012     return getTruncateExpr(V, Ty, Depth);
4013   return getZeroExtendExpr(V, Ty, Depth);
4014 }
4015 
4016 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4017                                                      unsigned Depth) {
4018   Type *SrcTy = V->getType();
4019   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4020          "Cannot truncate or zero extend with non-integer arguments!");
4021   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4022     return V;  // No conversion
4023   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4024     return getTruncateExpr(V, Ty, Depth);
4025   return getSignExtendExpr(V, Ty, Depth);
4026 }
4027 
4028 const SCEV *
4029 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4030   Type *SrcTy = V->getType();
4031   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4032          "Cannot noop or zero extend with non-integer arguments!");
4033   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4034          "getNoopOrZeroExtend cannot truncate!");
4035   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4036     return V;  // No conversion
4037   return getZeroExtendExpr(V, Ty);
4038 }
4039 
4040 const SCEV *
4041 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4042   Type *SrcTy = V->getType();
4043   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4044          "Cannot noop or sign extend with non-integer arguments!");
4045   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4046          "getNoopOrSignExtend cannot truncate!");
4047   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4048     return V;  // No conversion
4049   return getSignExtendExpr(V, Ty);
4050 }
4051 
4052 const SCEV *
4053 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4054   Type *SrcTy = V->getType();
4055   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4056          "Cannot noop or any extend with non-integer arguments!");
4057   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4058          "getNoopOrAnyExtend cannot truncate!");
4059   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4060     return V;  // No conversion
4061   return getAnyExtendExpr(V, Ty);
4062 }
4063 
4064 const SCEV *
4065 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4066   Type *SrcTy = V->getType();
4067   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4068          "Cannot truncate or noop with non-integer arguments!");
4069   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4070          "getTruncateOrNoop cannot extend!");
4071   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4072     return V;  // No conversion
4073   return getTruncateExpr(V, Ty);
4074 }
4075 
4076 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4077                                                         const SCEV *RHS) {
4078   const SCEV *PromotedLHS = LHS;
4079   const SCEV *PromotedRHS = RHS;
4080 
4081   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4082     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4083   else
4084     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4085 
4086   return getUMaxExpr(PromotedLHS, PromotedRHS);
4087 }
4088 
4089 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4090                                                         const SCEV *RHS) {
4091   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4092   return getUMinFromMismatchedTypes(Ops);
4093 }
4094 
4095 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4096     SmallVectorImpl<const SCEV *> &Ops) {
4097   assert(!Ops.empty() && "At least one operand must be!");
4098   // Trivial case.
4099   if (Ops.size() == 1)
4100     return Ops[0];
4101 
4102   // Find the max type first.
4103   Type *MaxType = nullptr;
4104   for (auto *S : Ops)
4105     if (MaxType)
4106       MaxType = getWiderType(MaxType, S->getType());
4107     else
4108       MaxType = S->getType();
4109   assert(MaxType && "Failed to find maximum type!");
4110 
4111   // Extend all ops to max type.
4112   SmallVector<const SCEV *, 2> PromotedOps;
4113   for (auto *S : Ops)
4114     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4115 
4116   // Generate umin.
4117   return getUMinExpr(PromotedOps);
4118 }
4119 
4120 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4121   // A pointer operand may evaluate to a nonpointer expression, such as null.
4122   if (!V->getType()->isPointerTy())
4123     return V;
4124 
4125   while (true) {
4126     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4127       V = Cast->getOperand();
4128     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4129       const SCEV *PtrOp = nullptr;
4130       for (const SCEV *NAryOp : NAry->operands()) {
4131         if (NAryOp->getType()->isPointerTy()) {
4132           // Cannot find the base of an expression with multiple pointer ops.
4133           if (PtrOp)
4134             return V;
4135           PtrOp = NAryOp;
4136         }
4137       }
4138       if (!PtrOp) // All operands were non-pointer.
4139         return V;
4140       V = PtrOp;
4141     } else // Not something we can look further into.
4142       return V;
4143   }
4144 }
4145 
4146 /// Push users of the given Instruction onto the given Worklist.
4147 static void
4148 PushDefUseChildren(Instruction *I,
4149                    SmallVectorImpl<Instruction *> &Worklist) {
4150   // Push the def-use children onto the Worklist stack.
4151   for (User *U : I->users())
4152     Worklist.push_back(cast<Instruction>(U));
4153 }
4154 
4155 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4156   SmallVector<Instruction *, 16> Worklist;
4157   PushDefUseChildren(PN, Worklist);
4158 
4159   SmallPtrSet<Instruction *, 8> Visited;
4160   Visited.insert(PN);
4161   while (!Worklist.empty()) {
4162     Instruction *I = Worklist.pop_back_val();
4163     if (!Visited.insert(I).second)
4164       continue;
4165 
4166     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4167     if (It != ValueExprMap.end()) {
4168       const SCEV *Old = It->second;
4169 
4170       // Short-circuit the def-use traversal if the symbolic name
4171       // ceases to appear in expressions.
4172       if (Old != SymName && !hasOperand(Old, SymName))
4173         continue;
4174 
4175       // SCEVUnknown for a PHI either means that it has an unrecognized
4176       // structure, it's a PHI that's in the progress of being computed
4177       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4178       // additional loop trip count information isn't going to change anything.
4179       // In the second case, createNodeForPHI will perform the necessary
4180       // updates on its own when it gets to that point. In the third, we do
4181       // want to forget the SCEVUnknown.
4182       if (!isa<PHINode>(I) ||
4183           !isa<SCEVUnknown>(Old) ||
4184           (I != PN && Old == SymName)) {
4185         eraseValueFromMap(It->first);
4186         forgetMemoizedResults(Old);
4187       }
4188     }
4189 
4190     PushDefUseChildren(I, Worklist);
4191   }
4192 }
4193 
4194 namespace {
4195 
4196 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4197 /// expression in case its Loop is L. If it is not L then
4198 /// if IgnoreOtherLoops is true then use AddRec itself
4199 /// otherwise rewrite cannot be done.
4200 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4201 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4202 public:
4203   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4204                              bool IgnoreOtherLoops = true) {
4205     SCEVInitRewriter Rewriter(L, SE);
4206     const SCEV *Result = Rewriter.visit(S);
4207     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4208       return SE.getCouldNotCompute();
4209     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4210                ? SE.getCouldNotCompute()
4211                : Result;
4212   }
4213 
4214   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4215     if (!SE.isLoopInvariant(Expr, L))
4216       SeenLoopVariantSCEVUnknown = true;
4217     return Expr;
4218   }
4219 
4220   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4221     // Only re-write AddRecExprs for this loop.
4222     if (Expr->getLoop() == L)
4223       return Expr->getStart();
4224     SeenOtherLoops = true;
4225     return Expr;
4226   }
4227 
4228   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4229 
4230   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4231 
4232 private:
4233   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4234       : SCEVRewriteVisitor(SE), L(L) {}
4235 
4236   const Loop *L;
4237   bool SeenLoopVariantSCEVUnknown = false;
4238   bool SeenOtherLoops = false;
4239 };
4240 
4241 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4242 /// increment expression in case its Loop is L. If it is not L then
4243 /// use AddRec itself.
4244 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4245 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4246 public:
4247   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4248     SCEVPostIncRewriter Rewriter(L, SE);
4249     const SCEV *Result = Rewriter.visit(S);
4250     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4251         ? SE.getCouldNotCompute()
4252         : Result;
4253   }
4254 
4255   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4256     if (!SE.isLoopInvariant(Expr, L))
4257       SeenLoopVariantSCEVUnknown = true;
4258     return Expr;
4259   }
4260 
4261   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4262     // Only re-write AddRecExprs for this loop.
4263     if (Expr->getLoop() == L)
4264       return Expr->getPostIncExpr(SE);
4265     SeenOtherLoops = true;
4266     return Expr;
4267   }
4268 
4269   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4270 
4271   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4272 
4273 private:
4274   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4275       : SCEVRewriteVisitor(SE), L(L) {}
4276 
4277   const Loop *L;
4278   bool SeenLoopVariantSCEVUnknown = false;
4279   bool SeenOtherLoops = false;
4280 };
4281 
4282 /// This class evaluates the compare condition by matching it against the
4283 /// condition of loop latch. If there is a match we assume a true value
4284 /// for the condition while building SCEV nodes.
4285 class SCEVBackedgeConditionFolder
4286     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4287 public:
4288   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4289                              ScalarEvolution &SE) {
4290     bool IsPosBECond = false;
4291     Value *BECond = nullptr;
4292     if (BasicBlock *Latch = L->getLoopLatch()) {
4293       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4294       if (BI && BI->isConditional()) {
4295         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4296                "Both outgoing branches should not target same header!");
4297         BECond = BI->getCondition();
4298         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4299       } else {
4300         return S;
4301       }
4302     }
4303     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4304     return Rewriter.visit(S);
4305   }
4306 
4307   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4308     const SCEV *Result = Expr;
4309     bool InvariantF = SE.isLoopInvariant(Expr, L);
4310 
4311     if (!InvariantF) {
4312       Instruction *I = cast<Instruction>(Expr->getValue());
4313       switch (I->getOpcode()) {
4314       case Instruction::Select: {
4315         SelectInst *SI = cast<SelectInst>(I);
4316         Optional<const SCEV *> Res =
4317             compareWithBackedgeCondition(SI->getCondition());
4318         if (Res.hasValue()) {
4319           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4320           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4321         }
4322         break;
4323       }
4324       default: {
4325         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4326         if (Res.hasValue())
4327           Result = Res.getValue();
4328         break;
4329       }
4330       }
4331     }
4332     return Result;
4333   }
4334 
4335 private:
4336   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4337                                        bool IsPosBECond, ScalarEvolution &SE)
4338       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4339         IsPositiveBECond(IsPosBECond) {}
4340 
4341   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4342 
4343   const Loop *L;
4344   /// Loop back condition.
4345   Value *BackedgeCond = nullptr;
4346   /// Set to true if loop back is on positive branch condition.
4347   bool IsPositiveBECond;
4348 };
4349 
4350 Optional<const SCEV *>
4351 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4352 
4353   // If value matches the backedge condition for loop latch,
4354   // then return a constant evolution node based on loopback
4355   // branch taken.
4356   if (BackedgeCond == IC)
4357     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4358                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4359   return None;
4360 }
4361 
4362 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4363 public:
4364   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4365                              ScalarEvolution &SE) {
4366     SCEVShiftRewriter Rewriter(L, SE);
4367     const SCEV *Result = Rewriter.visit(S);
4368     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4369   }
4370 
4371   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4372     // Only allow AddRecExprs for this loop.
4373     if (!SE.isLoopInvariant(Expr, L))
4374       Valid = false;
4375     return Expr;
4376   }
4377 
4378   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4379     if (Expr->getLoop() == L && Expr->isAffine())
4380       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4381     Valid = false;
4382     return Expr;
4383   }
4384 
4385   bool isValid() { return Valid; }
4386 
4387 private:
4388   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4389       : SCEVRewriteVisitor(SE), L(L) {}
4390 
4391   const Loop *L;
4392   bool Valid = true;
4393 };
4394 
4395 } // end anonymous namespace
4396 
4397 SCEV::NoWrapFlags
4398 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4399   if (!AR->isAffine())
4400     return SCEV::FlagAnyWrap;
4401 
4402   using OBO = OverflowingBinaryOperator;
4403 
4404   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4405 
4406   if (!AR->hasNoSignedWrap()) {
4407     ConstantRange AddRecRange = getSignedRange(AR);
4408     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4409 
4410     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4411         Instruction::Add, IncRange, OBO::NoSignedWrap);
4412     if (NSWRegion.contains(AddRecRange))
4413       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4414   }
4415 
4416   if (!AR->hasNoUnsignedWrap()) {
4417     ConstantRange AddRecRange = getUnsignedRange(AR);
4418     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4419 
4420     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4421         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4422     if (NUWRegion.contains(AddRecRange))
4423       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4424   }
4425 
4426   return Result;
4427 }
4428 
4429 namespace {
4430 
4431 /// Represents an abstract binary operation.  This may exist as a
4432 /// normal instruction or constant expression, or may have been
4433 /// derived from an expression tree.
4434 struct BinaryOp {
4435   unsigned Opcode;
4436   Value *LHS;
4437   Value *RHS;
4438   bool IsNSW = false;
4439   bool IsNUW = false;
4440   bool IsExact = false;
4441 
4442   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4443   /// constant expression.
4444   Operator *Op = nullptr;
4445 
4446   explicit BinaryOp(Operator *Op)
4447       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4448         Op(Op) {
4449     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4450       IsNSW = OBO->hasNoSignedWrap();
4451       IsNUW = OBO->hasNoUnsignedWrap();
4452     }
4453     if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op))
4454       IsExact = PEO->isExact();
4455   }
4456 
4457   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4458                     bool IsNUW = false, bool IsExact = false)
4459       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4460         IsExact(IsExact) {}
4461 };
4462 
4463 } // end anonymous namespace
4464 
4465 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4466 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4467   auto *Op = dyn_cast<Operator>(V);
4468   if (!Op)
4469     return None;
4470 
4471   // Implementation detail: all the cleverness here should happen without
4472   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4473   // SCEV expressions when possible, and we should not break that.
4474 
4475   switch (Op->getOpcode()) {
4476   case Instruction::Add:
4477   case Instruction::Sub:
4478   case Instruction::Mul:
4479   case Instruction::UDiv:
4480   case Instruction::URem:
4481   case Instruction::And:
4482   case Instruction::Or:
4483   case Instruction::AShr:
4484   case Instruction::Shl:
4485     return BinaryOp(Op);
4486 
4487   case Instruction::Xor:
4488     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4489       // If the RHS of the xor is a signmask, then this is just an add.
4490       // Instcombine turns add of signmask into xor as a strength reduction step.
4491       if (RHSC->getValue().isSignMask())
4492         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4493     return BinaryOp(Op);
4494 
4495   case Instruction::LShr:
4496     // Turn logical shift right of a constant into a unsigned divide.
4497     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4498       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4499 
4500       // If the shift count is not less than the bitwidth, the result of
4501       // the shift is undefined. Don't try to analyze it, because the
4502       // resolution chosen here may differ from the resolution chosen in
4503       // other parts of the compiler.
4504       if (SA->getValue().ult(BitWidth)) {
4505         Constant *X =
4506             ConstantInt::get(SA->getContext(),
4507                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4508         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4509       }
4510     }
4511     return BinaryOp(Op);
4512 
4513   case Instruction::ExtractValue: {
4514     auto *EVI = cast<ExtractValueInst>(Op);
4515     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4516       break;
4517 
4518     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4519     if (!WO)
4520       break;
4521 
4522     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4523     bool Signed = WO->isSigned();
4524     // TODO: Should add nuw/nsw flags for mul as well.
4525     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4526       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4527 
4528     // Now that we know that all uses of the arithmetic-result component of
4529     // CI are guarded by the overflow check, we can go ahead and pretend
4530     // that the arithmetic is non-overflowing.
4531     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4532                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4533   }
4534 
4535   default:
4536     break;
4537   }
4538 
4539   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4540   // semantics as a Sub, return a binary sub expression.
4541   if (auto *II = dyn_cast<IntrinsicInst>(V))
4542     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4543       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4544 
4545   return None;
4546 }
4547 
4548 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4549 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4550 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4551 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4552 /// follows one of the following patterns:
4553 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4554 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4555 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4556 /// we return the type of the truncation operation, and indicate whether the
4557 /// truncated type should be treated as signed/unsigned by setting
4558 /// \p Signed to true/false, respectively.
4559 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4560                                bool &Signed, ScalarEvolution &SE) {
4561   // The case where Op == SymbolicPHI (that is, with no type conversions on
4562   // the way) is handled by the regular add recurrence creating logic and
4563   // would have already been triggered in createAddRecForPHI. Reaching it here
4564   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4565   // because one of the other operands of the SCEVAddExpr updating this PHI is
4566   // not invariant).
4567   //
4568   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4569   // this case predicates that allow us to prove that Op == SymbolicPHI will
4570   // be added.
4571   if (Op == SymbolicPHI)
4572     return nullptr;
4573 
4574   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4575   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4576   if (SourceBits != NewBits)
4577     return nullptr;
4578 
4579   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4580   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4581   if (!SExt && !ZExt)
4582     return nullptr;
4583   const SCEVTruncateExpr *Trunc =
4584       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4585            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4586   if (!Trunc)
4587     return nullptr;
4588   const SCEV *X = Trunc->getOperand();
4589   if (X != SymbolicPHI)
4590     return nullptr;
4591   Signed = SExt != nullptr;
4592   return Trunc->getType();
4593 }
4594 
4595 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4596   if (!PN->getType()->isIntegerTy())
4597     return nullptr;
4598   const Loop *L = LI.getLoopFor(PN->getParent());
4599   if (!L || L->getHeader() != PN->getParent())
4600     return nullptr;
4601   return L;
4602 }
4603 
4604 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4605 // computation that updates the phi follows the following pattern:
4606 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4607 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4608 // If so, try to see if it can be rewritten as an AddRecExpr under some
4609 // Predicates. If successful, return them as a pair. Also cache the results
4610 // of the analysis.
4611 //
4612 // Example usage scenario:
4613 //    Say the Rewriter is called for the following SCEV:
4614 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4615 //    where:
4616 //         %X = phi i64 (%Start, %BEValue)
4617 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4618 //    and call this function with %SymbolicPHI = %X.
4619 //
4620 //    The analysis will find that the value coming around the backedge has
4621 //    the following SCEV:
4622 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4623 //    Upon concluding that this matches the desired pattern, the function
4624 //    will return the pair {NewAddRec, SmallPredsVec} where:
4625 //         NewAddRec = {%Start,+,%Step}
4626 //         SmallPredsVec = {P1, P2, P3} as follows:
4627 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4628 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4629 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4630 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4631 //    under the predicates {P1,P2,P3}.
4632 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4633 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4634 //
4635 // TODO's:
4636 //
4637 // 1) Extend the Induction descriptor to also support inductions that involve
4638 //    casts: When needed (namely, when we are called in the context of the
4639 //    vectorizer induction analysis), a Set of cast instructions will be
4640 //    populated by this method, and provided back to isInductionPHI. This is
4641 //    needed to allow the vectorizer to properly record them to be ignored by
4642 //    the cost model and to avoid vectorizing them (otherwise these casts,
4643 //    which are redundant under the runtime overflow checks, will be
4644 //    vectorized, which can be costly).
4645 //
4646 // 2) Support additional induction/PHISCEV patterns: We also want to support
4647 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4648 //    after the induction update operation (the induction increment):
4649 //
4650 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4651 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4652 //
4653 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4654 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4655 //
4656 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4657 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4658 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4659   SmallVector<const SCEVPredicate *, 3> Predicates;
4660 
4661   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4662   // return an AddRec expression under some predicate.
4663 
4664   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4665   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4666   assert(L && "Expecting an integer loop header phi");
4667 
4668   // The loop may have multiple entrances or multiple exits; we can analyze
4669   // this phi as an addrec if it has a unique entry value and a unique
4670   // backedge value.
4671   Value *BEValueV = nullptr, *StartValueV = nullptr;
4672   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4673     Value *V = PN->getIncomingValue(i);
4674     if (L->contains(PN->getIncomingBlock(i))) {
4675       if (!BEValueV) {
4676         BEValueV = V;
4677       } else if (BEValueV != V) {
4678         BEValueV = nullptr;
4679         break;
4680       }
4681     } else if (!StartValueV) {
4682       StartValueV = V;
4683     } else if (StartValueV != V) {
4684       StartValueV = nullptr;
4685       break;
4686     }
4687   }
4688   if (!BEValueV || !StartValueV)
4689     return None;
4690 
4691   const SCEV *BEValue = getSCEV(BEValueV);
4692 
4693   // If the value coming around the backedge is an add with the symbolic
4694   // value we just inserted, possibly with casts that we can ignore under
4695   // an appropriate runtime guard, then we found a simple induction variable!
4696   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4697   if (!Add)
4698     return None;
4699 
4700   // If there is a single occurrence of the symbolic value, possibly
4701   // casted, replace it with a recurrence.
4702   unsigned FoundIndex = Add->getNumOperands();
4703   Type *TruncTy = nullptr;
4704   bool Signed;
4705   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4706     if ((TruncTy =
4707              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4708       if (FoundIndex == e) {
4709         FoundIndex = i;
4710         break;
4711       }
4712 
4713   if (FoundIndex == Add->getNumOperands())
4714     return None;
4715 
4716   // Create an add with everything but the specified operand.
4717   SmallVector<const SCEV *, 8> Ops;
4718   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4719     if (i != FoundIndex)
4720       Ops.push_back(Add->getOperand(i));
4721   const SCEV *Accum = getAddExpr(Ops);
4722 
4723   // The runtime checks will not be valid if the step amount is
4724   // varying inside the loop.
4725   if (!isLoopInvariant(Accum, L))
4726     return None;
4727 
4728   // *** Part2: Create the predicates
4729 
4730   // Analysis was successful: we have a phi-with-cast pattern for which we
4731   // can return an AddRec expression under the following predicates:
4732   //
4733   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4734   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4735   // P2: An Equal predicate that guarantees that
4736   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4737   // P3: An Equal predicate that guarantees that
4738   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4739   //
4740   // As we next prove, the above predicates guarantee that:
4741   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4742   //
4743   //
4744   // More formally, we want to prove that:
4745   //     Expr(i+1) = Start + (i+1) * Accum
4746   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4747   //
4748   // Given that:
4749   // 1) Expr(0) = Start
4750   // 2) Expr(1) = Start + Accum
4751   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4752   // 3) Induction hypothesis (step i):
4753   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4754   //
4755   // Proof:
4756   //  Expr(i+1) =
4757   //   = Start + (i+1)*Accum
4758   //   = (Start + i*Accum) + Accum
4759   //   = Expr(i) + Accum
4760   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4761   //                                                             :: from step i
4762   //
4763   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4764   //
4765   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4766   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4767   //     + Accum                                                     :: from P3
4768   //
4769   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4770   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4771   //
4772   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4773   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4774   //
4775   // By induction, the same applies to all iterations 1<=i<n:
4776   //
4777 
4778   // Create a truncated addrec for which we will add a no overflow check (P1).
4779   const SCEV *StartVal = getSCEV(StartValueV);
4780   const SCEV *PHISCEV =
4781       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4782                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4783 
4784   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4785   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4786   // will be constant.
4787   //
4788   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4789   // add P1.
4790   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4791     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4792         Signed ? SCEVWrapPredicate::IncrementNSSW
4793                : SCEVWrapPredicate::IncrementNUSW;
4794     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4795     Predicates.push_back(AddRecPred);
4796   }
4797 
4798   // Create the Equal Predicates P2,P3:
4799 
4800   // It is possible that the predicates P2 and/or P3 are computable at
4801   // compile time due to StartVal and/or Accum being constants.
4802   // If either one is, then we can check that now and escape if either P2
4803   // or P3 is false.
4804 
4805   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4806   // for each of StartVal and Accum
4807   auto getExtendedExpr = [&](const SCEV *Expr,
4808                              bool CreateSignExtend) -> const SCEV * {
4809     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4810     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4811     const SCEV *ExtendedExpr =
4812         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4813                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4814     return ExtendedExpr;
4815   };
4816 
4817   // Given:
4818   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4819   //               = getExtendedExpr(Expr)
4820   // Determine whether the predicate P: Expr == ExtendedExpr
4821   // is known to be false at compile time
4822   auto PredIsKnownFalse = [&](const SCEV *Expr,
4823                               const SCEV *ExtendedExpr) -> bool {
4824     return Expr != ExtendedExpr &&
4825            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4826   };
4827 
4828   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4829   if (PredIsKnownFalse(StartVal, StartExtended)) {
4830     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4831     return None;
4832   }
4833 
4834   // The Step is always Signed (because the overflow checks are either
4835   // NSSW or NUSW)
4836   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4837   if (PredIsKnownFalse(Accum, AccumExtended)) {
4838     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4839     return None;
4840   }
4841 
4842   auto AppendPredicate = [&](const SCEV *Expr,
4843                              const SCEV *ExtendedExpr) -> void {
4844     if (Expr != ExtendedExpr &&
4845         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4846       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4847       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4848       Predicates.push_back(Pred);
4849     }
4850   };
4851 
4852   AppendPredicate(StartVal, StartExtended);
4853   AppendPredicate(Accum, AccumExtended);
4854 
4855   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4856   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4857   // into NewAR if it will also add the runtime overflow checks specified in
4858   // Predicates.
4859   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4860 
4861   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4862       std::make_pair(NewAR, Predicates);
4863   // Remember the result of the analysis for this SCEV at this locayyytion.
4864   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4865   return PredRewrite;
4866 }
4867 
4868 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4869 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4870   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4871   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4872   if (!L)
4873     return None;
4874 
4875   // Check to see if we already analyzed this PHI.
4876   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4877   if (I != PredicatedSCEVRewrites.end()) {
4878     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4879         I->second;
4880     // Analysis was done before and failed to create an AddRec:
4881     if (Rewrite.first == SymbolicPHI)
4882       return None;
4883     // Analysis was done before and succeeded to create an AddRec under
4884     // a predicate:
4885     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4886     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4887     return Rewrite;
4888   }
4889 
4890   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4891     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4892 
4893   // Record in the cache that the analysis failed
4894   if (!Rewrite) {
4895     SmallVector<const SCEVPredicate *, 3> Predicates;
4896     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4897     return None;
4898   }
4899 
4900   return Rewrite;
4901 }
4902 
4903 // FIXME: This utility is currently required because the Rewriter currently
4904 // does not rewrite this expression:
4905 // {0, +, (sext ix (trunc iy to ix) to iy)}
4906 // into {0, +, %step},
4907 // even when the following Equal predicate exists:
4908 // "%step == (sext ix (trunc iy to ix) to iy)".
4909 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4910     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4911   if (AR1 == AR2)
4912     return true;
4913 
4914   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4915     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4916         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4917       return false;
4918     return true;
4919   };
4920 
4921   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4922       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4923     return false;
4924   return true;
4925 }
4926 
4927 /// A helper function for createAddRecFromPHI to handle simple cases.
4928 ///
4929 /// This function tries to find an AddRec expression for the simplest (yet most
4930 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4931 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4932 /// technique for finding the AddRec expression.
4933 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4934                                                       Value *BEValueV,
4935                                                       Value *StartValueV) {
4936   const Loop *L = LI.getLoopFor(PN->getParent());
4937   assert(L && L->getHeader() == PN->getParent());
4938   assert(BEValueV && StartValueV);
4939 
4940   auto BO = MatchBinaryOp(BEValueV, DT);
4941   if (!BO)
4942     return nullptr;
4943 
4944   if (BO->Opcode != Instruction::Add)
4945     return nullptr;
4946 
4947   const SCEV *Accum = nullptr;
4948   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4949     Accum = getSCEV(BO->RHS);
4950   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4951     Accum = getSCEV(BO->LHS);
4952 
4953   if (!Accum)
4954     return nullptr;
4955 
4956   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4957   if (BO->IsNUW)
4958     Flags = setFlags(Flags, SCEV::FlagNUW);
4959   if (BO->IsNSW)
4960     Flags = setFlags(Flags, SCEV::FlagNSW);
4961 
4962   const SCEV *StartVal = getSCEV(StartValueV);
4963   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4964 
4965   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4966 
4967   // We can add Flags to the post-inc expression only if we
4968   // know that it is *undefined behavior* for BEValueV to
4969   // overflow.
4970   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4971     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4972       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4973 
4974   return PHISCEV;
4975 }
4976 
4977 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4978   const Loop *L = LI.getLoopFor(PN->getParent());
4979   if (!L || L->getHeader() != PN->getParent())
4980     return nullptr;
4981 
4982   // The loop may have multiple entrances or multiple exits; we can analyze
4983   // this phi as an addrec if it has a unique entry value and a unique
4984   // backedge value.
4985   Value *BEValueV = nullptr, *StartValueV = nullptr;
4986   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4987     Value *V = PN->getIncomingValue(i);
4988     if (L->contains(PN->getIncomingBlock(i))) {
4989       if (!BEValueV) {
4990         BEValueV = V;
4991       } else if (BEValueV != V) {
4992         BEValueV = nullptr;
4993         break;
4994       }
4995     } else if (!StartValueV) {
4996       StartValueV = V;
4997     } else if (StartValueV != V) {
4998       StartValueV = nullptr;
4999       break;
5000     }
5001   }
5002   if (!BEValueV || !StartValueV)
5003     return nullptr;
5004 
5005   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5006          "PHI node already processed?");
5007 
5008   // First, try to find AddRec expression without creating a fictituos symbolic
5009   // value for PN.
5010   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5011     return S;
5012 
5013   // Handle PHI node value symbolically.
5014   const SCEV *SymbolicName = getUnknown(PN);
5015   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5016 
5017   // Using this symbolic name for the PHI, analyze the value coming around
5018   // the back-edge.
5019   const SCEV *BEValue = getSCEV(BEValueV);
5020 
5021   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5022   // has a special value for the first iteration of the loop.
5023 
5024   // If the value coming around the backedge is an add with the symbolic
5025   // value we just inserted, then we found a simple induction variable!
5026   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5027     // If there is a single occurrence of the symbolic value, replace it
5028     // with a recurrence.
5029     unsigned FoundIndex = Add->getNumOperands();
5030     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5031       if (Add->getOperand(i) == SymbolicName)
5032         if (FoundIndex == e) {
5033           FoundIndex = i;
5034           break;
5035         }
5036 
5037     if (FoundIndex != Add->getNumOperands()) {
5038       // Create an add with everything but the specified operand.
5039       SmallVector<const SCEV *, 8> Ops;
5040       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5041         if (i != FoundIndex)
5042           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5043                                                              L, *this));
5044       const SCEV *Accum = getAddExpr(Ops);
5045 
5046       // This is not a valid addrec if the step amount is varying each
5047       // loop iteration, but is not itself an addrec in this loop.
5048       if (isLoopInvariant(Accum, L) ||
5049           (isa<SCEVAddRecExpr>(Accum) &&
5050            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5051         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5052 
5053         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5054           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5055             if (BO->IsNUW)
5056               Flags = setFlags(Flags, SCEV::FlagNUW);
5057             if (BO->IsNSW)
5058               Flags = setFlags(Flags, SCEV::FlagNSW);
5059           }
5060         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5061           // If the increment is an inbounds GEP, then we know the address
5062           // space cannot be wrapped around. We cannot make any guarantee
5063           // about signed or unsigned overflow because pointers are
5064           // unsigned but we may have a negative index from the base
5065           // pointer. We can guarantee that no unsigned wrap occurs if the
5066           // indices form a positive value.
5067           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5068             Flags = setFlags(Flags, SCEV::FlagNW);
5069 
5070             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5071             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5072               Flags = setFlags(Flags, SCEV::FlagNUW);
5073           }
5074 
5075           // We cannot transfer nuw and nsw flags from subtraction
5076           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5077           // for instance.
5078         }
5079 
5080         const SCEV *StartVal = getSCEV(StartValueV);
5081         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5082 
5083         // Okay, for the entire analysis of this edge we assumed the PHI
5084         // to be symbolic.  We now need to go back and purge all of the
5085         // entries for the scalars that use the symbolic expression.
5086         forgetSymbolicName(PN, SymbolicName);
5087         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5088 
5089         // We can add Flags to the post-inc expression only if we
5090         // know that it is *undefined behavior* for BEValueV to
5091         // overflow.
5092         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5093           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5094             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5095 
5096         return PHISCEV;
5097       }
5098     }
5099   } else {
5100     // Otherwise, this could be a loop like this:
5101     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5102     // In this case, j = {1,+,1}  and BEValue is j.
5103     // Because the other in-value of i (0) fits the evolution of BEValue
5104     // i really is an addrec evolution.
5105     //
5106     // We can generalize this saying that i is the shifted value of BEValue
5107     // by one iteration:
5108     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5109     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5110     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5111     if (Shifted != getCouldNotCompute() &&
5112         Start != getCouldNotCompute()) {
5113       const SCEV *StartVal = getSCEV(StartValueV);
5114       if (Start == StartVal) {
5115         // Okay, for the entire analysis of this edge we assumed the PHI
5116         // to be symbolic.  We now need to go back and purge all of the
5117         // entries for the scalars that use the symbolic expression.
5118         forgetSymbolicName(PN, SymbolicName);
5119         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5120         return Shifted;
5121       }
5122     }
5123   }
5124 
5125   // Remove the temporary PHI node SCEV that has been inserted while intending
5126   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5127   // as it will prevent later (possibly simpler) SCEV expressions to be added
5128   // to the ValueExprMap.
5129   eraseValueFromMap(PN);
5130 
5131   return nullptr;
5132 }
5133 
5134 // Checks if the SCEV S is available at BB.  S is considered available at BB
5135 // if S can be materialized at BB without introducing a fault.
5136 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5137                                BasicBlock *BB) {
5138   struct CheckAvailable {
5139     bool TraversalDone = false;
5140     bool Available = true;
5141 
5142     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5143     BasicBlock *BB = nullptr;
5144     DominatorTree &DT;
5145 
5146     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5147       : L(L), BB(BB), DT(DT) {}
5148 
5149     bool setUnavailable() {
5150       TraversalDone = true;
5151       Available = false;
5152       return false;
5153     }
5154 
5155     bool follow(const SCEV *S) {
5156       switch (S->getSCEVType()) {
5157       case scConstant:
5158       case scPtrToInt:
5159       case scTruncate:
5160       case scZeroExtend:
5161       case scSignExtend:
5162       case scAddExpr:
5163       case scMulExpr:
5164       case scUMaxExpr:
5165       case scSMaxExpr:
5166       case scUMinExpr:
5167       case scSMinExpr:
5168         // These expressions are available if their operand(s) is/are.
5169         return true;
5170 
5171       case scAddRecExpr: {
5172         // We allow add recurrences that are on the loop BB is in, or some
5173         // outer loop.  This guarantees availability because the value of the
5174         // add recurrence at BB is simply the "current" value of the induction
5175         // variable.  We can relax this in the future; for instance an add
5176         // recurrence on a sibling dominating loop is also available at BB.
5177         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5178         if (L && (ARLoop == L || ARLoop->contains(L)))
5179           return true;
5180 
5181         return setUnavailable();
5182       }
5183 
5184       case scUnknown: {
5185         // For SCEVUnknown, we check for simple dominance.
5186         const auto *SU = cast<SCEVUnknown>(S);
5187         Value *V = SU->getValue();
5188 
5189         if (isa<Argument>(V))
5190           return false;
5191 
5192         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5193           return false;
5194 
5195         return setUnavailable();
5196       }
5197 
5198       case scUDivExpr:
5199       case scCouldNotCompute:
5200         // We do not try to smart about these at all.
5201         return setUnavailable();
5202       }
5203       llvm_unreachable("Unknown SCEV kind!");
5204     }
5205 
5206     bool isDone() { return TraversalDone; }
5207   };
5208 
5209   CheckAvailable CA(L, BB, DT);
5210   SCEVTraversal<CheckAvailable> ST(CA);
5211 
5212   ST.visitAll(S);
5213   return CA.Available;
5214 }
5215 
5216 // Try to match a control flow sequence that branches out at BI and merges back
5217 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5218 // match.
5219 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5220                           Value *&C, Value *&LHS, Value *&RHS) {
5221   C = BI->getCondition();
5222 
5223   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5224   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5225 
5226   if (!LeftEdge.isSingleEdge())
5227     return false;
5228 
5229   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5230 
5231   Use &LeftUse = Merge->getOperandUse(0);
5232   Use &RightUse = Merge->getOperandUse(1);
5233 
5234   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5235     LHS = LeftUse;
5236     RHS = RightUse;
5237     return true;
5238   }
5239 
5240   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5241     LHS = RightUse;
5242     RHS = LeftUse;
5243     return true;
5244   }
5245 
5246   return false;
5247 }
5248 
5249 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5250   auto IsReachable =
5251       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5252   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5253     const Loop *L = LI.getLoopFor(PN->getParent());
5254 
5255     // We don't want to break LCSSA, even in a SCEV expression tree.
5256     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5257       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5258         return nullptr;
5259 
5260     // Try to match
5261     //
5262     //  br %cond, label %left, label %right
5263     // left:
5264     //  br label %merge
5265     // right:
5266     //  br label %merge
5267     // merge:
5268     //  V = phi [ %x, %left ], [ %y, %right ]
5269     //
5270     // as "select %cond, %x, %y"
5271 
5272     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5273     assert(IDom && "At least the entry block should dominate PN");
5274 
5275     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5276     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5277 
5278     if (BI && BI->isConditional() &&
5279         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5280         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5281         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5282       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5283   }
5284 
5285   return nullptr;
5286 }
5287 
5288 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5289   if (const SCEV *S = createAddRecFromPHI(PN))
5290     return S;
5291 
5292   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5293     return S;
5294 
5295   // If the PHI has a single incoming value, follow that value, unless the
5296   // PHI's incoming blocks are in a different loop, in which case doing so
5297   // risks breaking LCSSA form. Instcombine would normally zap these, but
5298   // it doesn't have DominatorTree information, so it may miss cases.
5299   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5300     if (LI.replacementPreservesLCSSAForm(PN, V))
5301       return getSCEV(V);
5302 
5303   // If it's not a loop phi, we can't handle it yet.
5304   return getUnknown(PN);
5305 }
5306 
5307 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5308                                                       Value *Cond,
5309                                                       Value *TrueVal,
5310                                                       Value *FalseVal) {
5311   // Handle "constant" branch or select. This can occur for instance when a
5312   // loop pass transforms an inner loop and moves on to process the outer loop.
5313   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5314     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5315 
5316   // Try to match some simple smax or umax patterns.
5317   auto *ICI = dyn_cast<ICmpInst>(Cond);
5318   if (!ICI)
5319     return getUnknown(I);
5320 
5321   Value *LHS = ICI->getOperand(0);
5322   Value *RHS = ICI->getOperand(1);
5323 
5324   switch (ICI->getPredicate()) {
5325   case ICmpInst::ICMP_SLT:
5326   case ICmpInst::ICMP_SLE:
5327     std::swap(LHS, RHS);
5328     LLVM_FALLTHROUGH;
5329   case ICmpInst::ICMP_SGT:
5330   case ICmpInst::ICMP_SGE:
5331     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5332     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5333     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5334       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5335       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5336       const SCEV *LA = getSCEV(TrueVal);
5337       const SCEV *RA = getSCEV(FalseVal);
5338       const SCEV *LDiff = getMinusSCEV(LA, LS);
5339       const SCEV *RDiff = getMinusSCEV(RA, RS);
5340       if (LDiff == RDiff)
5341         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5342       LDiff = getMinusSCEV(LA, RS);
5343       RDiff = getMinusSCEV(RA, LS);
5344       if (LDiff == RDiff)
5345         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5346     }
5347     break;
5348   case ICmpInst::ICMP_ULT:
5349   case ICmpInst::ICMP_ULE:
5350     std::swap(LHS, RHS);
5351     LLVM_FALLTHROUGH;
5352   case ICmpInst::ICMP_UGT:
5353   case ICmpInst::ICMP_UGE:
5354     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5355     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5356     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5357       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5358       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5359       const SCEV *LA = getSCEV(TrueVal);
5360       const SCEV *RA = getSCEV(FalseVal);
5361       const SCEV *LDiff = getMinusSCEV(LA, LS);
5362       const SCEV *RDiff = getMinusSCEV(RA, RS);
5363       if (LDiff == RDiff)
5364         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5365       LDiff = getMinusSCEV(LA, RS);
5366       RDiff = getMinusSCEV(RA, LS);
5367       if (LDiff == RDiff)
5368         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5369     }
5370     break;
5371   case ICmpInst::ICMP_NE:
5372     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5373     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5374         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5375       const SCEV *One = getOne(I->getType());
5376       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5377       const SCEV *LA = getSCEV(TrueVal);
5378       const SCEV *RA = getSCEV(FalseVal);
5379       const SCEV *LDiff = getMinusSCEV(LA, LS);
5380       const SCEV *RDiff = getMinusSCEV(RA, One);
5381       if (LDiff == RDiff)
5382         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5383     }
5384     break;
5385   case ICmpInst::ICMP_EQ:
5386     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5387     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5388         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5389       const SCEV *One = getOne(I->getType());
5390       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5391       const SCEV *LA = getSCEV(TrueVal);
5392       const SCEV *RA = getSCEV(FalseVal);
5393       const SCEV *LDiff = getMinusSCEV(LA, One);
5394       const SCEV *RDiff = getMinusSCEV(RA, LS);
5395       if (LDiff == RDiff)
5396         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5397     }
5398     break;
5399   default:
5400     break;
5401   }
5402 
5403   return getUnknown(I);
5404 }
5405 
5406 /// Expand GEP instructions into add and multiply operations. This allows them
5407 /// to be analyzed by regular SCEV code.
5408 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5409   // Don't attempt to analyze GEPs over unsized objects.
5410   if (!GEP->getSourceElementType()->isSized())
5411     return getUnknown(GEP);
5412 
5413   SmallVector<const SCEV *, 4> IndexExprs;
5414   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5415     IndexExprs.push_back(getSCEV(*Index));
5416   return getGEPExpr(GEP, IndexExprs);
5417 }
5418 
5419 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5420   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5421     return C->getAPInt().countTrailingZeros();
5422 
5423   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5424     return GetMinTrailingZeros(I->getOperand());
5425 
5426   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5427     return std::min(GetMinTrailingZeros(T->getOperand()),
5428                     (uint32_t)getTypeSizeInBits(T->getType()));
5429 
5430   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5431     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5432     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5433                ? getTypeSizeInBits(E->getType())
5434                : OpRes;
5435   }
5436 
5437   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5438     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5439     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5440                ? getTypeSizeInBits(E->getType())
5441                : OpRes;
5442   }
5443 
5444   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5445     // The result is the min of all operands results.
5446     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5447     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5448       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5449     return MinOpRes;
5450   }
5451 
5452   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5453     // The result is the sum of all operands results.
5454     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5455     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5456     for (unsigned i = 1, e = M->getNumOperands();
5457          SumOpRes != BitWidth && i != e; ++i)
5458       SumOpRes =
5459           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5460     return SumOpRes;
5461   }
5462 
5463   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5464     // The result is the min of all operands results.
5465     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5466     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5467       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5468     return MinOpRes;
5469   }
5470 
5471   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5472     // The result is the min of all operands results.
5473     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5474     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5475       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5476     return MinOpRes;
5477   }
5478 
5479   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5480     // The result is the min of all operands results.
5481     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5482     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5483       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5484     return MinOpRes;
5485   }
5486 
5487   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5488     // For a SCEVUnknown, ask ValueTracking.
5489     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5490     return Known.countMinTrailingZeros();
5491   }
5492 
5493   // SCEVUDivExpr
5494   return 0;
5495 }
5496 
5497 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5498   auto I = MinTrailingZerosCache.find(S);
5499   if (I != MinTrailingZerosCache.end())
5500     return I->second;
5501 
5502   uint32_t Result = GetMinTrailingZerosImpl(S);
5503   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5504   assert(InsertPair.second && "Should insert a new key");
5505   return InsertPair.first->second;
5506 }
5507 
5508 /// Helper method to assign a range to V from metadata present in the IR.
5509 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5510   if (Instruction *I = dyn_cast<Instruction>(V))
5511     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5512       return getConstantRangeFromMetadata(*MD);
5513 
5514   return None;
5515 }
5516 
5517 /// Determine the range for a particular SCEV.  If SignHint is
5518 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5519 /// with a "cleaner" unsigned (resp. signed) representation.
5520 const ConstantRange &
5521 ScalarEvolution::getRangeRef(const SCEV *S,
5522                              ScalarEvolution::RangeSignHint SignHint) {
5523   DenseMap<const SCEV *, ConstantRange> &Cache =
5524       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5525                                                        : SignedRanges;
5526   ConstantRange::PreferredRangeType RangeType =
5527       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5528           ? ConstantRange::Unsigned : ConstantRange::Signed;
5529 
5530   // See if we've computed this range already.
5531   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5532   if (I != Cache.end())
5533     return I->second;
5534 
5535   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5536     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5537 
5538   unsigned BitWidth = getTypeSizeInBits(S->getType());
5539   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5540   using OBO = OverflowingBinaryOperator;
5541 
5542   // If the value has known zeros, the maximum value will have those known zeros
5543   // as well.
5544   uint32_t TZ = GetMinTrailingZeros(S);
5545   if (TZ != 0) {
5546     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5547       ConservativeResult =
5548           ConstantRange(APInt::getMinValue(BitWidth),
5549                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5550     else
5551       ConservativeResult = ConstantRange(
5552           APInt::getSignedMinValue(BitWidth),
5553           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5554   }
5555 
5556   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5557     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5558     unsigned WrapType = OBO::AnyWrap;
5559     if (Add->hasNoSignedWrap())
5560       WrapType |= OBO::NoSignedWrap;
5561     if (Add->hasNoUnsignedWrap())
5562       WrapType |= OBO::NoUnsignedWrap;
5563     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5564       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5565                           WrapType, RangeType);
5566     return setRange(Add, SignHint,
5567                     ConservativeResult.intersectWith(X, RangeType));
5568   }
5569 
5570   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5571     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5572     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5573       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5574     return setRange(Mul, SignHint,
5575                     ConservativeResult.intersectWith(X, RangeType));
5576   }
5577 
5578   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5579     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5580     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5581       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5582     return setRange(SMax, SignHint,
5583                     ConservativeResult.intersectWith(X, RangeType));
5584   }
5585 
5586   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5587     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5588     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5589       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5590     return setRange(UMax, SignHint,
5591                     ConservativeResult.intersectWith(X, RangeType));
5592   }
5593 
5594   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5595     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5596     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5597       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5598     return setRange(SMin, SignHint,
5599                     ConservativeResult.intersectWith(X, RangeType));
5600   }
5601 
5602   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5603     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5604     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5605       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5606     return setRange(UMin, SignHint,
5607                     ConservativeResult.intersectWith(X, RangeType));
5608   }
5609 
5610   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5611     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5612     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5613     return setRange(UDiv, SignHint,
5614                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5615   }
5616 
5617   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5618     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5619     return setRange(ZExt, SignHint,
5620                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5621                                                      RangeType));
5622   }
5623 
5624   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5625     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5626     return setRange(SExt, SignHint,
5627                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5628                                                      RangeType));
5629   }
5630 
5631   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5632     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5633     return setRange(PtrToInt, SignHint, X);
5634   }
5635 
5636   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5637     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5638     return setRange(Trunc, SignHint,
5639                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5640                                                      RangeType));
5641   }
5642 
5643   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5644     // If there's no unsigned wrap, the value will never be less than its
5645     // initial value.
5646     if (AddRec->hasNoUnsignedWrap()) {
5647       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5648       if (!UnsignedMinValue.isNullValue())
5649         ConservativeResult = ConservativeResult.intersectWith(
5650             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5651     }
5652 
5653     // If there's no signed wrap, and all the operands except initial value have
5654     // the same sign or zero, the value won't ever be:
5655     // 1: smaller than initial value if operands are non negative,
5656     // 2: bigger than initial value if operands are non positive.
5657     // For both cases, value can not cross signed min/max boundary.
5658     if (AddRec->hasNoSignedWrap()) {
5659       bool AllNonNeg = true;
5660       bool AllNonPos = true;
5661       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5662         if (!isKnownNonNegative(AddRec->getOperand(i)))
5663           AllNonNeg = false;
5664         if (!isKnownNonPositive(AddRec->getOperand(i)))
5665           AllNonPos = false;
5666       }
5667       if (AllNonNeg)
5668         ConservativeResult = ConservativeResult.intersectWith(
5669             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5670                                        APInt::getSignedMinValue(BitWidth)),
5671             RangeType);
5672       else if (AllNonPos)
5673         ConservativeResult = ConservativeResult.intersectWith(
5674             ConstantRange::getNonEmpty(
5675                 APInt::getSignedMinValue(BitWidth),
5676                 getSignedRangeMax(AddRec->getStart()) + 1),
5677             RangeType);
5678     }
5679 
5680     // TODO: non-affine addrec
5681     if (AddRec->isAffine()) {
5682       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5683       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5684           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5685         auto RangeFromAffine = getRangeForAffineAR(
5686             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5687             BitWidth);
5688         ConservativeResult =
5689             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5690 
5691         auto RangeFromFactoring = getRangeViaFactoring(
5692             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5693             BitWidth);
5694         ConservativeResult =
5695             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5696       }
5697 
5698       // Now try symbolic BE count and more powerful methods.
5699       if (UseExpensiveRangeSharpening) {
5700         const SCEV *SymbolicMaxBECount =
5701             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5702         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5703             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5704             AddRec->hasNoSelfWrap()) {
5705           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5706               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5707           ConservativeResult =
5708               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5709         }
5710       }
5711     }
5712 
5713     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5714   }
5715 
5716   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5717     // Check if the IR explicitly contains !range metadata.
5718     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5719     if (MDRange.hasValue())
5720       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5721                                                             RangeType);
5722 
5723     // Split here to avoid paying the compile-time cost of calling both
5724     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5725     // if needed.
5726     const DataLayout &DL = getDataLayout();
5727     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5728       // For a SCEVUnknown, ask ValueTracking.
5729       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5730       if (Known.getBitWidth() != BitWidth)
5731         Known = Known.zextOrTrunc(BitWidth);
5732       // If Known does not result in full-set, intersect with it.
5733       if (Known.getMinValue() != Known.getMaxValue() + 1)
5734         ConservativeResult = ConservativeResult.intersectWith(
5735             ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5736             RangeType);
5737     } else {
5738       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5739              "generalize as needed!");
5740       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5741       // If the pointer size is larger than the index size type, this can cause
5742       // NS to be larger than BitWidth. So compensate for this.
5743       if (U->getType()->isPointerTy()) {
5744         unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5745         int ptrIdxDiff = ptrSize - BitWidth;
5746         if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5747           NS -= ptrIdxDiff;
5748       }
5749 
5750       if (NS > 1)
5751         ConservativeResult = ConservativeResult.intersectWith(
5752             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5753                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5754             RangeType);
5755     }
5756 
5757     // A range of Phi is a subset of union of all ranges of its input.
5758     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5759       // Make sure that we do not run over cycled Phis.
5760       if (PendingPhiRanges.insert(Phi).second) {
5761         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5762         for (auto &Op : Phi->operands()) {
5763           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5764           RangeFromOps = RangeFromOps.unionWith(OpRange);
5765           // No point to continue if we already have a full set.
5766           if (RangeFromOps.isFullSet())
5767             break;
5768         }
5769         ConservativeResult =
5770             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5771         bool Erased = PendingPhiRanges.erase(Phi);
5772         assert(Erased && "Failed to erase Phi properly?");
5773         (void) Erased;
5774       }
5775     }
5776 
5777     return setRange(U, SignHint, std::move(ConservativeResult));
5778   }
5779 
5780   return setRange(S, SignHint, std::move(ConservativeResult));
5781 }
5782 
5783 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5784 // values that the expression can take. Initially, the expression has a value
5785 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5786 // argument defines if we treat Step as signed or unsigned.
5787 static ConstantRange getRangeForAffineARHelper(APInt Step,
5788                                                const ConstantRange &StartRange,
5789                                                const APInt &MaxBECount,
5790                                                unsigned BitWidth, bool Signed) {
5791   // If either Step or MaxBECount is 0, then the expression won't change, and we
5792   // just need to return the initial range.
5793   if (Step == 0 || MaxBECount == 0)
5794     return StartRange;
5795 
5796   // If we don't know anything about the initial value (i.e. StartRange is
5797   // FullRange), then we don't know anything about the final range either.
5798   // Return FullRange.
5799   if (StartRange.isFullSet())
5800     return ConstantRange::getFull(BitWidth);
5801 
5802   // If Step is signed and negative, then we use its absolute value, but we also
5803   // note that we're moving in the opposite direction.
5804   bool Descending = Signed && Step.isNegative();
5805 
5806   if (Signed)
5807     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5808     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5809     // This equations hold true due to the well-defined wrap-around behavior of
5810     // APInt.
5811     Step = Step.abs();
5812 
5813   // Check if Offset is more than full span of BitWidth. If it is, the
5814   // expression is guaranteed to overflow.
5815   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5816     return ConstantRange::getFull(BitWidth);
5817 
5818   // Offset is by how much the expression can change. Checks above guarantee no
5819   // overflow here.
5820   APInt Offset = Step * MaxBECount;
5821 
5822   // Minimum value of the final range will match the minimal value of StartRange
5823   // if the expression is increasing and will be decreased by Offset otherwise.
5824   // Maximum value of the final range will match the maximal value of StartRange
5825   // if the expression is decreasing and will be increased by Offset otherwise.
5826   APInt StartLower = StartRange.getLower();
5827   APInt StartUpper = StartRange.getUpper() - 1;
5828   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5829                                    : (StartUpper + std::move(Offset));
5830 
5831   // It's possible that the new minimum/maximum value will fall into the initial
5832   // range (due to wrap around). This means that the expression can take any
5833   // value in this bitwidth, and we have to return full range.
5834   if (StartRange.contains(MovedBoundary))
5835     return ConstantRange::getFull(BitWidth);
5836 
5837   APInt NewLower =
5838       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5839   APInt NewUpper =
5840       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5841   NewUpper += 1;
5842 
5843   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5844   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5845 }
5846 
5847 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5848                                                    const SCEV *Step,
5849                                                    const SCEV *MaxBECount,
5850                                                    unsigned BitWidth) {
5851   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5852          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5853          "Precondition!");
5854 
5855   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5856   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5857 
5858   // First, consider step signed.
5859   ConstantRange StartSRange = getSignedRange(Start);
5860   ConstantRange StepSRange = getSignedRange(Step);
5861 
5862   // If Step can be both positive and negative, we need to find ranges for the
5863   // maximum absolute step values in both directions and union them.
5864   ConstantRange SR =
5865       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5866                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5867   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5868                                               StartSRange, MaxBECountValue,
5869                                               BitWidth, /* Signed = */ true));
5870 
5871   // Next, consider step unsigned.
5872   ConstantRange UR = getRangeForAffineARHelper(
5873       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5874       MaxBECountValue, BitWidth, /* Signed = */ false);
5875 
5876   // Finally, intersect signed and unsigned ranges.
5877   return SR.intersectWith(UR, ConstantRange::Smallest);
5878 }
5879 
5880 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
5881     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
5882     ScalarEvolution::RangeSignHint SignHint) {
5883   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
5884   assert(AddRec->hasNoSelfWrap() &&
5885          "This only works for non-self-wrapping AddRecs!");
5886   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
5887   const SCEV *Step = AddRec->getStepRecurrence(*this);
5888   // Only deal with constant step to save compile time.
5889   if (!isa<SCEVConstant>(Step))
5890     return ConstantRange::getFull(BitWidth);
5891   // Let's make sure that we can prove that we do not self-wrap during
5892   // MaxBECount iterations. We need this because MaxBECount is a maximum
5893   // iteration count estimate, and we might infer nw from some exit for which we
5894   // do not know max exit count (or any other side reasoning).
5895   // TODO: Turn into assert at some point.
5896   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
5897   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
5898   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
5899   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
5900   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
5901                                          MaxItersWithoutWrap))
5902     return ConstantRange::getFull(BitWidth);
5903 
5904   ICmpInst::Predicate LEPred =
5905       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
5906   ICmpInst::Predicate GEPred =
5907       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
5908   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
5909 
5910   // We know that there is no self-wrap. Let's take Start and End values and
5911   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
5912   // the iteration. They either lie inside the range [Min(Start, End),
5913   // Max(Start, End)] or outside it:
5914   //
5915   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
5916   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
5917   //
5918   // No self wrap flag guarantees that the intermediate values cannot be BOTH
5919   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
5920   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
5921   // Start <= End and step is positive, or Start >= End and step is negative.
5922   const SCEV *Start = AddRec->getStart();
5923   ConstantRange StartRange = getRangeRef(Start, SignHint);
5924   ConstantRange EndRange = getRangeRef(End, SignHint);
5925   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
5926   // If they already cover full iteration space, we will know nothing useful
5927   // even if we prove what we want to prove.
5928   if (RangeBetween.isFullSet())
5929     return RangeBetween;
5930   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
5931   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
5932                                : RangeBetween.isWrappedSet();
5933   if (IsWrappedSet)
5934     return ConstantRange::getFull(BitWidth);
5935 
5936   if (isKnownPositive(Step) &&
5937       isKnownPredicateViaConstantRanges(LEPred, Start, End))
5938     return RangeBetween;
5939   else if (isKnownNegative(Step) &&
5940            isKnownPredicateViaConstantRanges(GEPred, Start, End))
5941     return RangeBetween;
5942   return ConstantRange::getFull(BitWidth);
5943 }
5944 
5945 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5946                                                     const SCEV *Step,
5947                                                     const SCEV *MaxBECount,
5948                                                     unsigned BitWidth) {
5949   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5950   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5951 
5952   struct SelectPattern {
5953     Value *Condition = nullptr;
5954     APInt TrueValue;
5955     APInt FalseValue;
5956 
5957     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5958                            const SCEV *S) {
5959       Optional<unsigned> CastOp;
5960       APInt Offset(BitWidth, 0);
5961 
5962       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5963              "Should be!");
5964 
5965       // Peel off a constant offset:
5966       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5967         // In the future we could consider being smarter here and handle
5968         // {Start+Step,+,Step} too.
5969         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5970           return;
5971 
5972         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5973         S = SA->getOperand(1);
5974       }
5975 
5976       // Peel off a cast operation
5977       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
5978         CastOp = SCast->getSCEVType();
5979         S = SCast->getOperand();
5980       }
5981 
5982       using namespace llvm::PatternMatch;
5983 
5984       auto *SU = dyn_cast<SCEVUnknown>(S);
5985       const APInt *TrueVal, *FalseVal;
5986       if (!SU ||
5987           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5988                                           m_APInt(FalseVal)))) {
5989         Condition = nullptr;
5990         return;
5991       }
5992 
5993       TrueValue = *TrueVal;
5994       FalseValue = *FalseVal;
5995 
5996       // Re-apply the cast we peeled off earlier
5997       if (CastOp.hasValue())
5998         switch (*CastOp) {
5999         default:
6000           llvm_unreachable("Unknown SCEV cast type!");
6001 
6002         case scTruncate:
6003           TrueValue = TrueValue.trunc(BitWidth);
6004           FalseValue = FalseValue.trunc(BitWidth);
6005           break;
6006         case scZeroExtend:
6007           TrueValue = TrueValue.zext(BitWidth);
6008           FalseValue = FalseValue.zext(BitWidth);
6009           break;
6010         case scSignExtend:
6011           TrueValue = TrueValue.sext(BitWidth);
6012           FalseValue = FalseValue.sext(BitWidth);
6013           break;
6014         }
6015 
6016       // Re-apply the constant offset we peeled off earlier
6017       TrueValue += Offset;
6018       FalseValue += Offset;
6019     }
6020 
6021     bool isRecognized() { return Condition != nullptr; }
6022   };
6023 
6024   SelectPattern StartPattern(*this, BitWidth, Start);
6025   if (!StartPattern.isRecognized())
6026     return ConstantRange::getFull(BitWidth);
6027 
6028   SelectPattern StepPattern(*this, BitWidth, Step);
6029   if (!StepPattern.isRecognized())
6030     return ConstantRange::getFull(BitWidth);
6031 
6032   if (StartPattern.Condition != StepPattern.Condition) {
6033     // We don't handle this case today; but we could, by considering four
6034     // possibilities below instead of two. I'm not sure if there are cases where
6035     // that will help over what getRange already does, though.
6036     return ConstantRange::getFull(BitWidth);
6037   }
6038 
6039   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6040   // construct arbitrary general SCEV expressions here.  This function is called
6041   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6042   // say) can end up caching a suboptimal value.
6043 
6044   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6045   // C2352 and C2512 (otherwise it isn't needed).
6046 
6047   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6048   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6049   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6050   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6051 
6052   ConstantRange TrueRange =
6053       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6054   ConstantRange FalseRange =
6055       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6056 
6057   return TrueRange.unionWith(FalseRange);
6058 }
6059 
6060 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6061   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6062   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6063 
6064   // Return early if there are no flags to propagate to the SCEV.
6065   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6066   if (BinOp->hasNoUnsignedWrap())
6067     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6068   if (BinOp->hasNoSignedWrap())
6069     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6070   if (Flags == SCEV::FlagAnyWrap)
6071     return SCEV::FlagAnyWrap;
6072 
6073   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6074 }
6075 
6076 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6077   // Here we check that I is in the header of the innermost loop containing I,
6078   // since we only deal with instructions in the loop header. The actual loop we
6079   // need to check later will come from an add recurrence, but getting that
6080   // requires computing the SCEV of the operands, which can be expensive. This
6081   // check we can do cheaply to rule out some cases early.
6082   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6083   if (InnermostContainingLoop == nullptr ||
6084       InnermostContainingLoop->getHeader() != I->getParent())
6085     return false;
6086 
6087   // Only proceed if we can prove that I does not yield poison.
6088   if (!programUndefinedIfPoison(I))
6089     return false;
6090 
6091   // At this point we know that if I is executed, then it does not wrap
6092   // according to at least one of NSW or NUW. If I is not executed, then we do
6093   // not know if the calculation that I represents would wrap. Multiple
6094   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6095   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6096   // derived from other instructions that map to the same SCEV. We cannot make
6097   // that guarantee for cases where I is not executed. So we need to find the
6098   // loop that I is considered in relation to and prove that I is executed for
6099   // every iteration of that loop. That implies that the value that I
6100   // calculates does not wrap anywhere in the loop, so then we can apply the
6101   // flags to the SCEV.
6102   //
6103   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6104   // from different loops, so that we know which loop to prove that I is
6105   // executed in.
6106   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6107     // I could be an extractvalue from a call to an overflow intrinsic.
6108     // TODO: We can do better here in some cases.
6109     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6110       return false;
6111     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6112     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6113       bool AllOtherOpsLoopInvariant = true;
6114       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6115            ++OtherOpIndex) {
6116         if (OtherOpIndex != OpIndex) {
6117           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6118           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6119             AllOtherOpsLoopInvariant = false;
6120             break;
6121           }
6122         }
6123       }
6124       if (AllOtherOpsLoopInvariant &&
6125           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6126         return true;
6127     }
6128   }
6129   return false;
6130 }
6131 
6132 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6133   // If we know that \c I can never be poison period, then that's enough.
6134   if (isSCEVExprNeverPoison(I))
6135     return true;
6136 
6137   // For an add recurrence specifically, we assume that infinite loops without
6138   // side effects are undefined behavior, and then reason as follows:
6139   //
6140   // If the add recurrence is poison in any iteration, it is poison on all
6141   // future iterations (since incrementing poison yields poison). If the result
6142   // of the add recurrence is fed into the loop latch condition and the loop
6143   // does not contain any throws or exiting blocks other than the latch, we now
6144   // have the ability to "choose" whether the backedge is taken or not (by
6145   // choosing a sufficiently evil value for the poison feeding into the branch)
6146   // for every iteration including and after the one in which \p I first became
6147   // poison.  There are two possibilities (let's call the iteration in which \p
6148   // I first became poison as K):
6149   //
6150   //  1. In the set of iterations including and after K, the loop body executes
6151   //     no side effects.  In this case executing the backege an infinte number
6152   //     of times will yield undefined behavior.
6153   //
6154   //  2. In the set of iterations including and after K, the loop body executes
6155   //     at least one side effect.  In this case, that specific instance of side
6156   //     effect is control dependent on poison, which also yields undefined
6157   //     behavior.
6158 
6159   auto *ExitingBB = L->getExitingBlock();
6160   auto *LatchBB = L->getLoopLatch();
6161   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6162     return false;
6163 
6164   SmallPtrSet<const Instruction *, 16> Pushed;
6165   SmallVector<const Instruction *, 8> PoisonStack;
6166 
6167   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6168   // things that are known to be poison under that assumption go on the
6169   // PoisonStack.
6170   Pushed.insert(I);
6171   PoisonStack.push_back(I);
6172 
6173   bool LatchControlDependentOnPoison = false;
6174   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6175     const Instruction *Poison = PoisonStack.pop_back_val();
6176 
6177     for (auto *PoisonUser : Poison->users()) {
6178       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6179         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6180           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6181       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6182         assert(BI->isConditional() && "Only possibility!");
6183         if (BI->getParent() == LatchBB) {
6184           LatchControlDependentOnPoison = true;
6185           break;
6186         }
6187       }
6188     }
6189   }
6190 
6191   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6192 }
6193 
6194 ScalarEvolution::LoopProperties
6195 ScalarEvolution::getLoopProperties(const Loop *L) {
6196   using LoopProperties = ScalarEvolution::LoopProperties;
6197 
6198   auto Itr = LoopPropertiesCache.find(L);
6199   if (Itr == LoopPropertiesCache.end()) {
6200     auto HasSideEffects = [](Instruction *I) {
6201       if (auto *SI = dyn_cast<StoreInst>(I))
6202         return !SI->isSimple();
6203 
6204       return I->mayHaveSideEffects();
6205     };
6206 
6207     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6208                          /*HasNoSideEffects*/ true};
6209 
6210     for (auto *BB : L->getBlocks())
6211       for (auto &I : *BB) {
6212         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6213           LP.HasNoAbnormalExits = false;
6214         if (HasSideEffects(&I))
6215           LP.HasNoSideEffects = false;
6216         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6217           break; // We're already as pessimistic as we can get.
6218       }
6219 
6220     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6221     assert(InsertPair.second && "We just checked!");
6222     Itr = InsertPair.first;
6223   }
6224 
6225   return Itr->second;
6226 }
6227 
6228 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6229   if (!isSCEVable(V->getType()))
6230     return getUnknown(V);
6231 
6232   if (Instruction *I = dyn_cast<Instruction>(V)) {
6233     // Don't attempt to analyze instructions in blocks that aren't
6234     // reachable. Such instructions don't matter, and they aren't required
6235     // to obey basic rules for definitions dominating uses which this
6236     // analysis depends on.
6237     if (!DT.isReachableFromEntry(I->getParent()))
6238       return getUnknown(UndefValue::get(V->getType()));
6239   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6240     return getConstant(CI);
6241   else if (isa<ConstantPointerNull>(V))
6242     // FIXME: we shouldn't special-case null pointer constant.
6243     return getZero(V->getType());
6244   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6245     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6246   else if (!isa<ConstantExpr>(V))
6247     return getUnknown(V);
6248 
6249   Operator *U = cast<Operator>(V);
6250   if (auto BO = MatchBinaryOp(U, DT)) {
6251     switch (BO->Opcode) {
6252     case Instruction::Add: {
6253       // The simple thing to do would be to just call getSCEV on both operands
6254       // and call getAddExpr with the result. However if we're looking at a
6255       // bunch of things all added together, this can be quite inefficient,
6256       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6257       // Instead, gather up all the operands and make a single getAddExpr call.
6258       // LLVM IR canonical form means we need only traverse the left operands.
6259       SmallVector<const SCEV *, 4> AddOps;
6260       do {
6261         if (BO->Op) {
6262           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6263             AddOps.push_back(OpSCEV);
6264             break;
6265           }
6266 
6267           // If a NUW or NSW flag can be applied to the SCEV for this
6268           // addition, then compute the SCEV for this addition by itself
6269           // with a separate call to getAddExpr. We need to do that
6270           // instead of pushing the operands of the addition onto AddOps,
6271           // since the flags are only known to apply to this particular
6272           // addition - they may not apply to other additions that can be
6273           // formed with operands from AddOps.
6274           const SCEV *RHS = getSCEV(BO->RHS);
6275           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6276           if (Flags != SCEV::FlagAnyWrap) {
6277             const SCEV *LHS = getSCEV(BO->LHS);
6278             if (BO->Opcode == Instruction::Sub)
6279               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6280             else
6281               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6282             break;
6283           }
6284         }
6285 
6286         if (BO->Opcode == Instruction::Sub)
6287           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6288         else
6289           AddOps.push_back(getSCEV(BO->RHS));
6290 
6291         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6292         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6293                        NewBO->Opcode != Instruction::Sub)) {
6294           AddOps.push_back(getSCEV(BO->LHS));
6295           break;
6296         }
6297         BO = NewBO;
6298       } while (true);
6299 
6300       return getAddExpr(AddOps);
6301     }
6302 
6303     case Instruction::Mul: {
6304       SmallVector<const SCEV *, 4> MulOps;
6305       do {
6306         if (BO->Op) {
6307           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6308             MulOps.push_back(OpSCEV);
6309             break;
6310           }
6311 
6312           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6313           if (Flags != SCEV::FlagAnyWrap) {
6314             MulOps.push_back(
6315                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6316             break;
6317           }
6318         }
6319 
6320         MulOps.push_back(getSCEV(BO->RHS));
6321         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6322         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6323           MulOps.push_back(getSCEV(BO->LHS));
6324           break;
6325         }
6326         BO = NewBO;
6327       } while (true);
6328 
6329       return getMulExpr(MulOps);
6330     }
6331     case Instruction::UDiv:
6332       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6333     case Instruction::URem:
6334       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6335     case Instruction::Sub: {
6336       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6337       if (BO->Op)
6338         Flags = getNoWrapFlagsFromUB(BO->Op);
6339       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6340     }
6341     case Instruction::And:
6342       // For an expression like x&255 that merely masks off the high bits,
6343       // use zext(trunc(x)) as the SCEV expression.
6344       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6345         if (CI->isZero())
6346           return getSCEV(BO->RHS);
6347         if (CI->isMinusOne())
6348           return getSCEV(BO->LHS);
6349         const APInt &A = CI->getValue();
6350 
6351         // Instcombine's ShrinkDemandedConstant may strip bits out of
6352         // constants, obscuring what would otherwise be a low-bits mask.
6353         // Use computeKnownBits to compute what ShrinkDemandedConstant
6354         // knew about to reconstruct a low-bits mask value.
6355         unsigned LZ = A.countLeadingZeros();
6356         unsigned TZ = A.countTrailingZeros();
6357         unsigned BitWidth = A.getBitWidth();
6358         KnownBits Known(BitWidth);
6359         computeKnownBits(BO->LHS, Known, getDataLayout(),
6360                          0, &AC, nullptr, &DT);
6361 
6362         APInt EffectiveMask =
6363             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6364         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6365           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6366           const SCEV *LHS = getSCEV(BO->LHS);
6367           const SCEV *ShiftedLHS = nullptr;
6368           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6369             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6370               // For an expression like (x * 8) & 8, simplify the multiply.
6371               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6372               unsigned GCD = std::min(MulZeros, TZ);
6373               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6374               SmallVector<const SCEV*, 4> MulOps;
6375               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6376               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6377               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6378               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6379             }
6380           }
6381           if (!ShiftedLHS)
6382             ShiftedLHS = getUDivExpr(LHS, MulCount);
6383           return getMulExpr(
6384               getZeroExtendExpr(
6385                   getTruncateExpr(ShiftedLHS,
6386                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6387                   BO->LHS->getType()),
6388               MulCount);
6389         }
6390       }
6391       break;
6392 
6393     case Instruction::Or:
6394       // If the RHS of the Or is a constant, we may have something like:
6395       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6396       // optimizations will transparently handle this case.
6397       //
6398       // In order for this transformation to be safe, the LHS must be of the
6399       // form X*(2^n) and the Or constant must be less than 2^n.
6400       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6401         const SCEV *LHS = getSCEV(BO->LHS);
6402         const APInt &CIVal = CI->getValue();
6403         if (GetMinTrailingZeros(LHS) >=
6404             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6405           // Build a plain add SCEV.
6406           return getAddExpr(LHS, getSCEV(CI),
6407                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6408         }
6409       }
6410       break;
6411 
6412     case Instruction::Xor:
6413       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6414         // If the RHS of xor is -1, then this is a not operation.
6415         if (CI->isMinusOne())
6416           return getNotSCEV(getSCEV(BO->LHS));
6417 
6418         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6419         // This is a variant of the check for xor with -1, and it handles
6420         // the case where instcombine has trimmed non-demanded bits out
6421         // of an xor with -1.
6422         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6423           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6424             if (LBO->getOpcode() == Instruction::And &&
6425                 LCI->getValue() == CI->getValue())
6426               if (const SCEVZeroExtendExpr *Z =
6427                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6428                 Type *UTy = BO->LHS->getType();
6429                 const SCEV *Z0 = Z->getOperand();
6430                 Type *Z0Ty = Z0->getType();
6431                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6432 
6433                 // If C is a low-bits mask, the zero extend is serving to
6434                 // mask off the high bits. Complement the operand and
6435                 // re-apply the zext.
6436                 if (CI->getValue().isMask(Z0TySize))
6437                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6438 
6439                 // If C is a single bit, it may be in the sign-bit position
6440                 // before the zero-extend. In this case, represent the xor
6441                 // using an add, which is equivalent, and re-apply the zext.
6442                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6443                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6444                     Trunc.isSignMask())
6445                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6446                                            UTy);
6447               }
6448       }
6449       break;
6450 
6451     case Instruction::Shl:
6452       // Turn shift left of a constant amount into a multiply.
6453       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6454         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6455 
6456         // If the shift count is not less than the bitwidth, the result of
6457         // the shift is undefined. Don't try to analyze it, because the
6458         // resolution chosen here may differ from the resolution chosen in
6459         // other parts of the compiler.
6460         if (SA->getValue().uge(BitWidth))
6461           break;
6462 
6463         // We can safely preserve the nuw flag in all cases. It's also safe to
6464         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6465         // requires special handling. It can be preserved as long as we're not
6466         // left shifting by bitwidth - 1.
6467         auto Flags = SCEV::FlagAnyWrap;
6468         if (BO->Op) {
6469           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6470           if ((MulFlags & SCEV::FlagNSW) &&
6471               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6472             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6473           if (MulFlags & SCEV::FlagNUW)
6474             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6475         }
6476 
6477         Constant *X = ConstantInt::get(
6478             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6479         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6480       }
6481       break;
6482 
6483     case Instruction::AShr: {
6484       // AShr X, C, where C is a constant.
6485       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6486       if (!CI)
6487         break;
6488 
6489       Type *OuterTy = BO->LHS->getType();
6490       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6491       // If the shift count is not less than the bitwidth, the result of
6492       // the shift is undefined. Don't try to analyze it, because the
6493       // resolution chosen here may differ from the resolution chosen in
6494       // other parts of the compiler.
6495       if (CI->getValue().uge(BitWidth))
6496         break;
6497 
6498       if (CI->isZero())
6499         return getSCEV(BO->LHS); // shift by zero --> noop
6500 
6501       uint64_t AShrAmt = CI->getZExtValue();
6502       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6503 
6504       Operator *L = dyn_cast<Operator>(BO->LHS);
6505       if (L && L->getOpcode() == Instruction::Shl) {
6506         // X = Shl A, n
6507         // Y = AShr X, m
6508         // Both n and m are constant.
6509 
6510         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6511         if (L->getOperand(1) == BO->RHS)
6512           // For a two-shift sext-inreg, i.e. n = m,
6513           // use sext(trunc(x)) as the SCEV expression.
6514           return getSignExtendExpr(
6515               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6516 
6517         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6518         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6519           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6520           if (ShlAmt > AShrAmt) {
6521             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6522             // expression. We already checked that ShlAmt < BitWidth, so
6523             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6524             // ShlAmt - AShrAmt < Amt.
6525             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6526                                             ShlAmt - AShrAmt);
6527             return getSignExtendExpr(
6528                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6529                 getConstant(Mul)), OuterTy);
6530           }
6531         }
6532       }
6533       if (BO->IsExact) {
6534         // Given exact arithmetic in-bounds right-shift by a constant,
6535         // we can lower it into:  (abs(x) EXACT/u (1<<C)) * signum(x)
6536         const SCEV *X = getSCEV(BO->LHS);
6537         const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false);
6538         APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt);
6539         const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult));
6540         return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW);
6541       }
6542       break;
6543     }
6544     }
6545   }
6546 
6547   switch (U->getOpcode()) {
6548   case Instruction::Trunc:
6549     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6550 
6551   case Instruction::ZExt:
6552     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6553 
6554   case Instruction::SExt:
6555     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6556       // The NSW flag of a subtract does not always survive the conversion to
6557       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6558       // more likely to preserve NSW and allow later AddRec optimisations.
6559       //
6560       // NOTE: This is effectively duplicating this logic from getSignExtend:
6561       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6562       // but by that point the NSW information has potentially been lost.
6563       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6564         Type *Ty = U->getType();
6565         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6566         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6567         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6568       }
6569     }
6570     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6571 
6572   case Instruction::BitCast:
6573     // BitCasts are no-op casts so we just eliminate the cast.
6574     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6575       return getSCEV(U->getOperand(0));
6576     break;
6577 
6578   case Instruction::PtrToInt: {
6579     // Pointer to integer cast is straight-forward, so do model it.
6580     Value *Ptr = U->getOperand(0);
6581     const SCEV *Op = getSCEV(Ptr);
6582     Type *DstIntTy = U->getType();
6583     // SCEV doesn't have constant pointer expression type, but it supports
6584     // nullptr constant (and only that one), which is modelled in SCEV as a
6585     // zero integer constant. So just skip the ptrtoint cast for constants.
6586     if (isa<SCEVConstant>(Op))
6587       return getTruncateOrZeroExtend(Op, DstIntTy);
6588     Type *PtrTy = Ptr->getType();
6589     Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy);
6590     // But only if effective SCEV (integer) type is wide enough to represent
6591     // all possible pointer values.
6592     if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) !=
6593         getDataLayout().getTypeSizeInBits(IntPtrTy))
6594       return getUnknown(V);
6595     return getPtrToIntExpr(Op, DstIntTy);
6596   }
6597   case Instruction::IntToPtr:
6598     // Just don't deal with inttoptr casts.
6599     return getUnknown(V);
6600 
6601   case Instruction::SDiv:
6602     // If both operands are non-negative, this is just an udiv.
6603     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6604         isKnownNonNegative(getSCEV(U->getOperand(1))))
6605       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6606     break;
6607 
6608   case Instruction::SRem:
6609     // If both operands are non-negative, this is just an urem.
6610     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6611         isKnownNonNegative(getSCEV(U->getOperand(1))))
6612       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6613     break;
6614 
6615   case Instruction::GetElementPtr:
6616     return createNodeForGEP(cast<GEPOperator>(U));
6617 
6618   case Instruction::PHI:
6619     return createNodeForPHI(cast<PHINode>(U));
6620 
6621   case Instruction::Select:
6622     // U can also be a select constant expr, which let fall through.  Since
6623     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6624     // constant expressions cannot have instructions as operands, we'd have
6625     // returned getUnknown for a select constant expressions anyway.
6626     if (isa<Instruction>(U))
6627       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6628                                       U->getOperand(1), U->getOperand(2));
6629     break;
6630 
6631   case Instruction::Call:
6632   case Instruction::Invoke:
6633     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6634       return getSCEV(RV);
6635 
6636     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6637       switch (II->getIntrinsicID()) {
6638       case Intrinsic::abs:
6639         return getAbsExpr(
6640             getSCEV(II->getArgOperand(0)),
6641             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6642       case Intrinsic::umax:
6643         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6644                            getSCEV(II->getArgOperand(1)));
6645       case Intrinsic::umin:
6646         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6647                            getSCEV(II->getArgOperand(1)));
6648       case Intrinsic::smax:
6649         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6650                            getSCEV(II->getArgOperand(1)));
6651       case Intrinsic::smin:
6652         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6653                            getSCEV(II->getArgOperand(1)));
6654       case Intrinsic::usub_sat: {
6655         const SCEV *X = getSCEV(II->getArgOperand(0));
6656         const SCEV *Y = getSCEV(II->getArgOperand(1));
6657         const SCEV *ClampedY = getUMinExpr(X, Y);
6658         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6659       }
6660       case Intrinsic::uadd_sat: {
6661         const SCEV *X = getSCEV(II->getArgOperand(0));
6662         const SCEV *Y = getSCEV(II->getArgOperand(1));
6663         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6664         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6665       }
6666       default:
6667         break;
6668       }
6669     }
6670     break;
6671   }
6672 
6673   return getUnknown(V);
6674 }
6675 
6676 //===----------------------------------------------------------------------===//
6677 //                   Iteration Count Computation Code
6678 //
6679 
6680 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6681   if (!ExitCount)
6682     return 0;
6683 
6684   ConstantInt *ExitConst = ExitCount->getValue();
6685 
6686   // Guard against huge trip counts.
6687   if (ExitConst->getValue().getActiveBits() > 32)
6688     return 0;
6689 
6690   // In case of integer overflow, this returns 0, which is correct.
6691   return ((unsigned)ExitConst->getZExtValue()) + 1;
6692 }
6693 
6694 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6695   if (BasicBlock *ExitingBB = L->getExitingBlock())
6696     return getSmallConstantTripCount(L, ExitingBB);
6697 
6698   // No trip count information for multiple exits.
6699   return 0;
6700 }
6701 
6702 unsigned
6703 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6704                                            const BasicBlock *ExitingBlock) {
6705   assert(ExitingBlock && "Must pass a non-null exiting block!");
6706   assert(L->isLoopExiting(ExitingBlock) &&
6707          "Exiting block must actually branch out of the loop!");
6708   const SCEVConstant *ExitCount =
6709       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6710   return getConstantTripCount(ExitCount);
6711 }
6712 
6713 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6714   const auto *MaxExitCount =
6715       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6716   return getConstantTripCount(MaxExitCount);
6717 }
6718 
6719 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6720   if (BasicBlock *ExitingBB = L->getExitingBlock())
6721     return getSmallConstantTripMultiple(L, ExitingBB);
6722 
6723   // No trip multiple information for multiple exits.
6724   return 0;
6725 }
6726 
6727 /// Returns the largest constant divisor of the trip count of this loop as a
6728 /// normal unsigned value, if possible. This means that the actual trip count is
6729 /// always a multiple of the returned value (don't forget the trip count could
6730 /// very well be zero as well!).
6731 ///
6732 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6733 /// multiple of a constant (which is also the case if the trip count is simply
6734 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6735 /// if the trip count is very large (>= 2^32).
6736 ///
6737 /// As explained in the comments for getSmallConstantTripCount, this assumes
6738 /// that control exits the loop via ExitingBlock.
6739 unsigned
6740 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6741                                               const BasicBlock *ExitingBlock) {
6742   assert(ExitingBlock && "Must pass a non-null exiting block!");
6743   assert(L->isLoopExiting(ExitingBlock) &&
6744          "Exiting block must actually branch out of the loop!");
6745   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6746   if (ExitCount == getCouldNotCompute())
6747     return 1;
6748 
6749   // Get the trip count from the BE count by adding 1.
6750   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6751 
6752   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6753   if (!TC)
6754     // Attempt to factor more general cases. Returns the greatest power of
6755     // two divisor. If overflow happens, the trip count expression is still
6756     // divisible by the greatest power of 2 divisor returned.
6757     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6758 
6759   ConstantInt *Result = TC->getValue();
6760 
6761   // Guard against huge trip counts (this requires checking
6762   // for zero to handle the case where the trip count == -1 and the
6763   // addition wraps).
6764   if (!Result || Result->getValue().getActiveBits() > 32 ||
6765       Result->getValue().getActiveBits() == 0)
6766     return 1;
6767 
6768   return (unsigned)Result->getZExtValue();
6769 }
6770 
6771 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6772                                           const BasicBlock *ExitingBlock,
6773                                           ExitCountKind Kind) {
6774   switch (Kind) {
6775   case Exact:
6776   case SymbolicMaximum:
6777     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6778   case ConstantMaximum:
6779     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
6780   };
6781   llvm_unreachable("Invalid ExitCountKind!");
6782 }
6783 
6784 const SCEV *
6785 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6786                                                  SCEVUnionPredicate &Preds) {
6787   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6788 }
6789 
6790 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6791                                                    ExitCountKind Kind) {
6792   switch (Kind) {
6793   case Exact:
6794     return getBackedgeTakenInfo(L).getExact(L, this);
6795   case ConstantMaximum:
6796     return getBackedgeTakenInfo(L).getConstantMax(this);
6797   case SymbolicMaximum:
6798     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
6799   };
6800   llvm_unreachable("Invalid ExitCountKind!");
6801 }
6802 
6803 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6804   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
6805 }
6806 
6807 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6808 static void
6809 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6810   BasicBlock *Header = L->getHeader();
6811 
6812   // Push all Loop-header PHIs onto the Worklist stack.
6813   for (PHINode &PN : Header->phis())
6814     Worklist.push_back(&PN);
6815 }
6816 
6817 const ScalarEvolution::BackedgeTakenInfo &
6818 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6819   auto &BTI = getBackedgeTakenInfo(L);
6820   if (BTI.hasFullInfo())
6821     return BTI;
6822 
6823   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6824 
6825   if (!Pair.second)
6826     return Pair.first->second;
6827 
6828   BackedgeTakenInfo Result =
6829       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6830 
6831   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6832 }
6833 
6834 ScalarEvolution::BackedgeTakenInfo &
6835 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6836   // Initially insert an invalid entry for this loop. If the insertion
6837   // succeeds, proceed to actually compute a backedge-taken count and
6838   // update the value. The temporary CouldNotCompute value tells SCEV
6839   // code elsewhere that it shouldn't attempt to request a new
6840   // backedge-taken count, which could result in infinite recursion.
6841   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6842       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6843   if (!Pair.second)
6844     return Pair.first->second;
6845 
6846   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6847   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6848   // must be cleared in this scope.
6849   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6850 
6851   // In product build, there are no usage of statistic.
6852   (void)NumTripCountsComputed;
6853   (void)NumTripCountsNotComputed;
6854 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6855   const SCEV *BEExact = Result.getExact(L, this);
6856   if (BEExact != getCouldNotCompute()) {
6857     assert(isLoopInvariant(BEExact, L) &&
6858            isLoopInvariant(Result.getConstantMax(this), L) &&
6859            "Computed backedge-taken count isn't loop invariant for loop!");
6860     ++NumTripCountsComputed;
6861   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
6862              isa<PHINode>(L->getHeader()->begin())) {
6863     // Only count loops that have phi nodes as not being computable.
6864     ++NumTripCountsNotComputed;
6865   }
6866 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6867 
6868   // Now that we know more about the trip count for this loop, forget any
6869   // existing SCEV values for PHI nodes in this loop since they are only
6870   // conservative estimates made without the benefit of trip count
6871   // information. This is similar to the code in forgetLoop, except that
6872   // it handles SCEVUnknown PHI nodes specially.
6873   if (Result.hasAnyInfo()) {
6874     SmallVector<Instruction *, 16> Worklist;
6875     PushLoopPHIs(L, Worklist);
6876 
6877     SmallPtrSet<Instruction *, 8> Discovered;
6878     while (!Worklist.empty()) {
6879       Instruction *I = Worklist.pop_back_val();
6880 
6881       ValueExprMapType::iterator It =
6882         ValueExprMap.find_as(static_cast<Value *>(I));
6883       if (It != ValueExprMap.end()) {
6884         const SCEV *Old = It->second;
6885 
6886         // SCEVUnknown for a PHI either means that it has an unrecognized
6887         // structure, or it's a PHI that's in the progress of being computed
6888         // by createNodeForPHI.  In the former case, additional loop trip
6889         // count information isn't going to change anything. In the later
6890         // case, createNodeForPHI will perform the necessary updates on its
6891         // own when it gets to that point.
6892         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6893           eraseValueFromMap(It->first);
6894           forgetMemoizedResults(Old);
6895         }
6896         if (PHINode *PN = dyn_cast<PHINode>(I))
6897           ConstantEvolutionLoopExitValue.erase(PN);
6898       }
6899 
6900       // Since we don't need to invalidate anything for correctness and we're
6901       // only invalidating to make SCEV's results more precise, we get to stop
6902       // early to avoid invalidating too much.  This is especially important in
6903       // cases like:
6904       //
6905       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6906       // loop0:
6907       //   %pn0 = phi
6908       //   ...
6909       // loop1:
6910       //   %pn1 = phi
6911       //   ...
6912       //
6913       // where both loop0 and loop1's backedge taken count uses the SCEV
6914       // expression for %v.  If we don't have the early stop below then in cases
6915       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6916       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6917       // count for loop1, effectively nullifying SCEV's trip count cache.
6918       for (auto *U : I->users())
6919         if (auto *I = dyn_cast<Instruction>(U)) {
6920           auto *LoopForUser = LI.getLoopFor(I->getParent());
6921           if (LoopForUser && L->contains(LoopForUser) &&
6922               Discovered.insert(I).second)
6923             Worklist.push_back(I);
6924         }
6925     }
6926   }
6927 
6928   // Re-lookup the insert position, since the call to
6929   // computeBackedgeTakenCount above could result in a
6930   // recusive call to getBackedgeTakenInfo (on a different
6931   // loop), which would invalidate the iterator computed
6932   // earlier.
6933   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6934 }
6935 
6936 void ScalarEvolution::forgetAllLoops() {
6937   // This method is intended to forget all info about loops. It should
6938   // invalidate caches as if the following happened:
6939   // - The trip counts of all loops have changed arbitrarily
6940   // - Every llvm::Value has been updated in place to produce a different
6941   // result.
6942   BackedgeTakenCounts.clear();
6943   PredicatedBackedgeTakenCounts.clear();
6944   LoopPropertiesCache.clear();
6945   ConstantEvolutionLoopExitValue.clear();
6946   ValueExprMap.clear();
6947   ValuesAtScopes.clear();
6948   LoopDispositions.clear();
6949   BlockDispositions.clear();
6950   UnsignedRanges.clear();
6951   SignedRanges.clear();
6952   ExprValueMap.clear();
6953   HasRecMap.clear();
6954   MinTrailingZerosCache.clear();
6955   PredicatedSCEVRewrites.clear();
6956 }
6957 
6958 void ScalarEvolution::forgetLoop(const Loop *L) {
6959   // Drop any stored trip count value.
6960   auto RemoveLoopFromBackedgeMap =
6961       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6962         auto BTCPos = Map.find(L);
6963         if (BTCPos != Map.end()) {
6964           BTCPos->second.clear();
6965           Map.erase(BTCPos);
6966         }
6967       };
6968 
6969   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6970   SmallVector<Instruction *, 32> Worklist;
6971   SmallPtrSet<Instruction *, 16> Visited;
6972 
6973   // Iterate over all the loops and sub-loops to drop SCEV information.
6974   while (!LoopWorklist.empty()) {
6975     auto *CurrL = LoopWorklist.pop_back_val();
6976 
6977     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6978     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6979 
6980     // Drop information about predicated SCEV rewrites for this loop.
6981     for (auto I = PredicatedSCEVRewrites.begin();
6982          I != PredicatedSCEVRewrites.end();) {
6983       std::pair<const SCEV *, const Loop *> Entry = I->first;
6984       if (Entry.second == CurrL)
6985         PredicatedSCEVRewrites.erase(I++);
6986       else
6987         ++I;
6988     }
6989 
6990     auto LoopUsersItr = LoopUsers.find(CurrL);
6991     if (LoopUsersItr != LoopUsers.end()) {
6992       for (auto *S : LoopUsersItr->second)
6993         forgetMemoizedResults(S);
6994       LoopUsers.erase(LoopUsersItr);
6995     }
6996 
6997     // Drop information about expressions based on loop-header PHIs.
6998     PushLoopPHIs(CurrL, Worklist);
6999 
7000     while (!Worklist.empty()) {
7001       Instruction *I = Worklist.pop_back_val();
7002       if (!Visited.insert(I).second)
7003         continue;
7004 
7005       ValueExprMapType::iterator It =
7006           ValueExprMap.find_as(static_cast<Value *>(I));
7007       if (It != ValueExprMap.end()) {
7008         eraseValueFromMap(It->first);
7009         forgetMemoizedResults(It->second);
7010         if (PHINode *PN = dyn_cast<PHINode>(I))
7011           ConstantEvolutionLoopExitValue.erase(PN);
7012       }
7013 
7014       PushDefUseChildren(I, Worklist);
7015     }
7016 
7017     LoopPropertiesCache.erase(CurrL);
7018     // Forget all contained loops too, to avoid dangling entries in the
7019     // ValuesAtScopes map.
7020     LoopWorklist.append(CurrL->begin(), CurrL->end());
7021   }
7022 }
7023 
7024 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7025   while (Loop *Parent = L->getParentLoop())
7026     L = Parent;
7027   forgetLoop(L);
7028 }
7029 
7030 void ScalarEvolution::forgetValue(Value *V) {
7031   Instruction *I = dyn_cast<Instruction>(V);
7032   if (!I) return;
7033 
7034   // Drop information about expressions based on loop-header PHIs.
7035   SmallVector<Instruction *, 16> Worklist;
7036   Worklist.push_back(I);
7037 
7038   SmallPtrSet<Instruction *, 8> Visited;
7039   while (!Worklist.empty()) {
7040     I = Worklist.pop_back_val();
7041     if (!Visited.insert(I).second)
7042       continue;
7043 
7044     ValueExprMapType::iterator It =
7045       ValueExprMap.find_as(static_cast<Value *>(I));
7046     if (It != ValueExprMap.end()) {
7047       eraseValueFromMap(It->first);
7048       forgetMemoizedResults(It->second);
7049       if (PHINode *PN = dyn_cast<PHINode>(I))
7050         ConstantEvolutionLoopExitValue.erase(PN);
7051     }
7052 
7053     PushDefUseChildren(I, Worklist);
7054   }
7055 }
7056 
7057 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7058   LoopDispositions.clear();
7059 }
7060 
7061 /// Get the exact loop backedge taken count considering all loop exits. A
7062 /// computable result can only be returned for loops with all exiting blocks
7063 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7064 /// is never skipped. This is a valid assumption as long as the loop exits via
7065 /// that test. For precise results, it is the caller's responsibility to specify
7066 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7067 const SCEV *
7068 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7069                                              SCEVUnionPredicate *Preds) const {
7070   // If any exits were not computable, the loop is not computable.
7071   if (!isComplete() || ExitNotTaken.empty())
7072     return SE->getCouldNotCompute();
7073 
7074   const BasicBlock *Latch = L->getLoopLatch();
7075   // All exiting blocks we have collected must dominate the only backedge.
7076   if (!Latch)
7077     return SE->getCouldNotCompute();
7078 
7079   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7080   // count is simply a minimum out of all these calculated exit counts.
7081   SmallVector<const SCEV *, 2> Ops;
7082   for (auto &ENT : ExitNotTaken) {
7083     const SCEV *BECount = ENT.ExactNotTaken;
7084     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7085     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7086            "We should only have known counts for exiting blocks that dominate "
7087            "latch!");
7088 
7089     Ops.push_back(BECount);
7090 
7091     if (Preds && !ENT.hasAlwaysTruePredicate())
7092       Preds->add(ENT.Predicate.get());
7093 
7094     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7095            "Predicate should be always true!");
7096   }
7097 
7098   return SE->getUMinFromMismatchedTypes(Ops);
7099 }
7100 
7101 /// Get the exact not taken count for this loop exit.
7102 const SCEV *
7103 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7104                                              ScalarEvolution *SE) const {
7105   for (auto &ENT : ExitNotTaken)
7106     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7107       return ENT.ExactNotTaken;
7108 
7109   return SE->getCouldNotCompute();
7110 }
7111 
7112 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7113     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7114   for (auto &ENT : ExitNotTaken)
7115     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7116       return ENT.MaxNotTaken;
7117 
7118   return SE->getCouldNotCompute();
7119 }
7120 
7121 /// getConstantMax - Get the constant max backedge taken count for the loop.
7122 const SCEV *
7123 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7124   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7125     return !ENT.hasAlwaysTruePredicate();
7126   };
7127 
7128   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7129     return SE->getCouldNotCompute();
7130 
7131   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7132           isa<SCEVConstant>(getConstantMax())) &&
7133          "No point in having a non-constant max backedge taken count!");
7134   return getConstantMax();
7135 }
7136 
7137 const SCEV *
7138 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7139                                                    ScalarEvolution *SE) {
7140   if (!SymbolicMax)
7141     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7142   return SymbolicMax;
7143 }
7144 
7145 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7146     ScalarEvolution *SE) const {
7147   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7148     return !ENT.hasAlwaysTruePredicate();
7149   };
7150   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7151 }
7152 
7153 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7154                                                     ScalarEvolution *SE) const {
7155   if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7156       SE->hasOperand(getConstantMax(), S))
7157     return true;
7158 
7159   for (auto &ENT : ExitNotTaken)
7160     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7161         SE->hasOperand(ENT.ExactNotTaken, S))
7162       return true;
7163 
7164   return false;
7165 }
7166 
7167 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7168     : ExactNotTaken(E), MaxNotTaken(E) {
7169   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7170           isa<SCEVConstant>(MaxNotTaken)) &&
7171          "No point in having a non-constant max backedge taken count!");
7172 }
7173 
7174 ScalarEvolution::ExitLimit::ExitLimit(
7175     const SCEV *E, const SCEV *M, bool MaxOrZero,
7176     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7177     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7178   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7179           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7180          "Exact is not allowed to be less precise than Max");
7181   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7182           isa<SCEVConstant>(MaxNotTaken)) &&
7183          "No point in having a non-constant max backedge taken count!");
7184   for (auto *PredSet : PredSetList)
7185     for (auto *P : *PredSet)
7186       addPredicate(P);
7187 }
7188 
7189 ScalarEvolution::ExitLimit::ExitLimit(
7190     const SCEV *E, const SCEV *M, bool MaxOrZero,
7191     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7192     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7193   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7194           isa<SCEVConstant>(MaxNotTaken)) &&
7195          "No point in having a non-constant max backedge taken count!");
7196 }
7197 
7198 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7199                                       bool MaxOrZero)
7200     : ExitLimit(E, M, MaxOrZero, None) {
7201   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7202           isa<SCEVConstant>(MaxNotTaken)) &&
7203          "No point in having a non-constant max backedge taken count!");
7204 }
7205 
7206 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7207 /// computable exit into a persistent ExitNotTakenInfo array.
7208 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7209     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7210     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7211     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7212   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7213 
7214   ExitNotTaken.reserve(ExitCounts.size());
7215   std::transform(
7216       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7217       [&](const EdgeExitInfo &EEI) {
7218         BasicBlock *ExitBB = EEI.first;
7219         const ExitLimit &EL = EEI.second;
7220         if (EL.Predicates.empty())
7221           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7222                                   nullptr);
7223 
7224         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7225         for (auto *Pred : EL.Predicates)
7226           Predicate->add(Pred);
7227 
7228         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7229                                 std::move(Predicate));
7230       });
7231   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7232           isa<SCEVConstant>(ConstantMax)) &&
7233          "No point in having a non-constant max backedge taken count!");
7234 }
7235 
7236 /// Invalidate this result and free the ExitNotTakenInfo array.
7237 void ScalarEvolution::BackedgeTakenInfo::clear() {
7238   ExitNotTaken.clear();
7239 }
7240 
7241 /// Compute the number of times the backedge of the specified loop will execute.
7242 ScalarEvolution::BackedgeTakenInfo
7243 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7244                                            bool AllowPredicates) {
7245   SmallVector<BasicBlock *, 8> ExitingBlocks;
7246   L->getExitingBlocks(ExitingBlocks);
7247 
7248   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7249 
7250   SmallVector<EdgeExitInfo, 4> ExitCounts;
7251   bool CouldComputeBECount = true;
7252   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7253   const SCEV *MustExitMaxBECount = nullptr;
7254   const SCEV *MayExitMaxBECount = nullptr;
7255   bool MustExitMaxOrZero = false;
7256 
7257   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7258   // and compute maxBECount.
7259   // Do a union of all the predicates here.
7260   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7261     BasicBlock *ExitBB = ExitingBlocks[i];
7262 
7263     // We canonicalize untaken exits to br (constant), ignore them so that
7264     // proving an exit untaken doesn't negatively impact our ability to reason
7265     // about the loop as whole.
7266     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7267       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7268         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7269         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7270           continue;
7271       }
7272 
7273     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7274 
7275     assert((AllowPredicates || EL.Predicates.empty()) &&
7276            "Predicated exit limit when predicates are not allowed!");
7277 
7278     // 1. For each exit that can be computed, add an entry to ExitCounts.
7279     // CouldComputeBECount is true only if all exits can be computed.
7280     if (EL.ExactNotTaken == getCouldNotCompute())
7281       // We couldn't compute an exact value for this exit, so
7282       // we won't be able to compute an exact value for the loop.
7283       CouldComputeBECount = false;
7284     else
7285       ExitCounts.emplace_back(ExitBB, EL);
7286 
7287     // 2. Derive the loop's MaxBECount from each exit's max number of
7288     // non-exiting iterations. Partition the loop exits into two kinds:
7289     // LoopMustExits and LoopMayExits.
7290     //
7291     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7292     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7293     // MaxBECount is the minimum EL.MaxNotTaken of computable
7294     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7295     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7296     // computable EL.MaxNotTaken.
7297     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7298         DT.dominates(ExitBB, Latch)) {
7299       if (!MustExitMaxBECount) {
7300         MustExitMaxBECount = EL.MaxNotTaken;
7301         MustExitMaxOrZero = EL.MaxOrZero;
7302       } else {
7303         MustExitMaxBECount =
7304             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7305       }
7306     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7307       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7308         MayExitMaxBECount = EL.MaxNotTaken;
7309       else {
7310         MayExitMaxBECount =
7311             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7312       }
7313     }
7314   }
7315   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7316     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7317   // The loop backedge will be taken the maximum or zero times if there's
7318   // a single exit that must be taken the maximum or zero times.
7319   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7320   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7321                            MaxBECount, MaxOrZero);
7322 }
7323 
7324 ScalarEvolution::ExitLimit
7325 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7326                                       bool AllowPredicates) {
7327   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7328   // If our exiting block does not dominate the latch, then its connection with
7329   // loop's exit limit may be far from trivial.
7330   const BasicBlock *Latch = L->getLoopLatch();
7331   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7332     return getCouldNotCompute();
7333 
7334   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7335   Instruction *Term = ExitingBlock->getTerminator();
7336   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7337     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7338     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7339     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7340            "It should have one successor in loop and one exit block!");
7341     // Proceed to the next level to examine the exit condition expression.
7342     return computeExitLimitFromCond(
7343         L, BI->getCondition(), ExitIfTrue,
7344         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7345   }
7346 
7347   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7348     // For switch, make sure that there is a single exit from the loop.
7349     BasicBlock *Exit = nullptr;
7350     for (auto *SBB : successors(ExitingBlock))
7351       if (!L->contains(SBB)) {
7352         if (Exit) // Multiple exit successors.
7353           return getCouldNotCompute();
7354         Exit = SBB;
7355       }
7356     assert(Exit && "Exiting block must have at least one exit");
7357     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7358                                                 /*ControlsExit=*/IsOnlyExit);
7359   }
7360 
7361   return getCouldNotCompute();
7362 }
7363 
7364 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7365     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7366     bool ControlsExit, bool AllowPredicates) {
7367   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7368   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7369                                         ControlsExit, AllowPredicates);
7370 }
7371 
7372 Optional<ScalarEvolution::ExitLimit>
7373 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7374                                       bool ExitIfTrue, bool ControlsExit,
7375                                       bool AllowPredicates) {
7376   (void)this->L;
7377   (void)this->ExitIfTrue;
7378   (void)this->AllowPredicates;
7379 
7380   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7381          this->AllowPredicates == AllowPredicates &&
7382          "Variance in assumed invariant key components!");
7383   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7384   if (Itr == TripCountMap.end())
7385     return None;
7386   return Itr->second;
7387 }
7388 
7389 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7390                                              bool ExitIfTrue,
7391                                              bool ControlsExit,
7392                                              bool AllowPredicates,
7393                                              const ExitLimit &EL) {
7394   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7395          this->AllowPredicates == AllowPredicates &&
7396          "Variance in assumed invariant key components!");
7397 
7398   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7399   assert(InsertResult.second && "Expected successful insertion!");
7400   (void)InsertResult;
7401   (void)ExitIfTrue;
7402 }
7403 
7404 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7405     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7406     bool ControlsExit, bool AllowPredicates) {
7407 
7408   if (auto MaybeEL =
7409           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7410     return *MaybeEL;
7411 
7412   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7413                                               ControlsExit, AllowPredicates);
7414   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7415   return EL;
7416 }
7417 
7418 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7419     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7420     bool ControlsExit, bool AllowPredicates) {
7421   // Check if the controlling expression for this loop is an And or Or.
7422   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7423     if (BO->getOpcode() == Instruction::And) {
7424       // Recurse on the operands of the and.
7425       bool EitherMayExit = !ExitIfTrue;
7426       ExitLimit EL0 = computeExitLimitFromCondCached(
7427           Cache, L, BO->getOperand(0), ExitIfTrue,
7428           ControlsExit && !EitherMayExit, AllowPredicates);
7429       ExitLimit EL1 = computeExitLimitFromCondCached(
7430           Cache, L, BO->getOperand(1), ExitIfTrue,
7431           ControlsExit && !EitherMayExit, AllowPredicates);
7432       // Be robust against unsimplified IR for the form "and i1 X, true"
7433       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7434         return CI->isOne() ? EL0 : EL1;
7435       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7436         return CI->isOne() ? EL1 : EL0;
7437       const SCEV *BECount = getCouldNotCompute();
7438       const SCEV *MaxBECount = getCouldNotCompute();
7439       if (EitherMayExit) {
7440         // Both conditions must be true for the loop to continue executing.
7441         // Choose the less conservative count.
7442         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7443             EL1.ExactNotTaken == getCouldNotCompute())
7444           BECount = getCouldNotCompute();
7445         else
7446           BECount =
7447               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7448         if (EL0.MaxNotTaken == getCouldNotCompute())
7449           MaxBECount = EL1.MaxNotTaken;
7450         else if (EL1.MaxNotTaken == getCouldNotCompute())
7451           MaxBECount = EL0.MaxNotTaken;
7452         else
7453           MaxBECount =
7454               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7455       } else {
7456         // Both conditions must be true at the same time for the loop to exit.
7457         // For now, be conservative.
7458         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7459           MaxBECount = EL0.MaxNotTaken;
7460         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7461           BECount = EL0.ExactNotTaken;
7462       }
7463 
7464       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7465       // to be more aggressive when computing BECount than when computing
7466       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7467       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7468       // to not.
7469       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7470           !isa<SCEVCouldNotCompute>(BECount))
7471         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7472 
7473       return ExitLimit(BECount, MaxBECount, false,
7474                        {&EL0.Predicates, &EL1.Predicates});
7475     }
7476     if (BO->getOpcode() == Instruction::Or) {
7477       // Recurse on the operands of the or.
7478       bool EitherMayExit = ExitIfTrue;
7479       ExitLimit EL0 = computeExitLimitFromCondCached(
7480           Cache, L, BO->getOperand(0), ExitIfTrue,
7481           ControlsExit && !EitherMayExit, AllowPredicates);
7482       ExitLimit EL1 = computeExitLimitFromCondCached(
7483           Cache, L, BO->getOperand(1), ExitIfTrue,
7484           ControlsExit && !EitherMayExit, AllowPredicates);
7485       // Be robust against unsimplified IR for the form "or i1 X, true"
7486       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7487         return CI->isZero() ? EL0 : EL1;
7488       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7489         return CI->isZero() ? EL1 : EL0;
7490       const SCEV *BECount = getCouldNotCompute();
7491       const SCEV *MaxBECount = getCouldNotCompute();
7492       if (EitherMayExit) {
7493         // Both conditions must be false for the loop to continue executing.
7494         // Choose the less conservative count.
7495         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7496             EL1.ExactNotTaken == getCouldNotCompute())
7497           BECount = getCouldNotCompute();
7498         else
7499           BECount =
7500               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7501         if (EL0.MaxNotTaken == getCouldNotCompute())
7502           MaxBECount = EL1.MaxNotTaken;
7503         else if (EL1.MaxNotTaken == getCouldNotCompute())
7504           MaxBECount = EL0.MaxNotTaken;
7505         else
7506           MaxBECount =
7507               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7508       } else {
7509         // Both conditions must be false at the same time for the loop to exit.
7510         // For now, be conservative.
7511         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7512           MaxBECount = EL0.MaxNotTaken;
7513         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7514           BECount = EL0.ExactNotTaken;
7515       }
7516       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7517       // to be more aggressive when computing BECount than when computing
7518       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7519       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7520       // to not.
7521       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7522           !isa<SCEVCouldNotCompute>(BECount))
7523         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7524 
7525       return ExitLimit(BECount, MaxBECount, false,
7526                        {&EL0.Predicates, &EL1.Predicates});
7527     }
7528   }
7529 
7530   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7531   // Proceed to the next level to examine the icmp.
7532   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7533     ExitLimit EL =
7534         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7535     if (EL.hasFullInfo() || !AllowPredicates)
7536       return EL;
7537 
7538     // Try again, but use SCEV predicates this time.
7539     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7540                                     /*AllowPredicates=*/true);
7541   }
7542 
7543   // Check for a constant condition. These are normally stripped out by
7544   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7545   // preserve the CFG and is temporarily leaving constant conditions
7546   // in place.
7547   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7548     if (ExitIfTrue == !CI->getZExtValue())
7549       // The backedge is always taken.
7550       return getCouldNotCompute();
7551     else
7552       // The backedge is never taken.
7553       return getZero(CI->getType());
7554   }
7555 
7556   // If it's not an integer or pointer comparison then compute it the hard way.
7557   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7558 }
7559 
7560 ScalarEvolution::ExitLimit
7561 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7562                                           ICmpInst *ExitCond,
7563                                           bool ExitIfTrue,
7564                                           bool ControlsExit,
7565                                           bool AllowPredicates) {
7566   // If the condition was exit on true, convert the condition to exit on false
7567   ICmpInst::Predicate Pred;
7568   if (!ExitIfTrue)
7569     Pred = ExitCond->getPredicate();
7570   else
7571     Pred = ExitCond->getInversePredicate();
7572   const ICmpInst::Predicate OriginalPred = Pred;
7573 
7574   // Handle common loops like: for (X = "string"; *X; ++X)
7575   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7576     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7577       ExitLimit ItCnt =
7578         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7579       if (ItCnt.hasAnyInfo())
7580         return ItCnt;
7581     }
7582 
7583   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7584   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7585 
7586   // Try to evaluate any dependencies out of the loop.
7587   LHS = getSCEVAtScope(LHS, L);
7588   RHS = getSCEVAtScope(RHS, L);
7589 
7590   // At this point, we would like to compute how many iterations of the
7591   // loop the predicate will return true for these inputs.
7592   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7593     // If there is a loop-invariant, force it into the RHS.
7594     std::swap(LHS, RHS);
7595     Pred = ICmpInst::getSwappedPredicate(Pred);
7596   }
7597 
7598   // Simplify the operands before analyzing them.
7599   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7600 
7601   // If we have a comparison of a chrec against a constant, try to use value
7602   // ranges to answer this query.
7603   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7604     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7605       if (AddRec->getLoop() == L) {
7606         // Form the constant range.
7607         ConstantRange CompRange =
7608             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7609 
7610         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7611         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7612       }
7613 
7614   switch (Pred) {
7615   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7616     // Convert to: while (X-Y != 0)
7617     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7618                                 AllowPredicates);
7619     if (EL.hasAnyInfo()) return EL;
7620     break;
7621   }
7622   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7623     // Convert to: while (X-Y == 0)
7624     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7625     if (EL.hasAnyInfo()) return EL;
7626     break;
7627   }
7628   case ICmpInst::ICMP_SLT:
7629   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7630     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7631     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7632                                     AllowPredicates);
7633     if (EL.hasAnyInfo()) return EL;
7634     break;
7635   }
7636   case ICmpInst::ICMP_SGT:
7637   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7638     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7639     ExitLimit EL =
7640         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7641                             AllowPredicates);
7642     if (EL.hasAnyInfo()) return EL;
7643     break;
7644   }
7645   default:
7646     break;
7647   }
7648 
7649   auto *ExhaustiveCount =
7650       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7651 
7652   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7653     return ExhaustiveCount;
7654 
7655   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7656                                       ExitCond->getOperand(1), L, OriginalPred);
7657 }
7658 
7659 ScalarEvolution::ExitLimit
7660 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7661                                                       SwitchInst *Switch,
7662                                                       BasicBlock *ExitingBlock,
7663                                                       bool ControlsExit) {
7664   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7665 
7666   // Give up if the exit is the default dest of a switch.
7667   if (Switch->getDefaultDest() == ExitingBlock)
7668     return getCouldNotCompute();
7669 
7670   assert(L->contains(Switch->getDefaultDest()) &&
7671          "Default case must not exit the loop!");
7672   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7673   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7674 
7675   // while (X != Y) --> while (X-Y != 0)
7676   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7677   if (EL.hasAnyInfo())
7678     return EL;
7679 
7680   return getCouldNotCompute();
7681 }
7682 
7683 static ConstantInt *
7684 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7685                                 ScalarEvolution &SE) {
7686   const SCEV *InVal = SE.getConstant(C);
7687   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7688   assert(isa<SCEVConstant>(Val) &&
7689          "Evaluation of SCEV at constant didn't fold correctly?");
7690   return cast<SCEVConstant>(Val)->getValue();
7691 }
7692 
7693 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7694 /// compute the backedge execution count.
7695 ScalarEvolution::ExitLimit
7696 ScalarEvolution::computeLoadConstantCompareExitLimit(
7697   LoadInst *LI,
7698   Constant *RHS,
7699   const Loop *L,
7700   ICmpInst::Predicate predicate) {
7701   if (LI->isVolatile()) return getCouldNotCompute();
7702 
7703   // Check to see if the loaded pointer is a getelementptr of a global.
7704   // TODO: Use SCEV instead of manually grubbing with GEPs.
7705   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7706   if (!GEP) return getCouldNotCompute();
7707 
7708   // Make sure that it is really a constant global we are gepping, with an
7709   // initializer, and make sure the first IDX is really 0.
7710   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7711   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7712       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7713       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7714     return getCouldNotCompute();
7715 
7716   // Okay, we allow one non-constant index into the GEP instruction.
7717   Value *VarIdx = nullptr;
7718   std::vector<Constant*> Indexes;
7719   unsigned VarIdxNum = 0;
7720   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7721     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7722       Indexes.push_back(CI);
7723     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7724       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7725       VarIdx = GEP->getOperand(i);
7726       VarIdxNum = i-2;
7727       Indexes.push_back(nullptr);
7728     }
7729 
7730   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7731   if (!VarIdx)
7732     return getCouldNotCompute();
7733 
7734   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7735   // Check to see if X is a loop variant variable value now.
7736   const SCEV *Idx = getSCEV(VarIdx);
7737   Idx = getSCEVAtScope(Idx, L);
7738 
7739   // We can only recognize very limited forms of loop index expressions, in
7740   // particular, only affine AddRec's like {C1,+,C2}.
7741   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7742   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7743       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7744       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7745     return getCouldNotCompute();
7746 
7747   unsigned MaxSteps = MaxBruteForceIterations;
7748   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7749     ConstantInt *ItCst = ConstantInt::get(
7750                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7751     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7752 
7753     // Form the GEP offset.
7754     Indexes[VarIdxNum] = Val;
7755 
7756     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7757                                                          Indexes);
7758     if (!Result) break;  // Cannot compute!
7759 
7760     // Evaluate the condition for this iteration.
7761     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7762     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7763     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7764       ++NumArrayLenItCounts;
7765       return getConstant(ItCst);   // Found terminating iteration!
7766     }
7767   }
7768   return getCouldNotCompute();
7769 }
7770 
7771 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7772     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7773   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7774   if (!RHS)
7775     return getCouldNotCompute();
7776 
7777   const BasicBlock *Latch = L->getLoopLatch();
7778   if (!Latch)
7779     return getCouldNotCompute();
7780 
7781   const BasicBlock *Predecessor = L->getLoopPredecessor();
7782   if (!Predecessor)
7783     return getCouldNotCompute();
7784 
7785   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7786   // Return LHS in OutLHS and shift_opt in OutOpCode.
7787   auto MatchPositiveShift =
7788       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7789 
7790     using namespace PatternMatch;
7791 
7792     ConstantInt *ShiftAmt;
7793     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7794       OutOpCode = Instruction::LShr;
7795     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7796       OutOpCode = Instruction::AShr;
7797     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7798       OutOpCode = Instruction::Shl;
7799     else
7800       return false;
7801 
7802     return ShiftAmt->getValue().isStrictlyPositive();
7803   };
7804 
7805   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7806   //
7807   // loop:
7808   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7809   //   %iv.shifted = lshr i32 %iv, <positive constant>
7810   //
7811   // Return true on a successful match.  Return the corresponding PHI node (%iv
7812   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7813   auto MatchShiftRecurrence =
7814       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7815     Optional<Instruction::BinaryOps> PostShiftOpCode;
7816 
7817     {
7818       Instruction::BinaryOps OpC;
7819       Value *V;
7820 
7821       // If we encounter a shift instruction, "peel off" the shift operation,
7822       // and remember that we did so.  Later when we inspect %iv's backedge
7823       // value, we will make sure that the backedge value uses the same
7824       // operation.
7825       //
7826       // Note: the peeled shift operation does not have to be the same
7827       // instruction as the one feeding into the PHI's backedge value.  We only
7828       // really care about it being the same *kind* of shift instruction --
7829       // that's all that is required for our later inferences to hold.
7830       if (MatchPositiveShift(LHS, V, OpC)) {
7831         PostShiftOpCode = OpC;
7832         LHS = V;
7833       }
7834     }
7835 
7836     PNOut = dyn_cast<PHINode>(LHS);
7837     if (!PNOut || PNOut->getParent() != L->getHeader())
7838       return false;
7839 
7840     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7841     Value *OpLHS;
7842 
7843     return
7844         // The backedge value for the PHI node must be a shift by a positive
7845         // amount
7846         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7847 
7848         // of the PHI node itself
7849         OpLHS == PNOut &&
7850 
7851         // and the kind of shift should be match the kind of shift we peeled
7852         // off, if any.
7853         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7854   };
7855 
7856   PHINode *PN;
7857   Instruction::BinaryOps OpCode;
7858   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7859     return getCouldNotCompute();
7860 
7861   const DataLayout &DL = getDataLayout();
7862 
7863   // The key rationale for this optimization is that for some kinds of shift
7864   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7865   // within a finite number of iterations.  If the condition guarding the
7866   // backedge (in the sense that the backedge is taken if the condition is true)
7867   // is false for the value the shift recurrence stabilizes to, then we know
7868   // that the backedge is taken only a finite number of times.
7869 
7870   ConstantInt *StableValue = nullptr;
7871   switch (OpCode) {
7872   default:
7873     llvm_unreachable("Impossible case!");
7874 
7875   case Instruction::AShr: {
7876     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7877     // bitwidth(K) iterations.
7878     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7879     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7880                                        Predecessor->getTerminator(), &DT);
7881     auto *Ty = cast<IntegerType>(RHS->getType());
7882     if (Known.isNonNegative())
7883       StableValue = ConstantInt::get(Ty, 0);
7884     else if (Known.isNegative())
7885       StableValue = ConstantInt::get(Ty, -1, true);
7886     else
7887       return getCouldNotCompute();
7888 
7889     break;
7890   }
7891   case Instruction::LShr:
7892   case Instruction::Shl:
7893     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7894     // stabilize to 0 in at most bitwidth(K) iterations.
7895     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7896     break;
7897   }
7898 
7899   auto *Result =
7900       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7901   assert(Result->getType()->isIntegerTy(1) &&
7902          "Otherwise cannot be an operand to a branch instruction");
7903 
7904   if (Result->isZeroValue()) {
7905     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7906     const SCEV *UpperBound =
7907         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7908     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7909   }
7910 
7911   return getCouldNotCompute();
7912 }
7913 
7914 /// Return true if we can constant fold an instruction of the specified type,
7915 /// assuming that all operands were constants.
7916 static bool CanConstantFold(const Instruction *I) {
7917   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7918       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7919       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
7920     return true;
7921 
7922   if (const CallInst *CI = dyn_cast<CallInst>(I))
7923     if (const Function *F = CI->getCalledFunction())
7924       return canConstantFoldCallTo(CI, F);
7925   return false;
7926 }
7927 
7928 /// Determine whether this instruction can constant evolve within this loop
7929 /// assuming its operands can all constant evolve.
7930 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7931   // An instruction outside of the loop can't be derived from a loop PHI.
7932   if (!L->contains(I)) return false;
7933 
7934   if (isa<PHINode>(I)) {
7935     // We don't currently keep track of the control flow needed to evaluate
7936     // PHIs, so we cannot handle PHIs inside of loops.
7937     return L->getHeader() == I->getParent();
7938   }
7939 
7940   // If we won't be able to constant fold this expression even if the operands
7941   // are constants, bail early.
7942   return CanConstantFold(I);
7943 }
7944 
7945 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7946 /// recursing through each instruction operand until reaching a loop header phi.
7947 static PHINode *
7948 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7949                                DenseMap<Instruction *, PHINode *> &PHIMap,
7950                                unsigned Depth) {
7951   if (Depth > MaxConstantEvolvingDepth)
7952     return nullptr;
7953 
7954   // Otherwise, we can evaluate this instruction if all of its operands are
7955   // constant or derived from a PHI node themselves.
7956   PHINode *PHI = nullptr;
7957   for (Value *Op : UseInst->operands()) {
7958     if (isa<Constant>(Op)) continue;
7959 
7960     Instruction *OpInst = dyn_cast<Instruction>(Op);
7961     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7962 
7963     PHINode *P = dyn_cast<PHINode>(OpInst);
7964     if (!P)
7965       // If this operand is already visited, reuse the prior result.
7966       // We may have P != PHI if this is the deepest point at which the
7967       // inconsistent paths meet.
7968       P = PHIMap.lookup(OpInst);
7969     if (!P) {
7970       // Recurse and memoize the results, whether a phi is found or not.
7971       // This recursive call invalidates pointers into PHIMap.
7972       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7973       PHIMap[OpInst] = P;
7974     }
7975     if (!P)
7976       return nullptr;  // Not evolving from PHI
7977     if (PHI && PHI != P)
7978       return nullptr;  // Evolving from multiple different PHIs.
7979     PHI = P;
7980   }
7981   // This is a expression evolving from a constant PHI!
7982   return PHI;
7983 }
7984 
7985 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7986 /// in the loop that V is derived from.  We allow arbitrary operations along the
7987 /// way, but the operands of an operation must either be constants or a value
7988 /// derived from a constant PHI.  If this expression does not fit with these
7989 /// constraints, return null.
7990 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7991   Instruction *I = dyn_cast<Instruction>(V);
7992   if (!I || !canConstantEvolve(I, L)) return nullptr;
7993 
7994   if (PHINode *PN = dyn_cast<PHINode>(I))
7995     return PN;
7996 
7997   // Record non-constant instructions contained by the loop.
7998   DenseMap<Instruction *, PHINode *> PHIMap;
7999   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8000 }
8001 
8002 /// EvaluateExpression - Given an expression that passes the
8003 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8004 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8005 /// reason, return null.
8006 static Constant *EvaluateExpression(Value *V, const Loop *L,
8007                                     DenseMap<Instruction *, Constant *> &Vals,
8008                                     const DataLayout &DL,
8009                                     const TargetLibraryInfo *TLI) {
8010   // Convenient constant check, but redundant for recursive calls.
8011   if (Constant *C = dyn_cast<Constant>(V)) return C;
8012   Instruction *I = dyn_cast<Instruction>(V);
8013   if (!I) return nullptr;
8014 
8015   if (Constant *C = Vals.lookup(I)) return C;
8016 
8017   // An instruction inside the loop depends on a value outside the loop that we
8018   // weren't given a mapping for, or a value such as a call inside the loop.
8019   if (!canConstantEvolve(I, L)) return nullptr;
8020 
8021   // An unmapped PHI can be due to a branch or another loop inside this loop,
8022   // or due to this not being the initial iteration through a loop where we
8023   // couldn't compute the evolution of this particular PHI last time.
8024   if (isa<PHINode>(I)) return nullptr;
8025 
8026   std::vector<Constant*> Operands(I->getNumOperands());
8027 
8028   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8029     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8030     if (!Operand) {
8031       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8032       if (!Operands[i]) return nullptr;
8033       continue;
8034     }
8035     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8036     Vals[Operand] = C;
8037     if (!C) return nullptr;
8038     Operands[i] = C;
8039   }
8040 
8041   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8042     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8043                                            Operands[1], DL, TLI);
8044   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8045     if (!LI->isVolatile())
8046       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8047   }
8048   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8049 }
8050 
8051 
8052 // If every incoming value to PN except the one for BB is a specific Constant,
8053 // return that, else return nullptr.
8054 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8055   Constant *IncomingVal = nullptr;
8056 
8057   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8058     if (PN->getIncomingBlock(i) == BB)
8059       continue;
8060 
8061     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8062     if (!CurrentVal)
8063       return nullptr;
8064 
8065     if (IncomingVal != CurrentVal) {
8066       if (IncomingVal)
8067         return nullptr;
8068       IncomingVal = CurrentVal;
8069     }
8070   }
8071 
8072   return IncomingVal;
8073 }
8074 
8075 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8076 /// in the header of its containing loop, we know the loop executes a
8077 /// constant number of times, and the PHI node is just a recurrence
8078 /// involving constants, fold it.
8079 Constant *
8080 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8081                                                    const APInt &BEs,
8082                                                    const Loop *L) {
8083   auto I = ConstantEvolutionLoopExitValue.find(PN);
8084   if (I != ConstantEvolutionLoopExitValue.end())
8085     return I->second;
8086 
8087   if (BEs.ugt(MaxBruteForceIterations))
8088     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8089 
8090   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8091 
8092   DenseMap<Instruction *, Constant *> CurrentIterVals;
8093   BasicBlock *Header = L->getHeader();
8094   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8095 
8096   BasicBlock *Latch = L->getLoopLatch();
8097   if (!Latch)
8098     return nullptr;
8099 
8100   for (PHINode &PHI : Header->phis()) {
8101     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8102       CurrentIterVals[&PHI] = StartCST;
8103   }
8104   if (!CurrentIterVals.count(PN))
8105     return RetVal = nullptr;
8106 
8107   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8108 
8109   // Execute the loop symbolically to determine the exit value.
8110   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8111          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8112 
8113   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8114   unsigned IterationNum = 0;
8115   const DataLayout &DL = getDataLayout();
8116   for (; ; ++IterationNum) {
8117     if (IterationNum == NumIterations)
8118       return RetVal = CurrentIterVals[PN];  // Got exit value!
8119 
8120     // Compute the value of the PHIs for the next iteration.
8121     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8122     DenseMap<Instruction *, Constant *> NextIterVals;
8123     Constant *NextPHI =
8124         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8125     if (!NextPHI)
8126       return nullptr;        // Couldn't evaluate!
8127     NextIterVals[PN] = NextPHI;
8128 
8129     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8130 
8131     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8132     // cease to be able to evaluate one of them or if they stop evolving,
8133     // because that doesn't necessarily prevent us from computing PN.
8134     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8135     for (const auto &I : CurrentIterVals) {
8136       PHINode *PHI = dyn_cast<PHINode>(I.first);
8137       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8138       PHIsToCompute.emplace_back(PHI, I.second);
8139     }
8140     // We use two distinct loops because EvaluateExpression may invalidate any
8141     // iterators into CurrentIterVals.
8142     for (const auto &I : PHIsToCompute) {
8143       PHINode *PHI = I.first;
8144       Constant *&NextPHI = NextIterVals[PHI];
8145       if (!NextPHI) {   // Not already computed.
8146         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8147         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8148       }
8149       if (NextPHI != I.second)
8150         StoppedEvolving = false;
8151     }
8152 
8153     // If all entries in CurrentIterVals == NextIterVals then we can stop
8154     // iterating, the loop can't continue to change.
8155     if (StoppedEvolving)
8156       return RetVal = CurrentIterVals[PN];
8157 
8158     CurrentIterVals.swap(NextIterVals);
8159   }
8160 }
8161 
8162 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8163                                                           Value *Cond,
8164                                                           bool ExitWhen) {
8165   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8166   if (!PN) return getCouldNotCompute();
8167 
8168   // If the loop is canonicalized, the PHI will have exactly two entries.
8169   // That's the only form we support here.
8170   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8171 
8172   DenseMap<Instruction *, Constant *> CurrentIterVals;
8173   BasicBlock *Header = L->getHeader();
8174   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8175 
8176   BasicBlock *Latch = L->getLoopLatch();
8177   assert(Latch && "Should follow from NumIncomingValues == 2!");
8178 
8179   for (PHINode &PHI : Header->phis()) {
8180     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8181       CurrentIterVals[&PHI] = StartCST;
8182   }
8183   if (!CurrentIterVals.count(PN))
8184     return getCouldNotCompute();
8185 
8186   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8187   // the loop symbolically to determine when the condition gets a value of
8188   // "ExitWhen".
8189   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8190   const DataLayout &DL = getDataLayout();
8191   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8192     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8193         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8194 
8195     // Couldn't symbolically evaluate.
8196     if (!CondVal) return getCouldNotCompute();
8197 
8198     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8199       ++NumBruteForceTripCountsComputed;
8200       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8201     }
8202 
8203     // Update all the PHI nodes for the next iteration.
8204     DenseMap<Instruction *, Constant *> NextIterVals;
8205 
8206     // Create a list of which PHIs we need to compute. We want to do this before
8207     // calling EvaluateExpression on them because that may invalidate iterators
8208     // into CurrentIterVals.
8209     SmallVector<PHINode *, 8> PHIsToCompute;
8210     for (const auto &I : CurrentIterVals) {
8211       PHINode *PHI = dyn_cast<PHINode>(I.first);
8212       if (!PHI || PHI->getParent() != Header) continue;
8213       PHIsToCompute.push_back(PHI);
8214     }
8215     for (PHINode *PHI : PHIsToCompute) {
8216       Constant *&NextPHI = NextIterVals[PHI];
8217       if (NextPHI) continue;    // Already computed!
8218 
8219       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8220       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8221     }
8222     CurrentIterVals.swap(NextIterVals);
8223   }
8224 
8225   // Too many iterations were needed to evaluate.
8226   return getCouldNotCompute();
8227 }
8228 
8229 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8230   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8231       ValuesAtScopes[V];
8232   // Check to see if we've folded this expression at this loop before.
8233   for (auto &LS : Values)
8234     if (LS.first == L)
8235       return LS.second ? LS.second : V;
8236 
8237   Values.emplace_back(L, nullptr);
8238 
8239   // Otherwise compute it.
8240   const SCEV *C = computeSCEVAtScope(V, L);
8241   for (auto &LS : reverse(ValuesAtScopes[V]))
8242     if (LS.first == L) {
8243       LS.second = C;
8244       break;
8245     }
8246   return C;
8247 }
8248 
8249 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8250 /// will return Constants for objects which aren't represented by a
8251 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8252 /// Returns NULL if the SCEV isn't representable as a Constant.
8253 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8254   switch (V->getSCEVType()) {
8255   case scCouldNotCompute:
8256   case scAddRecExpr:
8257     return nullptr;
8258   case scConstant:
8259     return cast<SCEVConstant>(V)->getValue();
8260   case scUnknown:
8261     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8262   case scSignExtend: {
8263     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8264     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8265       return ConstantExpr::getSExt(CastOp, SS->getType());
8266     return nullptr;
8267   }
8268   case scZeroExtend: {
8269     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8270     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8271       return ConstantExpr::getZExt(CastOp, SZ->getType());
8272     return nullptr;
8273   }
8274   case scPtrToInt: {
8275     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8276     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8277       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8278 
8279     return nullptr;
8280   }
8281   case scTruncate: {
8282     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8283     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8284       return ConstantExpr::getTrunc(CastOp, ST->getType());
8285     return nullptr;
8286   }
8287   case scAddExpr: {
8288     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8289     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8290       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8291         unsigned AS = PTy->getAddressSpace();
8292         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8293         C = ConstantExpr::getBitCast(C, DestPtrTy);
8294       }
8295       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8296         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8297         if (!C2)
8298           return nullptr;
8299 
8300         // First pointer!
8301         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8302           unsigned AS = C2->getType()->getPointerAddressSpace();
8303           std::swap(C, C2);
8304           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8305           // The offsets have been converted to bytes.  We can add bytes to an
8306           // i8* by GEP with the byte count in the first index.
8307           C = ConstantExpr::getBitCast(C, DestPtrTy);
8308         }
8309 
8310         // Don't bother trying to sum two pointers. We probably can't
8311         // statically compute a load that results from it anyway.
8312         if (C2->getType()->isPointerTy())
8313           return nullptr;
8314 
8315         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8316           if (PTy->getElementType()->isStructTy())
8317             C2 = ConstantExpr::getIntegerCast(
8318                 C2, Type::getInt32Ty(C->getContext()), true);
8319           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8320         } else
8321           C = ConstantExpr::getAdd(C, C2);
8322       }
8323       return C;
8324     }
8325     return nullptr;
8326   }
8327   case scMulExpr: {
8328     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8329     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8330       // Don't bother with pointers at all.
8331       if (C->getType()->isPointerTy())
8332         return nullptr;
8333       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8334         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8335         if (!C2 || C2->getType()->isPointerTy())
8336           return nullptr;
8337         C = ConstantExpr::getMul(C, C2);
8338       }
8339       return C;
8340     }
8341     return nullptr;
8342   }
8343   case scUDivExpr: {
8344     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8345     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8346       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8347         if (LHS->getType() == RHS->getType())
8348           return ConstantExpr::getUDiv(LHS, RHS);
8349     return nullptr;
8350   }
8351   case scSMaxExpr:
8352   case scUMaxExpr:
8353   case scSMinExpr:
8354   case scUMinExpr:
8355     return nullptr; // TODO: smax, umax, smin, umax.
8356   }
8357   llvm_unreachable("Unknown SCEV kind!");
8358 }
8359 
8360 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8361   if (isa<SCEVConstant>(V)) return V;
8362 
8363   // If this instruction is evolved from a constant-evolving PHI, compute the
8364   // exit value from the loop without using SCEVs.
8365   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8366     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8367       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8368         const Loop *CurrLoop = this->LI[I->getParent()];
8369         // Looking for loop exit value.
8370         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8371             PN->getParent() == CurrLoop->getHeader()) {
8372           // Okay, there is no closed form solution for the PHI node.  Check
8373           // to see if the loop that contains it has a known backedge-taken
8374           // count.  If so, we may be able to force computation of the exit
8375           // value.
8376           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8377           // This trivial case can show up in some degenerate cases where
8378           // the incoming IR has not yet been fully simplified.
8379           if (BackedgeTakenCount->isZero()) {
8380             Value *InitValue = nullptr;
8381             bool MultipleInitValues = false;
8382             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8383               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8384                 if (!InitValue)
8385                   InitValue = PN->getIncomingValue(i);
8386                 else if (InitValue != PN->getIncomingValue(i)) {
8387                   MultipleInitValues = true;
8388                   break;
8389                 }
8390               }
8391             }
8392             if (!MultipleInitValues && InitValue)
8393               return getSCEV(InitValue);
8394           }
8395           // Do we have a loop invariant value flowing around the backedge
8396           // for a loop which must execute the backedge?
8397           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8398               isKnownPositive(BackedgeTakenCount) &&
8399               PN->getNumIncomingValues() == 2) {
8400 
8401             unsigned InLoopPred =
8402                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8403             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8404             if (CurrLoop->isLoopInvariant(BackedgeVal))
8405               return getSCEV(BackedgeVal);
8406           }
8407           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8408             // Okay, we know how many times the containing loop executes.  If
8409             // this is a constant evolving PHI node, get the final value at
8410             // the specified iteration number.
8411             Constant *RV = getConstantEvolutionLoopExitValue(
8412                 PN, BTCC->getAPInt(), CurrLoop);
8413             if (RV) return getSCEV(RV);
8414           }
8415         }
8416 
8417         // If there is a single-input Phi, evaluate it at our scope. If we can
8418         // prove that this replacement does not break LCSSA form, use new value.
8419         if (PN->getNumOperands() == 1) {
8420           const SCEV *Input = getSCEV(PN->getOperand(0));
8421           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8422           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8423           // for the simplest case just support constants.
8424           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8425         }
8426       }
8427 
8428       // Okay, this is an expression that we cannot symbolically evaluate
8429       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8430       // the arguments into constants, and if so, try to constant propagate the
8431       // result.  This is particularly useful for computing loop exit values.
8432       if (CanConstantFold(I)) {
8433         SmallVector<Constant *, 4> Operands;
8434         bool MadeImprovement = false;
8435         for (Value *Op : I->operands()) {
8436           if (Constant *C = dyn_cast<Constant>(Op)) {
8437             Operands.push_back(C);
8438             continue;
8439           }
8440 
8441           // If any of the operands is non-constant and if they are
8442           // non-integer and non-pointer, don't even try to analyze them
8443           // with scev techniques.
8444           if (!isSCEVable(Op->getType()))
8445             return V;
8446 
8447           const SCEV *OrigV = getSCEV(Op);
8448           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8449           MadeImprovement |= OrigV != OpV;
8450 
8451           Constant *C = BuildConstantFromSCEV(OpV);
8452           if (!C) return V;
8453           if (C->getType() != Op->getType())
8454             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8455                                                               Op->getType(),
8456                                                               false),
8457                                       C, Op->getType());
8458           Operands.push_back(C);
8459         }
8460 
8461         // Check to see if getSCEVAtScope actually made an improvement.
8462         if (MadeImprovement) {
8463           Constant *C = nullptr;
8464           const DataLayout &DL = getDataLayout();
8465           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8466             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8467                                                 Operands[1], DL, &TLI);
8468           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8469             if (!Load->isVolatile())
8470               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8471                                                DL);
8472           } else
8473             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8474           if (!C) return V;
8475           return getSCEV(C);
8476         }
8477       }
8478     }
8479 
8480     // This is some other type of SCEVUnknown, just return it.
8481     return V;
8482   }
8483 
8484   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8485     // Avoid performing the look-up in the common case where the specified
8486     // expression has no loop-variant portions.
8487     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8488       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8489       if (OpAtScope != Comm->getOperand(i)) {
8490         // Okay, at least one of these operands is loop variant but might be
8491         // foldable.  Build a new instance of the folded commutative expression.
8492         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8493                                             Comm->op_begin()+i);
8494         NewOps.push_back(OpAtScope);
8495 
8496         for (++i; i != e; ++i) {
8497           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8498           NewOps.push_back(OpAtScope);
8499         }
8500         if (isa<SCEVAddExpr>(Comm))
8501           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8502         if (isa<SCEVMulExpr>(Comm))
8503           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8504         if (isa<SCEVMinMaxExpr>(Comm))
8505           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8506         llvm_unreachable("Unknown commutative SCEV type!");
8507       }
8508     }
8509     // If we got here, all operands are loop invariant.
8510     return Comm;
8511   }
8512 
8513   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8514     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8515     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8516     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8517       return Div;   // must be loop invariant
8518     return getUDivExpr(LHS, RHS);
8519   }
8520 
8521   // If this is a loop recurrence for a loop that does not contain L, then we
8522   // are dealing with the final value computed by the loop.
8523   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8524     // First, attempt to evaluate each operand.
8525     // Avoid performing the look-up in the common case where the specified
8526     // expression has no loop-variant portions.
8527     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8528       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8529       if (OpAtScope == AddRec->getOperand(i))
8530         continue;
8531 
8532       // Okay, at least one of these operands is loop variant but might be
8533       // foldable.  Build a new instance of the folded commutative expression.
8534       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8535                                           AddRec->op_begin()+i);
8536       NewOps.push_back(OpAtScope);
8537       for (++i; i != e; ++i)
8538         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8539 
8540       const SCEV *FoldedRec =
8541         getAddRecExpr(NewOps, AddRec->getLoop(),
8542                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8543       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8544       // The addrec may be folded to a nonrecurrence, for example, if the
8545       // induction variable is multiplied by zero after constant folding. Go
8546       // ahead and return the folded value.
8547       if (!AddRec)
8548         return FoldedRec;
8549       break;
8550     }
8551 
8552     // If the scope is outside the addrec's loop, evaluate it by using the
8553     // loop exit value of the addrec.
8554     if (!AddRec->getLoop()->contains(L)) {
8555       // To evaluate this recurrence, we need to know how many times the AddRec
8556       // loop iterates.  Compute this now.
8557       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8558       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8559 
8560       // Then, evaluate the AddRec.
8561       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8562     }
8563 
8564     return AddRec;
8565   }
8566 
8567   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8568     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8569     if (Op == Cast->getOperand())
8570       return Cast;  // must be loop invariant
8571     return getZeroExtendExpr(Op, Cast->getType());
8572   }
8573 
8574   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8575     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8576     if (Op == Cast->getOperand())
8577       return Cast;  // must be loop invariant
8578     return getSignExtendExpr(Op, Cast->getType());
8579   }
8580 
8581   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8582     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8583     if (Op == Cast->getOperand())
8584       return Cast;  // must be loop invariant
8585     return getTruncateExpr(Op, Cast->getType());
8586   }
8587 
8588   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8589     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8590     if (Op == Cast->getOperand())
8591       return Cast; // must be loop invariant
8592     return getPtrToIntExpr(Op, Cast->getType());
8593   }
8594 
8595   llvm_unreachable("Unknown SCEV type!");
8596 }
8597 
8598 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8599   return getSCEVAtScope(getSCEV(V), L);
8600 }
8601 
8602 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8603   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8604     return stripInjectiveFunctions(ZExt->getOperand());
8605   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8606     return stripInjectiveFunctions(SExt->getOperand());
8607   return S;
8608 }
8609 
8610 /// Finds the minimum unsigned root of the following equation:
8611 ///
8612 ///     A * X = B (mod N)
8613 ///
8614 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8615 /// A and B isn't important.
8616 ///
8617 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8618 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8619                                                ScalarEvolution &SE) {
8620   uint32_t BW = A.getBitWidth();
8621   assert(BW == SE.getTypeSizeInBits(B->getType()));
8622   assert(A != 0 && "A must be non-zero.");
8623 
8624   // 1. D = gcd(A, N)
8625   //
8626   // The gcd of A and N may have only one prime factor: 2. The number of
8627   // trailing zeros in A is its multiplicity
8628   uint32_t Mult2 = A.countTrailingZeros();
8629   // D = 2^Mult2
8630 
8631   // 2. Check if B is divisible by D.
8632   //
8633   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8634   // is not less than multiplicity of this prime factor for D.
8635   if (SE.GetMinTrailingZeros(B) < Mult2)
8636     return SE.getCouldNotCompute();
8637 
8638   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8639   // modulo (N / D).
8640   //
8641   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8642   // (N / D) in general. The inverse itself always fits into BW bits, though,
8643   // so we immediately truncate it.
8644   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8645   APInt Mod(BW + 1, 0);
8646   Mod.setBit(BW - Mult2);  // Mod = N / D
8647   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8648 
8649   // 4. Compute the minimum unsigned root of the equation:
8650   // I * (B / D) mod (N / D)
8651   // To simplify the computation, we factor out the divide by D:
8652   // (I * B mod N) / D
8653   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8654   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8655 }
8656 
8657 /// For a given quadratic addrec, generate coefficients of the corresponding
8658 /// quadratic equation, multiplied by a common value to ensure that they are
8659 /// integers.
8660 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8661 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8662 /// were multiplied by, and BitWidth is the bit width of the original addrec
8663 /// coefficients.
8664 /// This function returns None if the addrec coefficients are not compile-
8665 /// time constants.
8666 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8667 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8668   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8669   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8670   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8671   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8672   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8673                     << *AddRec << '\n');
8674 
8675   // We currently can only solve this if the coefficients are constants.
8676   if (!LC || !MC || !NC) {
8677     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8678     return None;
8679   }
8680 
8681   APInt L = LC->getAPInt();
8682   APInt M = MC->getAPInt();
8683   APInt N = NC->getAPInt();
8684   assert(!N.isNullValue() && "This is not a quadratic addrec");
8685 
8686   unsigned BitWidth = LC->getAPInt().getBitWidth();
8687   unsigned NewWidth = BitWidth + 1;
8688   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8689                     << BitWidth << '\n');
8690   // The sign-extension (as opposed to a zero-extension) here matches the
8691   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8692   N = N.sext(NewWidth);
8693   M = M.sext(NewWidth);
8694   L = L.sext(NewWidth);
8695 
8696   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8697   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8698   //   L+M, L+2M+N, L+3M+3N, ...
8699   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8700   //
8701   // The equation Acc = 0 is then
8702   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8703   // In a quadratic form it becomes:
8704   //   N n^2 + (2M-N) n + 2L = 0.
8705 
8706   APInt A = N;
8707   APInt B = 2 * M - A;
8708   APInt C = 2 * L;
8709   APInt T = APInt(NewWidth, 2);
8710   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8711                     << "x + " << C << ", coeff bw: " << NewWidth
8712                     << ", multiplied by " << T << '\n');
8713   return std::make_tuple(A, B, C, T, BitWidth);
8714 }
8715 
8716 /// Helper function to compare optional APInts:
8717 /// (a) if X and Y both exist, return min(X, Y),
8718 /// (b) if neither X nor Y exist, return None,
8719 /// (c) if exactly one of X and Y exists, return that value.
8720 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8721   if (X.hasValue() && Y.hasValue()) {
8722     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8723     APInt XW = X->sextOrSelf(W);
8724     APInt YW = Y->sextOrSelf(W);
8725     return XW.slt(YW) ? *X : *Y;
8726   }
8727   if (!X.hasValue() && !Y.hasValue())
8728     return None;
8729   return X.hasValue() ? *X : *Y;
8730 }
8731 
8732 /// Helper function to truncate an optional APInt to a given BitWidth.
8733 /// When solving addrec-related equations, it is preferable to return a value
8734 /// that has the same bit width as the original addrec's coefficients. If the
8735 /// solution fits in the original bit width, truncate it (except for i1).
8736 /// Returning a value of a different bit width may inhibit some optimizations.
8737 ///
8738 /// In general, a solution to a quadratic equation generated from an addrec
8739 /// may require BW+1 bits, where BW is the bit width of the addrec's
8740 /// coefficients. The reason is that the coefficients of the quadratic
8741 /// equation are BW+1 bits wide (to avoid truncation when converting from
8742 /// the addrec to the equation).
8743 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8744   if (!X.hasValue())
8745     return None;
8746   unsigned W = X->getBitWidth();
8747   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8748     return X->trunc(BitWidth);
8749   return X;
8750 }
8751 
8752 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8753 /// iterations. The values L, M, N are assumed to be signed, and they
8754 /// should all have the same bit widths.
8755 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8756 /// where BW is the bit width of the addrec's coefficients.
8757 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8758 /// returned as such, otherwise the bit width of the returned value may
8759 /// be greater than BW.
8760 ///
8761 /// This function returns None if
8762 /// (a) the addrec coefficients are not constant, or
8763 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8764 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8765 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8766 static Optional<APInt>
8767 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8768   APInt A, B, C, M;
8769   unsigned BitWidth;
8770   auto T = GetQuadraticEquation(AddRec);
8771   if (!T.hasValue())
8772     return None;
8773 
8774   std::tie(A, B, C, M, BitWidth) = *T;
8775   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8776   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8777   if (!X.hasValue())
8778     return None;
8779 
8780   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8781   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8782   if (!V->isZero())
8783     return None;
8784 
8785   return TruncIfPossible(X, BitWidth);
8786 }
8787 
8788 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8789 /// iterations. The values M, N are assumed to be signed, and they
8790 /// should all have the same bit widths.
8791 /// Find the least n such that c(n) does not belong to the given range,
8792 /// while c(n-1) does.
8793 ///
8794 /// This function returns None if
8795 /// (a) the addrec coefficients are not constant, or
8796 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8797 ///     bounds of the range.
8798 static Optional<APInt>
8799 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8800                           const ConstantRange &Range, ScalarEvolution &SE) {
8801   assert(AddRec->getOperand(0)->isZero() &&
8802          "Starting value of addrec should be 0");
8803   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8804                     << Range << ", addrec " << *AddRec << '\n');
8805   // This case is handled in getNumIterationsInRange. Here we can assume that
8806   // we start in the range.
8807   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8808          "Addrec's initial value should be in range");
8809 
8810   APInt A, B, C, M;
8811   unsigned BitWidth;
8812   auto T = GetQuadraticEquation(AddRec);
8813   if (!T.hasValue())
8814     return None;
8815 
8816   // Be careful about the return value: there can be two reasons for not
8817   // returning an actual number. First, if no solutions to the equations
8818   // were found, and second, if the solutions don't leave the given range.
8819   // The first case means that the actual solution is "unknown", the second
8820   // means that it's known, but not valid. If the solution is unknown, we
8821   // cannot make any conclusions.
8822   // Return a pair: the optional solution and a flag indicating if the
8823   // solution was found.
8824   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8825     // Solve for signed overflow and unsigned overflow, pick the lower
8826     // solution.
8827     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8828                       << Bound << " (before multiplying by " << M << ")\n");
8829     Bound *= M; // The quadratic equation multiplier.
8830 
8831     Optional<APInt> SO = None;
8832     if (BitWidth > 1) {
8833       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8834                            "signed overflow\n");
8835       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8836     }
8837     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8838                          "unsigned overflow\n");
8839     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8840                                                               BitWidth+1);
8841 
8842     auto LeavesRange = [&] (const APInt &X) {
8843       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8844       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8845       if (Range.contains(V0->getValue()))
8846         return false;
8847       // X should be at least 1, so X-1 is non-negative.
8848       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8849       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8850       if (Range.contains(V1->getValue()))
8851         return true;
8852       return false;
8853     };
8854 
8855     // If SolveQuadraticEquationWrap returns None, it means that there can
8856     // be a solution, but the function failed to find it. We cannot treat it
8857     // as "no solution".
8858     if (!SO.hasValue() || !UO.hasValue())
8859       return { None, false };
8860 
8861     // Check the smaller value first to see if it leaves the range.
8862     // At this point, both SO and UO must have values.
8863     Optional<APInt> Min = MinOptional(SO, UO);
8864     if (LeavesRange(*Min))
8865       return { Min, true };
8866     Optional<APInt> Max = Min == SO ? UO : SO;
8867     if (LeavesRange(*Max))
8868       return { Max, true };
8869 
8870     // Solutions were found, but were eliminated, hence the "true".
8871     return { None, true };
8872   };
8873 
8874   std::tie(A, B, C, M, BitWidth) = *T;
8875   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8876   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8877   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8878   auto SL = SolveForBoundary(Lower);
8879   auto SU = SolveForBoundary(Upper);
8880   // If any of the solutions was unknown, no meaninigful conclusions can
8881   // be made.
8882   if (!SL.second || !SU.second)
8883     return None;
8884 
8885   // Claim: The correct solution is not some value between Min and Max.
8886   //
8887   // Justification: Assuming that Min and Max are different values, one of
8888   // them is when the first signed overflow happens, the other is when the
8889   // first unsigned overflow happens. Crossing the range boundary is only
8890   // possible via an overflow (treating 0 as a special case of it, modeling
8891   // an overflow as crossing k*2^W for some k).
8892   //
8893   // The interesting case here is when Min was eliminated as an invalid
8894   // solution, but Max was not. The argument is that if there was another
8895   // overflow between Min and Max, it would also have been eliminated if
8896   // it was considered.
8897   //
8898   // For a given boundary, it is possible to have two overflows of the same
8899   // type (signed/unsigned) without having the other type in between: this
8900   // can happen when the vertex of the parabola is between the iterations
8901   // corresponding to the overflows. This is only possible when the two
8902   // overflows cross k*2^W for the same k. In such case, if the second one
8903   // left the range (and was the first one to do so), the first overflow
8904   // would have to enter the range, which would mean that either we had left
8905   // the range before or that we started outside of it. Both of these cases
8906   // are contradictions.
8907   //
8908   // Claim: In the case where SolveForBoundary returns None, the correct
8909   // solution is not some value between the Max for this boundary and the
8910   // Min of the other boundary.
8911   //
8912   // Justification: Assume that we had such Max_A and Min_B corresponding
8913   // to range boundaries A and B and such that Max_A < Min_B. If there was
8914   // a solution between Max_A and Min_B, it would have to be caused by an
8915   // overflow corresponding to either A or B. It cannot correspond to B,
8916   // since Min_B is the first occurrence of such an overflow. If it
8917   // corresponded to A, it would have to be either a signed or an unsigned
8918   // overflow that is larger than both eliminated overflows for A. But
8919   // between the eliminated overflows and this overflow, the values would
8920   // cover the entire value space, thus crossing the other boundary, which
8921   // is a contradiction.
8922 
8923   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8924 }
8925 
8926 ScalarEvolution::ExitLimit
8927 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8928                               bool AllowPredicates) {
8929 
8930   // This is only used for loops with a "x != y" exit test. The exit condition
8931   // is now expressed as a single expression, V = x-y. So the exit test is
8932   // effectively V != 0.  We know and take advantage of the fact that this
8933   // expression only being used in a comparison by zero context.
8934 
8935   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8936   // If the value is a constant
8937   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8938     // If the value is already zero, the branch will execute zero times.
8939     if (C->getValue()->isZero()) return C;
8940     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8941   }
8942 
8943   const SCEVAddRecExpr *AddRec =
8944       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8945 
8946   if (!AddRec && AllowPredicates)
8947     // Try to make this an AddRec using runtime tests, in the first X
8948     // iterations of this loop, where X is the SCEV expression found by the
8949     // algorithm below.
8950     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8951 
8952   if (!AddRec || AddRec->getLoop() != L)
8953     return getCouldNotCompute();
8954 
8955   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8956   // the quadratic equation to solve it.
8957   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8958     // We can only use this value if the chrec ends up with an exact zero
8959     // value at this index.  When solving for "X*X != 5", for example, we
8960     // should not accept a root of 2.
8961     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8962       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8963       return ExitLimit(R, R, false, Predicates);
8964     }
8965     return getCouldNotCompute();
8966   }
8967 
8968   // Otherwise we can only handle this if it is affine.
8969   if (!AddRec->isAffine())
8970     return getCouldNotCompute();
8971 
8972   // If this is an affine expression, the execution count of this branch is
8973   // the minimum unsigned root of the following equation:
8974   //
8975   //     Start + Step*N = 0 (mod 2^BW)
8976   //
8977   // equivalent to:
8978   //
8979   //             Step*N = -Start (mod 2^BW)
8980   //
8981   // where BW is the common bit width of Start and Step.
8982 
8983   // Get the initial value for the loop.
8984   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8985   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8986 
8987   // For now we handle only constant steps.
8988   //
8989   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8990   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8991   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8992   // We have not yet seen any such cases.
8993   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8994   if (!StepC || StepC->getValue()->isZero())
8995     return getCouldNotCompute();
8996 
8997   // For positive steps (counting up until unsigned overflow):
8998   //   N = -Start/Step (as unsigned)
8999   // For negative steps (counting down to zero):
9000   //   N = Start/-Step
9001   // First compute the unsigned distance from zero in the direction of Step.
9002   bool CountDown = StepC->getAPInt().isNegative();
9003   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9004 
9005   // Handle unitary steps, which cannot wraparound.
9006   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9007   //   N = Distance (as unsigned)
9008   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9009     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9010     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9011     if (MaxBECountBase.ult(MaxBECount))
9012       MaxBECount = MaxBECountBase;
9013 
9014     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9015     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9016     // case, and see if we can improve the bound.
9017     //
9018     // Explicitly handling this here is necessary because getUnsignedRange
9019     // isn't context-sensitive; it doesn't know that we only care about the
9020     // range inside the loop.
9021     const SCEV *Zero = getZero(Distance->getType());
9022     const SCEV *One = getOne(Distance->getType());
9023     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9024     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9025       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9026       // as "unsigned_max(Distance + 1) - 1".
9027       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9028       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9029     }
9030     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9031   }
9032 
9033   // If the condition controls loop exit (the loop exits only if the expression
9034   // is true) and the addition is no-wrap we can use unsigned divide to
9035   // compute the backedge count.  In this case, the step may not divide the
9036   // distance, but we don't care because if the condition is "missed" the loop
9037   // will have undefined behavior due to wrapping.
9038   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9039       loopHasNoAbnormalExits(AddRec->getLoop())) {
9040     const SCEV *Exact =
9041         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9042     const SCEV *Max =
9043         Exact == getCouldNotCompute()
9044             ? Exact
9045             : getConstant(getUnsignedRangeMax(Exact));
9046     return ExitLimit(Exact, Max, false, Predicates);
9047   }
9048 
9049   // Solve the general equation.
9050   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9051                                                getNegativeSCEV(Start), *this);
9052   const SCEV *M = E == getCouldNotCompute()
9053                       ? E
9054                       : getConstant(getUnsignedRangeMax(E));
9055   return ExitLimit(E, M, false, Predicates);
9056 }
9057 
9058 ScalarEvolution::ExitLimit
9059 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9060   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9061   // handle them yet except for the trivial case.  This could be expanded in the
9062   // future as needed.
9063 
9064   // If the value is a constant, check to see if it is known to be non-zero
9065   // already.  If so, the backedge will execute zero times.
9066   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9067     if (!C->getValue()->isZero())
9068       return getZero(C->getType());
9069     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9070   }
9071 
9072   // We could implement others, but I really doubt anyone writes loops like
9073   // this, and if they did, they would already be constant folded.
9074   return getCouldNotCompute();
9075 }
9076 
9077 std::pair<const BasicBlock *, const BasicBlock *>
9078 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9079     const {
9080   // If the block has a unique predecessor, then there is no path from the
9081   // predecessor to the block that does not go through the direct edge
9082   // from the predecessor to the block.
9083   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9084     return {Pred, BB};
9085 
9086   // A loop's header is defined to be a block that dominates the loop.
9087   // If the header has a unique predecessor outside the loop, it must be
9088   // a block that has exactly one successor that can reach the loop.
9089   if (const Loop *L = LI.getLoopFor(BB))
9090     return {L->getLoopPredecessor(), L->getHeader()};
9091 
9092   return {nullptr, nullptr};
9093 }
9094 
9095 /// SCEV structural equivalence is usually sufficient for testing whether two
9096 /// expressions are equal, however for the purposes of looking for a condition
9097 /// guarding a loop, it can be useful to be a little more general, since a
9098 /// front-end may have replicated the controlling expression.
9099 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9100   // Quick check to see if they are the same SCEV.
9101   if (A == B) return true;
9102 
9103   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9104     // Not all instructions that are "identical" compute the same value.  For
9105     // instance, two distinct alloca instructions allocating the same type are
9106     // identical and do not read memory; but compute distinct values.
9107     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9108   };
9109 
9110   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9111   // two different instructions with the same value. Check for this case.
9112   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9113     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9114       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9115         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9116           if (ComputesEqualValues(AI, BI))
9117             return true;
9118 
9119   // Otherwise assume they may have a different value.
9120   return false;
9121 }
9122 
9123 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9124                                            const SCEV *&LHS, const SCEV *&RHS,
9125                                            unsigned Depth) {
9126   bool Changed = false;
9127   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9128   // '0 != 0'.
9129   auto TrivialCase = [&](bool TriviallyTrue) {
9130     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9131     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9132     return true;
9133   };
9134   // If we hit the max recursion limit bail out.
9135   if (Depth >= 3)
9136     return false;
9137 
9138   // Canonicalize a constant to the right side.
9139   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9140     // Check for both operands constant.
9141     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9142       if (ConstantExpr::getICmp(Pred,
9143                                 LHSC->getValue(),
9144                                 RHSC->getValue())->isNullValue())
9145         return TrivialCase(false);
9146       else
9147         return TrivialCase(true);
9148     }
9149     // Otherwise swap the operands to put the constant on the right.
9150     std::swap(LHS, RHS);
9151     Pred = ICmpInst::getSwappedPredicate(Pred);
9152     Changed = true;
9153   }
9154 
9155   // If we're comparing an addrec with a value which is loop-invariant in the
9156   // addrec's loop, put the addrec on the left. Also make a dominance check,
9157   // as both operands could be addrecs loop-invariant in each other's loop.
9158   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9159     const Loop *L = AR->getLoop();
9160     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9161       std::swap(LHS, RHS);
9162       Pred = ICmpInst::getSwappedPredicate(Pred);
9163       Changed = true;
9164     }
9165   }
9166 
9167   // If there's a constant operand, canonicalize comparisons with boundary
9168   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9169   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9170     const APInt &RA = RC->getAPInt();
9171 
9172     bool SimplifiedByConstantRange = false;
9173 
9174     if (!ICmpInst::isEquality(Pred)) {
9175       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9176       if (ExactCR.isFullSet())
9177         return TrivialCase(true);
9178       else if (ExactCR.isEmptySet())
9179         return TrivialCase(false);
9180 
9181       APInt NewRHS;
9182       CmpInst::Predicate NewPred;
9183       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9184           ICmpInst::isEquality(NewPred)) {
9185         // We were able to convert an inequality to an equality.
9186         Pred = NewPred;
9187         RHS = getConstant(NewRHS);
9188         Changed = SimplifiedByConstantRange = true;
9189       }
9190     }
9191 
9192     if (!SimplifiedByConstantRange) {
9193       switch (Pred) {
9194       default:
9195         break;
9196       case ICmpInst::ICMP_EQ:
9197       case ICmpInst::ICMP_NE:
9198         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9199         if (!RA)
9200           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9201             if (const SCEVMulExpr *ME =
9202                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9203               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9204                   ME->getOperand(0)->isAllOnesValue()) {
9205                 RHS = AE->getOperand(1);
9206                 LHS = ME->getOperand(1);
9207                 Changed = true;
9208               }
9209         break;
9210 
9211 
9212         // The "Should have been caught earlier!" messages refer to the fact
9213         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9214         // should have fired on the corresponding cases, and canonicalized the
9215         // check to trivial case.
9216 
9217       case ICmpInst::ICMP_UGE:
9218         assert(!RA.isMinValue() && "Should have been caught earlier!");
9219         Pred = ICmpInst::ICMP_UGT;
9220         RHS = getConstant(RA - 1);
9221         Changed = true;
9222         break;
9223       case ICmpInst::ICMP_ULE:
9224         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9225         Pred = ICmpInst::ICMP_ULT;
9226         RHS = getConstant(RA + 1);
9227         Changed = true;
9228         break;
9229       case ICmpInst::ICMP_SGE:
9230         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9231         Pred = ICmpInst::ICMP_SGT;
9232         RHS = getConstant(RA - 1);
9233         Changed = true;
9234         break;
9235       case ICmpInst::ICMP_SLE:
9236         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9237         Pred = ICmpInst::ICMP_SLT;
9238         RHS = getConstant(RA + 1);
9239         Changed = true;
9240         break;
9241       }
9242     }
9243   }
9244 
9245   // Check for obvious equality.
9246   if (HasSameValue(LHS, RHS)) {
9247     if (ICmpInst::isTrueWhenEqual(Pred))
9248       return TrivialCase(true);
9249     if (ICmpInst::isFalseWhenEqual(Pred))
9250       return TrivialCase(false);
9251   }
9252 
9253   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9254   // adding or subtracting 1 from one of the operands.
9255   switch (Pred) {
9256   case ICmpInst::ICMP_SLE:
9257     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9258       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9259                        SCEV::FlagNSW);
9260       Pred = ICmpInst::ICMP_SLT;
9261       Changed = true;
9262     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9263       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9264                        SCEV::FlagNSW);
9265       Pred = ICmpInst::ICMP_SLT;
9266       Changed = true;
9267     }
9268     break;
9269   case ICmpInst::ICMP_SGE:
9270     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9271       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9272                        SCEV::FlagNSW);
9273       Pred = ICmpInst::ICMP_SGT;
9274       Changed = true;
9275     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9276       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9277                        SCEV::FlagNSW);
9278       Pred = ICmpInst::ICMP_SGT;
9279       Changed = true;
9280     }
9281     break;
9282   case ICmpInst::ICMP_ULE:
9283     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9284       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9285                        SCEV::FlagNUW);
9286       Pred = ICmpInst::ICMP_ULT;
9287       Changed = true;
9288     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9289       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9290       Pred = ICmpInst::ICMP_ULT;
9291       Changed = true;
9292     }
9293     break;
9294   case ICmpInst::ICMP_UGE:
9295     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9296       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9297       Pred = ICmpInst::ICMP_UGT;
9298       Changed = true;
9299     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9300       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9301                        SCEV::FlagNUW);
9302       Pred = ICmpInst::ICMP_UGT;
9303       Changed = true;
9304     }
9305     break;
9306   default:
9307     break;
9308   }
9309 
9310   // TODO: More simplifications are possible here.
9311 
9312   // Recursively simplify until we either hit a recursion limit or nothing
9313   // changes.
9314   if (Changed)
9315     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9316 
9317   return Changed;
9318 }
9319 
9320 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9321   return getSignedRangeMax(S).isNegative();
9322 }
9323 
9324 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9325   return getSignedRangeMin(S).isStrictlyPositive();
9326 }
9327 
9328 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9329   return !getSignedRangeMin(S).isNegative();
9330 }
9331 
9332 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9333   return !getSignedRangeMax(S).isStrictlyPositive();
9334 }
9335 
9336 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9337   return isKnownNegative(S) || isKnownPositive(S);
9338 }
9339 
9340 std::pair<const SCEV *, const SCEV *>
9341 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9342   // Compute SCEV on entry of loop L.
9343   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9344   if (Start == getCouldNotCompute())
9345     return { Start, Start };
9346   // Compute post increment SCEV for loop L.
9347   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9348   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9349   return { Start, PostInc };
9350 }
9351 
9352 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9353                                           const SCEV *LHS, const SCEV *RHS) {
9354   // First collect all loops.
9355   SmallPtrSet<const Loop *, 8> LoopsUsed;
9356   getUsedLoops(LHS, LoopsUsed);
9357   getUsedLoops(RHS, LoopsUsed);
9358 
9359   if (LoopsUsed.empty())
9360     return false;
9361 
9362   // Domination relationship must be a linear order on collected loops.
9363 #ifndef NDEBUG
9364   for (auto *L1 : LoopsUsed)
9365     for (auto *L2 : LoopsUsed)
9366       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9367               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9368              "Domination relationship is not a linear order");
9369 #endif
9370 
9371   const Loop *MDL =
9372       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9373                         [&](const Loop *L1, const Loop *L2) {
9374          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9375        });
9376 
9377   // Get init and post increment value for LHS.
9378   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9379   // if LHS contains unknown non-invariant SCEV then bail out.
9380   if (SplitLHS.first == getCouldNotCompute())
9381     return false;
9382   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9383   // Get init and post increment value for RHS.
9384   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9385   // if RHS contains unknown non-invariant SCEV then bail out.
9386   if (SplitRHS.first == getCouldNotCompute())
9387     return false;
9388   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9389   // It is possible that init SCEV contains an invariant load but it does
9390   // not dominate MDL and is not available at MDL loop entry, so we should
9391   // check it here.
9392   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9393       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9394     return false;
9395 
9396   // It seems backedge guard check is faster than entry one so in some cases
9397   // it can speed up whole estimation by short circuit
9398   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9399                                      SplitRHS.second) &&
9400          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9401 }
9402 
9403 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9404                                        const SCEV *LHS, const SCEV *RHS) {
9405   // Canonicalize the inputs first.
9406   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9407 
9408   if (isKnownViaInduction(Pred, LHS, RHS))
9409     return true;
9410 
9411   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9412     return true;
9413 
9414   // Otherwise see what can be done with some simple reasoning.
9415   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9416 }
9417 
9418 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9419                                          const SCEV *LHS, const SCEV *RHS,
9420                                          const Instruction *Context) {
9421   // TODO: Analyze guards and assumes from Context's block.
9422   return isKnownPredicate(Pred, LHS, RHS) ||
9423          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9424 }
9425 
9426 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9427                                               const SCEVAddRecExpr *LHS,
9428                                               const SCEV *RHS) {
9429   const Loop *L = LHS->getLoop();
9430   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9431          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9432 }
9433 
9434 Optional<ScalarEvolution::MonotonicPredicateType>
9435 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9436                                            ICmpInst::Predicate Pred) {
9437   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9438 
9439 #ifndef NDEBUG
9440   // Verify an invariant: inverting the predicate should turn a monotonically
9441   // increasing change to a monotonically decreasing one, and vice versa.
9442   if (Result) {
9443     auto ResultSwapped =
9444         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9445 
9446     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9447     assert(ResultSwapped.getValue() != Result.getValue() &&
9448            "monotonicity should flip as we flip the predicate");
9449   }
9450 #endif
9451 
9452   return Result;
9453 }
9454 
9455 Optional<ScalarEvolution::MonotonicPredicateType>
9456 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9457                                                ICmpInst::Predicate Pred) {
9458   // A zero step value for LHS means the induction variable is essentially a
9459   // loop invariant value. We don't really depend on the predicate actually
9460   // flipping from false to true (for increasing predicates, and the other way
9461   // around for decreasing predicates), all we care about is that *if* the
9462   // predicate changes then it only changes from false to true.
9463   //
9464   // A zero step value in itself is not very useful, but there may be places
9465   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9466   // as general as possible.
9467 
9468   // Only handle LE/LT/GE/GT predicates.
9469   if (!ICmpInst::isRelational(Pred))
9470     return None;
9471 
9472   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9473   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9474          "Should be greater or less!");
9475 
9476   // Check that AR does not wrap.
9477   if (ICmpInst::isUnsigned(Pred)) {
9478     if (!LHS->hasNoUnsignedWrap())
9479       return None;
9480     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9481   } else {
9482     assert(ICmpInst::isSigned(Pred) &&
9483            "Relational predicate is either signed or unsigned!");
9484     if (!LHS->hasNoSignedWrap())
9485       return None;
9486 
9487     const SCEV *Step = LHS->getStepRecurrence(*this);
9488 
9489     if (isKnownNonNegative(Step))
9490       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9491 
9492     if (isKnownNonPositive(Step))
9493       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9494 
9495     return None;
9496   }
9497 }
9498 
9499 bool ScalarEvolution::isLoopInvariantPredicate(
9500     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9501     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9502     const SCEV *&InvariantRHS) {
9503 
9504   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9505   if (!isLoopInvariant(RHS, L)) {
9506     if (!isLoopInvariant(LHS, L))
9507       return false;
9508 
9509     std::swap(LHS, RHS);
9510     Pred = ICmpInst::getSwappedPredicate(Pred);
9511   }
9512 
9513   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9514   if (!ArLHS || ArLHS->getLoop() != L)
9515     return false;
9516 
9517   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9518   if (!MonotonicType)
9519     return false;
9520   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9521   // true as the loop iterates, and the backedge is control dependent on
9522   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9523   //
9524   //   * if the predicate was false in the first iteration then the predicate
9525   //     is never evaluated again, since the loop exits without taking the
9526   //     backedge.
9527   //   * if the predicate was true in the first iteration then it will
9528   //     continue to be true for all future iterations since it is
9529   //     monotonically increasing.
9530   //
9531   // For both the above possibilities, we can replace the loop varying
9532   // predicate with its value on the first iteration of the loop (which is
9533   // loop invariant).
9534   //
9535   // A similar reasoning applies for a monotonically decreasing predicate, by
9536   // replacing true with false and false with true in the above two bullets.
9537   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9538   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9539 
9540   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9541     return false;
9542 
9543   InvariantPred = Pred;
9544   InvariantLHS = ArLHS->getStart();
9545   InvariantRHS = RHS;
9546   return true;
9547 }
9548 
9549 bool ScalarEvolution::isLoopInvariantExitCondDuringFirstIterations(
9550     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9551     const Instruction *Context, const SCEV *MaxIter,
9552     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9553     const SCEV *&InvariantRHS) {
9554   // Try to prove the following set of facts:
9555   // - The predicate is monotonic.
9556   // - If the check does not fail on the 1st iteration:
9557   //   - No overflow will happen during first MaxIter iterations;
9558   //   - It will not fail on the MaxIter'th iteration.
9559   // If the check does fail on the 1st iteration, we leave the loop and no
9560   // other checks matter.
9561 
9562   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9563   if (!isLoopInvariant(RHS, L)) {
9564     if (!isLoopInvariant(LHS, L))
9565       return false;
9566 
9567     std::swap(LHS, RHS);
9568     Pred = ICmpInst::getSwappedPredicate(Pred);
9569   }
9570 
9571   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9572   // TODO: Lift affinity limitation in the future.
9573   if (!AR || AR->getLoop() != L || !AR->isAffine())
9574     return false;
9575 
9576   // The predicate must be relational (i.e. <, <=, >=, >).
9577   if (!ICmpInst::isRelational(Pred))
9578     return false;
9579 
9580   // TODO: Support steps other than +/- 1.
9581   const SCEV *Step = AR->getOperand(1);
9582   auto *One = getOne(Step->getType());
9583   auto *MinusOne = getNegativeSCEV(One);
9584   if (Step != One && Step != MinusOne)
9585     return false;
9586 
9587   // Type mismatch here means that MaxIter is potentially larger than max
9588   // unsigned value in start type, which mean we cannot prove no wrap for the
9589   // indvar.
9590   if (AR->getType() != MaxIter->getType())
9591     return false;
9592 
9593   // Value of IV on suggested last iteration.
9594   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9595   // Does it still meet the requirement?
9596   if (!isKnownPredicateAt(Pred, Last, RHS, Context))
9597     return false;
9598   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9599   // not exceed max unsigned value of this type), this effectively proves
9600   // that there is no wrap during the iteration. To prove that there is no
9601   // signed/unsigned wrap, we need to check that
9602   // Start <= Last for step = 1 or Start >= Last for step = -1.
9603   ICmpInst::Predicate NoOverflowPred =
9604       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9605   if (Step == MinusOne)
9606     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9607   const SCEV *Start = AR->getStart();
9608   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9609     return false;
9610 
9611   // Everything is fine.
9612   InvariantPred = Pred;
9613   InvariantLHS = Start;
9614   InvariantRHS = RHS;
9615   return true;
9616 }
9617 
9618 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9619     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9620   if (HasSameValue(LHS, RHS))
9621     return ICmpInst::isTrueWhenEqual(Pred);
9622 
9623   // This code is split out from isKnownPredicate because it is called from
9624   // within isLoopEntryGuardedByCond.
9625 
9626   auto CheckRanges =
9627       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9628     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9629         .contains(RangeLHS);
9630   };
9631 
9632   // The check at the top of the function catches the case where the values are
9633   // known to be equal.
9634   if (Pred == CmpInst::ICMP_EQ)
9635     return false;
9636 
9637   if (Pred == CmpInst::ICMP_NE)
9638     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9639            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9640            isKnownNonZero(getMinusSCEV(LHS, RHS));
9641 
9642   if (CmpInst::isSigned(Pred))
9643     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9644 
9645   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9646 }
9647 
9648 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9649                                                     const SCEV *LHS,
9650                                                     const SCEV *RHS) {
9651   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9652   // Return Y via OutY.
9653   auto MatchBinaryAddToConst =
9654       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9655              SCEV::NoWrapFlags ExpectedFlags) {
9656     const SCEV *NonConstOp, *ConstOp;
9657     SCEV::NoWrapFlags FlagsPresent;
9658 
9659     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9660         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9661       return false;
9662 
9663     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9664     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9665   };
9666 
9667   APInt C;
9668 
9669   switch (Pred) {
9670   default:
9671     break;
9672 
9673   case ICmpInst::ICMP_SGE:
9674     std::swap(LHS, RHS);
9675     LLVM_FALLTHROUGH;
9676   case ICmpInst::ICMP_SLE:
9677     // X s<= (X + C)<nsw> if C >= 0
9678     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9679       return true;
9680 
9681     // (X + C)<nsw> s<= X if C <= 0
9682     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9683         !C.isStrictlyPositive())
9684       return true;
9685     break;
9686 
9687   case ICmpInst::ICMP_SGT:
9688     std::swap(LHS, RHS);
9689     LLVM_FALLTHROUGH;
9690   case ICmpInst::ICMP_SLT:
9691     // X s< (X + C)<nsw> if C > 0
9692     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9693         C.isStrictlyPositive())
9694       return true;
9695 
9696     // (X + C)<nsw> s< X if C < 0
9697     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9698       return true;
9699     break;
9700 
9701   case ICmpInst::ICMP_UGE:
9702     std::swap(LHS, RHS);
9703     LLVM_FALLTHROUGH;
9704   case ICmpInst::ICMP_ULE:
9705     // X u<= (X + C)<nuw> for any C
9706     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9707       return true;
9708     break;
9709 
9710   case ICmpInst::ICMP_UGT:
9711     std::swap(LHS, RHS);
9712     LLVM_FALLTHROUGH;
9713   case ICmpInst::ICMP_ULT:
9714     // X u< (X + C)<nuw> if C != 0
9715     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9716       return true;
9717     break;
9718   }
9719 
9720   return false;
9721 }
9722 
9723 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9724                                                    const SCEV *LHS,
9725                                                    const SCEV *RHS) {
9726   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9727     return false;
9728 
9729   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9730   // the stack can result in exponential time complexity.
9731   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9732 
9733   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9734   //
9735   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9736   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9737   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9738   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9739   // use isKnownPredicate later if needed.
9740   return isKnownNonNegative(RHS) &&
9741          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9742          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9743 }
9744 
9745 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9746                                         ICmpInst::Predicate Pred,
9747                                         const SCEV *LHS, const SCEV *RHS) {
9748   // No need to even try if we know the module has no guards.
9749   if (!HasGuards)
9750     return false;
9751 
9752   return any_of(*BB, [&](const Instruction &I) {
9753     using namespace llvm::PatternMatch;
9754 
9755     Value *Condition;
9756     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9757                          m_Value(Condition))) &&
9758            isImpliedCond(Pred, LHS, RHS, Condition, false);
9759   });
9760 }
9761 
9762 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9763 /// protected by a conditional between LHS and RHS.  This is used to
9764 /// to eliminate casts.
9765 bool
9766 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9767                                              ICmpInst::Predicate Pred,
9768                                              const SCEV *LHS, const SCEV *RHS) {
9769   // Interpret a null as meaning no loop, where there is obviously no guard
9770   // (interprocedural conditions notwithstanding).
9771   if (!L) return true;
9772 
9773   if (VerifyIR)
9774     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9775            "This cannot be done on broken IR!");
9776 
9777 
9778   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9779     return true;
9780 
9781   BasicBlock *Latch = L->getLoopLatch();
9782   if (!Latch)
9783     return false;
9784 
9785   BranchInst *LoopContinuePredicate =
9786     dyn_cast<BranchInst>(Latch->getTerminator());
9787   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9788       isImpliedCond(Pred, LHS, RHS,
9789                     LoopContinuePredicate->getCondition(),
9790                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9791     return true;
9792 
9793   // We don't want more than one activation of the following loops on the stack
9794   // -- that can lead to O(n!) time complexity.
9795   if (WalkingBEDominatingConds)
9796     return false;
9797 
9798   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9799 
9800   // See if we can exploit a trip count to prove the predicate.
9801   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9802   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9803   if (LatchBECount != getCouldNotCompute()) {
9804     // We know that Latch branches back to the loop header exactly
9805     // LatchBECount times.  This means the backdege condition at Latch is
9806     // equivalent to  "{0,+,1} u< LatchBECount".
9807     Type *Ty = LatchBECount->getType();
9808     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9809     const SCEV *LoopCounter =
9810       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9811     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9812                       LatchBECount))
9813       return true;
9814   }
9815 
9816   // Check conditions due to any @llvm.assume intrinsics.
9817   for (auto &AssumeVH : AC.assumptions()) {
9818     if (!AssumeVH)
9819       continue;
9820     auto *CI = cast<CallInst>(AssumeVH);
9821     if (!DT.dominates(CI, Latch->getTerminator()))
9822       continue;
9823 
9824     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9825       return true;
9826   }
9827 
9828   // If the loop is not reachable from the entry block, we risk running into an
9829   // infinite loop as we walk up into the dom tree.  These loops do not matter
9830   // anyway, so we just return a conservative answer when we see them.
9831   if (!DT.isReachableFromEntry(L->getHeader()))
9832     return false;
9833 
9834   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9835     return true;
9836 
9837   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9838        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9839     assert(DTN && "should reach the loop header before reaching the root!");
9840 
9841     BasicBlock *BB = DTN->getBlock();
9842     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9843       return true;
9844 
9845     BasicBlock *PBB = BB->getSinglePredecessor();
9846     if (!PBB)
9847       continue;
9848 
9849     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9850     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9851       continue;
9852 
9853     Value *Condition = ContinuePredicate->getCondition();
9854 
9855     // If we have an edge `E` within the loop body that dominates the only
9856     // latch, the condition guarding `E` also guards the backedge.  This
9857     // reasoning works only for loops with a single latch.
9858 
9859     BasicBlockEdge DominatingEdge(PBB, BB);
9860     if (DominatingEdge.isSingleEdge()) {
9861       // We're constructively (and conservatively) enumerating edges within the
9862       // loop body that dominate the latch.  The dominator tree better agree
9863       // with us on this:
9864       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9865 
9866       if (isImpliedCond(Pred, LHS, RHS, Condition,
9867                         BB != ContinuePredicate->getSuccessor(0)))
9868         return true;
9869     }
9870   }
9871 
9872   return false;
9873 }
9874 
9875 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
9876                                                      ICmpInst::Predicate Pred,
9877                                                      const SCEV *LHS,
9878                                                      const SCEV *RHS) {
9879   if (VerifyIR)
9880     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
9881            "This cannot be done on broken IR!");
9882 
9883   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9884     return true;
9885 
9886   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9887   // the facts (a >= b && a != b) separately. A typical situation is when the
9888   // non-strict comparison is known from ranges and non-equality is known from
9889   // dominating predicates. If we are proving strict comparison, we always try
9890   // to prove non-equality and non-strict comparison separately.
9891   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9892   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9893   bool ProvedNonStrictComparison = false;
9894   bool ProvedNonEquality = false;
9895 
9896   if (ProvingStrictComparison) {
9897     ProvedNonStrictComparison =
9898         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9899     ProvedNonEquality =
9900         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9901     if (ProvedNonStrictComparison && ProvedNonEquality)
9902       return true;
9903   }
9904 
9905   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9906   auto ProveViaGuard = [&](const BasicBlock *Block) {
9907     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9908       return true;
9909     if (ProvingStrictComparison) {
9910       if (!ProvedNonStrictComparison)
9911         ProvedNonStrictComparison =
9912             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9913       if (!ProvedNonEquality)
9914         ProvedNonEquality =
9915             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9916       if (ProvedNonStrictComparison && ProvedNonEquality)
9917         return true;
9918     }
9919     return false;
9920   };
9921 
9922   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9923   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
9924     const Instruction *Context = &BB->front();
9925     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
9926       return true;
9927     if (ProvingStrictComparison) {
9928       if (!ProvedNonStrictComparison)
9929         ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS,
9930                                                   Condition, Inverse, Context);
9931       if (!ProvedNonEquality)
9932         ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS,
9933                                           Condition, Inverse, Context);
9934       if (ProvedNonStrictComparison && ProvedNonEquality)
9935         return true;
9936     }
9937     return false;
9938   };
9939 
9940   // Starting at the block's predecessor, climb up the predecessor chain, as long
9941   // as there are predecessors that can be found that have unique successors
9942   // leading to the original block.
9943   const Loop *ContainingLoop = LI.getLoopFor(BB);
9944   const BasicBlock *PredBB;
9945   if (ContainingLoop && ContainingLoop->getHeader() == BB)
9946     PredBB = ContainingLoop->getLoopPredecessor();
9947   else
9948     PredBB = BB->getSinglePredecessor();
9949   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
9950        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9951     if (ProveViaGuard(Pair.first))
9952       return true;
9953 
9954     const BranchInst *LoopEntryPredicate =
9955         dyn_cast<BranchInst>(Pair.first->getTerminator());
9956     if (!LoopEntryPredicate ||
9957         LoopEntryPredicate->isUnconditional())
9958       continue;
9959 
9960     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9961                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9962       return true;
9963   }
9964 
9965   // Check conditions due to any @llvm.assume intrinsics.
9966   for (auto &AssumeVH : AC.assumptions()) {
9967     if (!AssumeVH)
9968       continue;
9969     auto *CI = cast<CallInst>(AssumeVH);
9970     if (!DT.dominates(CI, BB))
9971       continue;
9972 
9973     if (ProveViaCond(CI->getArgOperand(0), false))
9974       return true;
9975   }
9976 
9977   return false;
9978 }
9979 
9980 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9981                                                ICmpInst::Predicate Pred,
9982                                                const SCEV *LHS,
9983                                                const SCEV *RHS) {
9984   // Interpret a null as meaning no loop, where there is obviously no guard
9985   // (interprocedural conditions notwithstanding).
9986   if (!L)
9987     return false;
9988 
9989   // Both LHS and RHS must be available at loop entry.
9990   assert(isAvailableAtLoopEntry(LHS, L) &&
9991          "LHS is not available at Loop Entry");
9992   assert(isAvailableAtLoopEntry(RHS, L) &&
9993          "RHS is not available at Loop Entry");
9994   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
9995 }
9996 
9997 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9998                                     const SCEV *RHS,
9999                                     const Value *FoundCondValue, bool Inverse,
10000                                     const Instruction *Context) {
10001   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10002     return false;
10003 
10004   auto ClearOnExit =
10005       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10006 
10007   // Recursively handle And and Or conditions.
10008   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
10009     if (BO->getOpcode() == Instruction::And) {
10010       if (!Inverse)
10011         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10012                              Context) ||
10013                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10014                              Context);
10015     } else if (BO->getOpcode() == Instruction::Or) {
10016       if (Inverse)
10017         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10018                              Context) ||
10019                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10020                              Context);
10021     }
10022   }
10023 
10024   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10025   if (!ICI) return false;
10026 
10027   // Now that we found a conditional branch that dominates the loop or controls
10028   // the loop latch. Check to see if it is the comparison we are looking for.
10029   ICmpInst::Predicate FoundPred;
10030   if (Inverse)
10031     FoundPred = ICI->getInversePredicate();
10032   else
10033     FoundPred = ICI->getPredicate();
10034 
10035   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10036   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10037 
10038   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10039 }
10040 
10041 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10042                                     const SCEV *RHS,
10043                                     ICmpInst::Predicate FoundPred,
10044                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10045                                     const Instruction *Context) {
10046   // Balance the types.
10047   if (getTypeSizeInBits(LHS->getType()) <
10048       getTypeSizeInBits(FoundLHS->getType())) {
10049     // For unsigned and equality predicates, try to prove that both found
10050     // operands fit into narrow unsigned range. If so, try to prove facts in
10051     // narrow types.
10052     if (!CmpInst::isSigned(FoundPred)) {
10053       auto *NarrowType = LHS->getType();
10054       auto *WideType = FoundLHS->getType();
10055       auto BitWidth = getTypeSizeInBits(NarrowType);
10056       const SCEV *MaxValue = getZeroExtendExpr(
10057           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10058       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10059           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10060         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10061         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10062         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10063                                        TruncFoundRHS, Context))
10064           return true;
10065       }
10066     }
10067 
10068     if (CmpInst::isSigned(Pred)) {
10069       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10070       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10071     } else {
10072       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10073       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10074     }
10075   } else if (getTypeSizeInBits(LHS->getType()) >
10076       getTypeSizeInBits(FoundLHS->getType())) {
10077     if (CmpInst::isSigned(FoundPred)) {
10078       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10079       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10080     } else {
10081       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10082       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10083     }
10084   }
10085   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10086                                     FoundRHS, Context);
10087 }
10088 
10089 bool ScalarEvolution::isImpliedCondBalancedTypes(
10090     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10091     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10092     const Instruction *Context) {
10093   assert(getTypeSizeInBits(LHS->getType()) ==
10094              getTypeSizeInBits(FoundLHS->getType()) &&
10095          "Types should be balanced!");
10096   // Canonicalize the query to match the way instcombine will have
10097   // canonicalized the comparison.
10098   if (SimplifyICmpOperands(Pred, LHS, RHS))
10099     if (LHS == RHS)
10100       return CmpInst::isTrueWhenEqual(Pred);
10101   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10102     if (FoundLHS == FoundRHS)
10103       return CmpInst::isFalseWhenEqual(FoundPred);
10104 
10105   // Check to see if we can make the LHS or RHS match.
10106   if (LHS == FoundRHS || RHS == FoundLHS) {
10107     if (isa<SCEVConstant>(RHS)) {
10108       std::swap(FoundLHS, FoundRHS);
10109       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10110     } else {
10111       std::swap(LHS, RHS);
10112       Pred = ICmpInst::getSwappedPredicate(Pred);
10113     }
10114   }
10115 
10116   // Check whether the found predicate is the same as the desired predicate.
10117   if (FoundPred == Pred)
10118     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10119 
10120   // Check whether swapping the found predicate makes it the same as the
10121   // desired predicate.
10122   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10123     if (isa<SCEVConstant>(RHS))
10124       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10125     else
10126       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS,
10127                                    LHS, FoundLHS, FoundRHS, Context);
10128   }
10129 
10130   // Unsigned comparison is the same as signed comparison when both the operands
10131   // are non-negative.
10132   if (CmpInst::isUnsigned(FoundPred) &&
10133       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10134       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10135     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10136 
10137   // Check if we can make progress by sharpening ranges.
10138   if (FoundPred == ICmpInst::ICMP_NE &&
10139       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10140 
10141     const SCEVConstant *C = nullptr;
10142     const SCEV *V = nullptr;
10143 
10144     if (isa<SCEVConstant>(FoundLHS)) {
10145       C = cast<SCEVConstant>(FoundLHS);
10146       V = FoundRHS;
10147     } else {
10148       C = cast<SCEVConstant>(FoundRHS);
10149       V = FoundLHS;
10150     }
10151 
10152     // The guarding predicate tells us that C != V. If the known range
10153     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10154     // range we consider has to correspond to same signedness as the
10155     // predicate we're interested in folding.
10156 
10157     APInt Min = ICmpInst::isSigned(Pred) ?
10158         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10159 
10160     if (Min == C->getAPInt()) {
10161       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10162       // This is true even if (Min + 1) wraps around -- in case of
10163       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10164 
10165       APInt SharperMin = Min + 1;
10166 
10167       switch (Pred) {
10168         case ICmpInst::ICMP_SGE:
10169         case ICmpInst::ICMP_UGE:
10170           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10171           // RHS, we're done.
10172           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10173                                     Context))
10174             return true;
10175           LLVM_FALLTHROUGH;
10176 
10177         case ICmpInst::ICMP_SGT:
10178         case ICmpInst::ICMP_UGT:
10179           // We know from the range information that (V `Pred` Min ||
10180           // V == Min).  We know from the guarding condition that !(V
10181           // == Min).  This gives us
10182           //
10183           //       V `Pred` Min || V == Min && !(V == Min)
10184           //   =>  V `Pred` Min
10185           //
10186           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10187 
10188           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10189                                     Context))
10190             return true;
10191           break;
10192 
10193         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10194         case ICmpInst::ICMP_SLE:
10195         case ICmpInst::ICMP_ULE:
10196           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10197                                     LHS, V, getConstant(SharperMin), Context))
10198             return true;
10199           LLVM_FALLTHROUGH;
10200 
10201         case ICmpInst::ICMP_SLT:
10202         case ICmpInst::ICMP_ULT:
10203           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10204                                     LHS, V, getConstant(Min), Context))
10205             return true;
10206           break;
10207 
10208         default:
10209           // No change
10210           break;
10211       }
10212     }
10213   }
10214 
10215   // Check whether the actual condition is beyond sufficient.
10216   if (FoundPred == ICmpInst::ICMP_EQ)
10217     if (ICmpInst::isTrueWhenEqual(Pred))
10218       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10219         return true;
10220   if (Pred == ICmpInst::ICMP_NE)
10221     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10222       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10223                                 Context))
10224         return true;
10225 
10226   // Otherwise assume the worst.
10227   return false;
10228 }
10229 
10230 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10231                                      const SCEV *&L, const SCEV *&R,
10232                                      SCEV::NoWrapFlags &Flags) {
10233   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10234   if (!AE || AE->getNumOperands() != 2)
10235     return false;
10236 
10237   L = AE->getOperand(0);
10238   R = AE->getOperand(1);
10239   Flags = AE->getNoWrapFlags();
10240   return true;
10241 }
10242 
10243 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10244                                                            const SCEV *Less) {
10245   // We avoid subtracting expressions here because this function is usually
10246   // fairly deep in the call stack (i.e. is called many times).
10247 
10248   // X - X = 0.
10249   if (More == Less)
10250     return APInt(getTypeSizeInBits(More->getType()), 0);
10251 
10252   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10253     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10254     const auto *MAR = cast<SCEVAddRecExpr>(More);
10255 
10256     if (LAR->getLoop() != MAR->getLoop())
10257       return None;
10258 
10259     // We look at affine expressions only; not for correctness but to keep
10260     // getStepRecurrence cheap.
10261     if (!LAR->isAffine() || !MAR->isAffine())
10262       return None;
10263 
10264     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10265       return None;
10266 
10267     Less = LAR->getStart();
10268     More = MAR->getStart();
10269 
10270     // fall through
10271   }
10272 
10273   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10274     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10275     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10276     return M - L;
10277   }
10278 
10279   SCEV::NoWrapFlags Flags;
10280   const SCEV *LLess = nullptr, *RLess = nullptr;
10281   const SCEV *LMore = nullptr, *RMore = nullptr;
10282   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10283   // Compare (X + C1) vs X.
10284   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10285     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10286       if (RLess == More)
10287         return -(C1->getAPInt());
10288 
10289   // Compare X vs (X + C2).
10290   if (splitBinaryAdd(More, LMore, RMore, Flags))
10291     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10292       if (RMore == Less)
10293         return C2->getAPInt();
10294 
10295   // Compare (X + C1) vs (X + C2).
10296   if (C1 && C2 && RLess == RMore)
10297     return C2->getAPInt() - C1->getAPInt();
10298 
10299   return None;
10300 }
10301 
10302 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10303     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10304     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10305   // Try to recognize the following pattern:
10306   //
10307   //   FoundRHS = ...
10308   // ...
10309   // loop:
10310   //   FoundLHS = {Start,+,W}
10311   // context_bb: // Basic block from the same loop
10312   //   known(Pred, FoundLHS, FoundRHS)
10313   //
10314   // If some predicate is known in the context of a loop, it is also known on
10315   // each iteration of this loop, including the first iteration. Therefore, in
10316   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10317   // prove the original pred using this fact.
10318   if (!Context)
10319     return false;
10320   const BasicBlock *ContextBB = Context->getParent();
10321   // Make sure AR varies in the context block.
10322   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10323     const Loop *L = AR->getLoop();
10324     // Make sure that context belongs to the loop and executes on 1st iteration
10325     // (if it ever executes at all).
10326     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10327       return false;
10328     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10329       return false;
10330     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10331   }
10332 
10333   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10334     const Loop *L = AR->getLoop();
10335     // Make sure that context belongs to the loop and executes on 1st iteration
10336     // (if it ever executes at all).
10337     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10338       return false;
10339     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10340       return false;
10341     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10342   }
10343 
10344   return false;
10345 }
10346 
10347 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10348     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10349     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10350   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10351     return false;
10352 
10353   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10354   if (!AddRecLHS)
10355     return false;
10356 
10357   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10358   if (!AddRecFoundLHS)
10359     return false;
10360 
10361   // We'd like to let SCEV reason about control dependencies, so we constrain
10362   // both the inequalities to be about add recurrences on the same loop.  This
10363   // way we can use isLoopEntryGuardedByCond later.
10364 
10365   const Loop *L = AddRecFoundLHS->getLoop();
10366   if (L != AddRecLHS->getLoop())
10367     return false;
10368 
10369   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10370   //
10371   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10372   //                                                                  ... (2)
10373   //
10374   // Informal proof for (2), assuming (1) [*]:
10375   //
10376   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10377   //
10378   // Then
10379   //
10380   //       FoundLHS s< FoundRHS s< INT_MIN - C
10381   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10382   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10383   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10384   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10385   // <=>  FoundLHS + C s< FoundRHS + C
10386   //
10387   // [*]: (1) can be proved by ruling out overflow.
10388   //
10389   // [**]: This can be proved by analyzing all the four possibilities:
10390   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10391   //    (A s>= 0, B s>= 0).
10392   //
10393   // Note:
10394   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10395   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10396   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10397   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10398   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10399   // C)".
10400 
10401   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10402   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10403   if (!LDiff || !RDiff || *LDiff != *RDiff)
10404     return false;
10405 
10406   if (LDiff->isMinValue())
10407     return true;
10408 
10409   APInt FoundRHSLimit;
10410 
10411   if (Pred == CmpInst::ICMP_ULT) {
10412     FoundRHSLimit = -(*RDiff);
10413   } else {
10414     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10415     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10416   }
10417 
10418   // Try to prove (1) or (2), as needed.
10419   return isAvailableAtLoopEntry(FoundRHS, L) &&
10420          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10421                                   getConstant(FoundRHSLimit));
10422 }
10423 
10424 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10425                                         const SCEV *LHS, const SCEV *RHS,
10426                                         const SCEV *FoundLHS,
10427                                         const SCEV *FoundRHS, unsigned Depth) {
10428   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10429 
10430   auto ClearOnExit = make_scope_exit([&]() {
10431     if (LPhi) {
10432       bool Erased = PendingMerges.erase(LPhi);
10433       assert(Erased && "Failed to erase LPhi!");
10434       (void)Erased;
10435     }
10436     if (RPhi) {
10437       bool Erased = PendingMerges.erase(RPhi);
10438       assert(Erased && "Failed to erase RPhi!");
10439       (void)Erased;
10440     }
10441   });
10442 
10443   // Find respective Phis and check that they are not being pending.
10444   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10445     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10446       if (!PendingMerges.insert(Phi).second)
10447         return false;
10448       LPhi = Phi;
10449     }
10450   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10451     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10452       // If we detect a loop of Phi nodes being processed by this method, for
10453       // example:
10454       //
10455       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10456       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10457       //
10458       // we don't want to deal with a case that complex, so return conservative
10459       // answer false.
10460       if (!PendingMerges.insert(Phi).second)
10461         return false;
10462       RPhi = Phi;
10463     }
10464 
10465   // If none of LHS, RHS is a Phi, nothing to do here.
10466   if (!LPhi && !RPhi)
10467     return false;
10468 
10469   // If there is a SCEVUnknown Phi we are interested in, make it left.
10470   if (!LPhi) {
10471     std::swap(LHS, RHS);
10472     std::swap(FoundLHS, FoundRHS);
10473     std::swap(LPhi, RPhi);
10474     Pred = ICmpInst::getSwappedPredicate(Pred);
10475   }
10476 
10477   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10478   const BasicBlock *LBB = LPhi->getParent();
10479   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10480 
10481   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10482     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10483            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10484            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10485   };
10486 
10487   if (RPhi && RPhi->getParent() == LBB) {
10488     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10489     // If we compare two Phis from the same block, and for each entry block
10490     // the predicate is true for incoming values from this block, then the
10491     // predicate is also true for the Phis.
10492     for (const BasicBlock *IncBB : predecessors(LBB)) {
10493       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10494       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10495       if (!ProvedEasily(L, R))
10496         return false;
10497     }
10498   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10499     // Case two: RHS is also a Phi from the same basic block, and it is an
10500     // AddRec. It means that there is a loop which has both AddRec and Unknown
10501     // PHIs, for it we can compare incoming values of AddRec from above the loop
10502     // and latch with their respective incoming values of LPhi.
10503     // TODO: Generalize to handle loops with many inputs in a header.
10504     if (LPhi->getNumIncomingValues() != 2) return false;
10505 
10506     auto *RLoop = RAR->getLoop();
10507     auto *Predecessor = RLoop->getLoopPredecessor();
10508     assert(Predecessor && "Loop with AddRec with no predecessor?");
10509     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10510     if (!ProvedEasily(L1, RAR->getStart()))
10511       return false;
10512     auto *Latch = RLoop->getLoopLatch();
10513     assert(Latch && "Loop with AddRec with no latch?");
10514     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10515     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10516       return false;
10517   } else {
10518     // In all other cases go over inputs of LHS and compare each of them to RHS,
10519     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10520     // At this point RHS is either a non-Phi, or it is a Phi from some block
10521     // different from LBB.
10522     for (const BasicBlock *IncBB : predecessors(LBB)) {
10523       // Check that RHS is available in this block.
10524       if (!dominates(RHS, IncBB))
10525         return false;
10526       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10527       if (!ProvedEasily(L, RHS))
10528         return false;
10529     }
10530   }
10531   return true;
10532 }
10533 
10534 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10535                                             const SCEV *LHS, const SCEV *RHS,
10536                                             const SCEV *FoundLHS,
10537                                             const SCEV *FoundRHS,
10538                                             const Instruction *Context) {
10539   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10540     return true;
10541 
10542   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10543     return true;
10544 
10545   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10546                                           Context))
10547     return true;
10548 
10549   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10550                                      FoundLHS, FoundRHS) ||
10551          // ~x < ~y --> x > y
10552          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10553                                      getNotSCEV(FoundRHS),
10554                                      getNotSCEV(FoundLHS));
10555 }
10556 
10557 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10558 template <typename MinMaxExprType>
10559 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10560                                  const SCEV *Candidate) {
10561   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10562   if (!MinMaxExpr)
10563     return false;
10564 
10565   return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10566 }
10567 
10568 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10569                                            ICmpInst::Predicate Pred,
10570                                            const SCEV *LHS, const SCEV *RHS) {
10571   // If both sides are affine addrecs for the same loop, with equal
10572   // steps, and we know the recurrences don't wrap, then we only
10573   // need to check the predicate on the starting values.
10574 
10575   if (!ICmpInst::isRelational(Pred))
10576     return false;
10577 
10578   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10579   if (!LAR)
10580     return false;
10581   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10582   if (!RAR)
10583     return false;
10584   if (LAR->getLoop() != RAR->getLoop())
10585     return false;
10586   if (!LAR->isAffine() || !RAR->isAffine())
10587     return false;
10588 
10589   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10590     return false;
10591 
10592   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10593                          SCEV::FlagNSW : SCEV::FlagNUW;
10594   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10595     return false;
10596 
10597   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10598 }
10599 
10600 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10601 /// expression?
10602 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10603                                         ICmpInst::Predicate Pred,
10604                                         const SCEV *LHS, const SCEV *RHS) {
10605   switch (Pred) {
10606   default:
10607     return false;
10608 
10609   case ICmpInst::ICMP_SGE:
10610     std::swap(LHS, RHS);
10611     LLVM_FALLTHROUGH;
10612   case ICmpInst::ICMP_SLE:
10613     return
10614         // min(A, ...) <= A
10615         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10616         // A <= max(A, ...)
10617         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10618 
10619   case ICmpInst::ICMP_UGE:
10620     std::swap(LHS, RHS);
10621     LLVM_FALLTHROUGH;
10622   case ICmpInst::ICMP_ULE:
10623     return
10624         // min(A, ...) <= A
10625         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10626         // A <= max(A, ...)
10627         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10628   }
10629 
10630   llvm_unreachable("covered switch fell through?!");
10631 }
10632 
10633 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10634                                              const SCEV *LHS, const SCEV *RHS,
10635                                              const SCEV *FoundLHS,
10636                                              const SCEV *FoundRHS,
10637                                              unsigned Depth) {
10638   assert(getTypeSizeInBits(LHS->getType()) ==
10639              getTypeSizeInBits(RHS->getType()) &&
10640          "LHS and RHS have different sizes?");
10641   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10642              getTypeSizeInBits(FoundRHS->getType()) &&
10643          "FoundLHS and FoundRHS have different sizes?");
10644   // We want to avoid hurting the compile time with analysis of too big trees.
10645   if (Depth > MaxSCEVOperationsImplicationDepth)
10646     return false;
10647 
10648   // We only want to work with GT comparison so far.
10649   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10650     Pred = CmpInst::getSwappedPredicate(Pred);
10651     std::swap(LHS, RHS);
10652     std::swap(FoundLHS, FoundRHS);
10653   }
10654 
10655   // For unsigned, try to reduce it to corresponding signed comparison.
10656   if (Pred == ICmpInst::ICMP_UGT)
10657     // We can replace unsigned predicate with its signed counterpart if all
10658     // involved values are non-negative.
10659     // TODO: We could have better support for unsigned.
10660     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10661       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10662       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10663       // use this fact to prove that LHS and RHS are non-negative.
10664       const SCEV *MinusOne = getMinusOne(LHS->getType());
10665       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10666                                 FoundRHS) &&
10667           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10668                                 FoundRHS))
10669         Pred = ICmpInst::ICMP_SGT;
10670     }
10671 
10672   if (Pred != ICmpInst::ICMP_SGT)
10673     return false;
10674 
10675   auto GetOpFromSExt = [&](const SCEV *S) {
10676     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10677       return Ext->getOperand();
10678     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10679     // the constant in some cases.
10680     return S;
10681   };
10682 
10683   // Acquire values from extensions.
10684   auto *OrigLHS = LHS;
10685   auto *OrigFoundLHS = FoundLHS;
10686   LHS = GetOpFromSExt(LHS);
10687   FoundLHS = GetOpFromSExt(FoundLHS);
10688 
10689   // Is the SGT predicate can be proved trivially or using the found context.
10690   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10691     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10692            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10693                                   FoundRHS, Depth + 1);
10694   };
10695 
10696   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10697     // We want to avoid creation of any new non-constant SCEV. Since we are
10698     // going to compare the operands to RHS, we should be certain that we don't
10699     // need any size extensions for this. So let's decline all cases when the
10700     // sizes of types of LHS and RHS do not match.
10701     // TODO: Maybe try to get RHS from sext to catch more cases?
10702     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10703       return false;
10704 
10705     // Should not overflow.
10706     if (!LHSAddExpr->hasNoSignedWrap())
10707       return false;
10708 
10709     auto *LL = LHSAddExpr->getOperand(0);
10710     auto *LR = LHSAddExpr->getOperand(1);
10711     auto *MinusOne = getMinusOne(RHS->getType());
10712 
10713     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10714     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10715       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10716     };
10717     // Try to prove the following rule:
10718     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10719     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10720     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10721       return true;
10722   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10723     Value *LL, *LR;
10724     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10725 
10726     using namespace llvm::PatternMatch;
10727 
10728     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10729       // Rules for division.
10730       // We are going to perform some comparisons with Denominator and its
10731       // derivative expressions. In general case, creating a SCEV for it may
10732       // lead to a complex analysis of the entire graph, and in particular it
10733       // can request trip count recalculation for the same loop. This would
10734       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10735       // this, we only want to create SCEVs that are constants in this section.
10736       // So we bail if Denominator is not a constant.
10737       if (!isa<ConstantInt>(LR))
10738         return false;
10739 
10740       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10741 
10742       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10743       // then a SCEV for the numerator already exists and matches with FoundLHS.
10744       auto *Numerator = getExistingSCEV(LL);
10745       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10746         return false;
10747 
10748       // Make sure that the numerator matches with FoundLHS and the denominator
10749       // is positive.
10750       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10751         return false;
10752 
10753       auto *DTy = Denominator->getType();
10754       auto *FRHSTy = FoundRHS->getType();
10755       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10756         // One of types is a pointer and another one is not. We cannot extend
10757         // them properly to a wider type, so let us just reject this case.
10758         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10759         // to avoid this check.
10760         return false;
10761 
10762       // Given that:
10763       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10764       auto *WTy = getWiderType(DTy, FRHSTy);
10765       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10766       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10767 
10768       // Try to prove the following rule:
10769       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10770       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10771       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10772       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10773       if (isKnownNonPositive(RHS) &&
10774           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10775         return true;
10776 
10777       // Try to prove the following rule:
10778       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10779       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10780       // If we divide it by Denominator > 2, then:
10781       // 1. If FoundLHS is negative, then the result is 0.
10782       // 2. If FoundLHS is non-negative, then the result is non-negative.
10783       // Anyways, the result is non-negative.
10784       auto *MinusOne = getMinusOne(WTy);
10785       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10786       if (isKnownNegative(RHS) &&
10787           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10788         return true;
10789     }
10790   }
10791 
10792   // If our expression contained SCEVUnknown Phis, and we split it down and now
10793   // need to prove something for them, try to prove the predicate for every
10794   // possible incoming values of those Phis.
10795   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10796     return true;
10797 
10798   return false;
10799 }
10800 
10801 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10802                                         const SCEV *LHS, const SCEV *RHS) {
10803   // zext x u<= sext x, sext x s<= zext x
10804   switch (Pred) {
10805   case ICmpInst::ICMP_SGE:
10806     std::swap(LHS, RHS);
10807     LLVM_FALLTHROUGH;
10808   case ICmpInst::ICMP_SLE: {
10809     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
10810     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10811     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10812     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10813       return true;
10814     break;
10815   }
10816   case ICmpInst::ICMP_UGE:
10817     std::swap(LHS, RHS);
10818     LLVM_FALLTHROUGH;
10819   case ICmpInst::ICMP_ULE: {
10820     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
10821     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10822     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10823     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10824       return true;
10825     break;
10826   }
10827   default:
10828     break;
10829   };
10830   return false;
10831 }
10832 
10833 bool
10834 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10835                                            const SCEV *LHS, const SCEV *RHS) {
10836   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10837          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10838          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10839          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10840          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10841 }
10842 
10843 bool
10844 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10845                                              const SCEV *LHS, const SCEV *RHS,
10846                                              const SCEV *FoundLHS,
10847                                              const SCEV *FoundRHS) {
10848   switch (Pred) {
10849   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10850   case ICmpInst::ICMP_EQ:
10851   case ICmpInst::ICMP_NE:
10852     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10853       return true;
10854     break;
10855   case ICmpInst::ICMP_SLT:
10856   case ICmpInst::ICMP_SLE:
10857     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10858         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10859       return true;
10860     break;
10861   case ICmpInst::ICMP_SGT:
10862   case ICmpInst::ICMP_SGE:
10863     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10864         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10865       return true;
10866     break;
10867   case ICmpInst::ICMP_ULT:
10868   case ICmpInst::ICMP_ULE:
10869     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10870         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10871       return true;
10872     break;
10873   case ICmpInst::ICMP_UGT:
10874   case ICmpInst::ICMP_UGE:
10875     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10876         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10877       return true;
10878     break;
10879   }
10880 
10881   // Maybe it can be proved via operations?
10882   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10883     return true;
10884 
10885   return false;
10886 }
10887 
10888 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10889                                                      const SCEV *LHS,
10890                                                      const SCEV *RHS,
10891                                                      const SCEV *FoundLHS,
10892                                                      const SCEV *FoundRHS) {
10893   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10894     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10895     // reduce the compile time impact of this optimization.
10896     return false;
10897 
10898   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10899   if (!Addend)
10900     return false;
10901 
10902   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10903 
10904   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10905   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10906   ConstantRange FoundLHSRange =
10907       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10908 
10909   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10910   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10911 
10912   // We can also compute the range of values for `LHS` that satisfy the
10913   // consequent, "`LHS` `Pred` `RHS`":
10914   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10915   ConstantRange SatisfyingLHSRange =
10916       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10917 
10918   // The antecedent implies the consequent if every value of `LHS` that
10919   // satisfies the antecedent also satisfies the consequent.
10920   return SatisfyingLHSRange.contains(LHSRange);
10921 }
10922 
10923 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10924                                          bool IsSigned, bool NoWrap) {
10925   assert(isKnownPositive(Stride) && "Positive stride expected!");
10926 
10927   if (NoWrap) return false;
10928 
10929   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10930   const SCEV *One = getOne(Stride->getType());
10931 
10932   if (IsSigned) {
10933     APInt MaxRHS = getSignedRangeMax(RHS);
10934     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10935     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10936 
10937     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10938     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10939   }
10940 
10941   APInt MaxRHS = getUnsignedRangeMax(RHS);
10942   APInt MaxValue = APInt::getMaxValue(BitWidth);
10943   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10944 
10945   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10946   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10947 }
10948 
10949 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10950                                          bool IsSigned, bool NoWrap) {
10951   if (NoWrap) return false;
10952 
10953   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10954   const SCEV *One = getOne(Stride->getType());
10955 
10956   if (IsSigned) {
10957     APInt MinRHS = getSignedRangeMin(RHS);
10958     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10959     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10960 
10961     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10962     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10963   }
10964 
10965   APInt MinRHS = getUnsignedRangeMin(RHS);
10966   APInt MinValue = APInt::getMinValue(BitWidth);
10967   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10968 
10969   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10970   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10971 }
10972 
10973 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10974                                             bool Equality) {
10975   const SCEV *One = getOne(Step->getType());
10976   Delta = Equality ? getAddExpr(Delta, Step)
10977                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10978   return getUDivExpr(Delta, Step);
10979 }
10980 
10981 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10982                                                     const SCEV *Stride,
10983                                                     const SCEV *End,
10984                                                     unsigned BitWidth,
10985                                                     bool IsSigned) {
10986 
10987   assert(!isKnownNonPositive(Stride) &&
10988          "Stride is expected strictly positive!");
10989   // Calculate the maximum backedge count based on the range of values
10990   // permitted by Start, End, and Stride.
10991   const SCEV *MaxBECount;
10992   APInt MinStart =
10993       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10994 
10995   APInt StrideForMaxBECount =
10996       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10997 
10998   // We already know that the stride is positive, so we paper over conservatism
10999   // in our range computation by forcing StrideForMaxBECount to be at least one.
11000   // In theory this is unnecessary, but we expect MaxBECount to be a
11001   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11002   // is nothing to constant fold it to).
11003   APInt One(BitWidth, 1, IsSigned);
11004   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11005 
11006   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11007                             : APInt::getMaxValue(BitWidth);
11008   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11009 
11010   // Although End can be a MAX expression we estimate MaxEnd considering only
11011   // the case End = RHS of the loop termination condition. This is safe because
11012   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11013   // taken count.
11014   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11015                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11016 
11017   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11018                               getConstant(StrideForMaxBECount) /* Step */,
11019                               false /* Equality */);
11020 
11021   return MaxBECount;
11022 }
11023 
11024 ScalarEvolution::ExitLimit
11025 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11026                                   const Loop *L, bool IsSigned,
11027                                   bool ControlsExit, bool AllowPredicates) {
11028   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11029 
11030   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11031   bool PredicatedIV = false;
11032 
11033   if (!IV && AllowPredicates) {
11034     // Try to make this an AddRec using runtime tests, in the first X
11035     // iterations of this loop, where X is the SCEV expression found by the
11036     // algorithm below.
11037     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11038     PredicatedIV = true;
11039   }
11040 
11041   // Avoid weird loops
11042   if (!IV || IV->getLoop() != L || !IV->isAffine())
11043     return getCouldNotCompute();
11044 
11045   bool NoWrap = ControlsExit &&
11046                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11047 
11048   const SCEV *Stride = IV->getStepRecurrence(*this);
11049 
11050   bool PositiveStride = isKnownPositive(Stride);
11051 
11052   // Avoid negative or zero stride values.
11053   if (!PositiveStride) {
11054     // We can compute the correct backedge taken count for loops with unknown
11055     // strides if we can prove that the loop is not an infinite loop with side
11056     // effects. Here's the loop structure we are trying to handle -
11057     //
11058     // i = start
11059     // do {
11060     //   A[i] = i;
11061     //   i += s;
11062     // } while (i < end);
11063     //
11064     // The backedge taken count for such loops is evaluated as -
11065     // (max(end, start + stride) - start - 1) /u stride
11066     //
11067     // The additional preconditions that we need to check to prove correctness
11068     // of the above formula is as follows -
11069     //
11070     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11071     //    NoWrap flag).
11072     // b) loop is single exit with no side effects.
11073     //
11074     //
11075     // Precondition a) implies that if the stride is negative, this is a single
11076     // trip loop. The backedge taken count formula reduces to zero in this case.
11077     //
11078     // Precondition b) implies that the unknown stride cannot be zero otherwise
11079     // we have UB.
11080     //
11081     // The positive stride case is the same as isKnownPositive(Stride) returning
11082     // true (original behavior of the function).
11083     //
11084     // We want to make sure that the stride is truly unknown as there are edge
11085     // cases where ScalarEvolution propagates no wrap flags to the
11086     // post-increment/decrement IV even though the increment/decrement operation
11087     // itself is wrapping. The computed backedge taken count may be wrong in
11088     // such cases. This is prevented by checking that the stride is not known to
11089     // be either positive or non-positive. For example, no wrap flags are
11090     // propagated to the post-increment IV of this loop with a trip count of 2 -
11091     //
11092     // unsigned char i;
11093     // for(i=127; i<128; i+=129)
11094     //   A[i] = i;
11095     //
11096     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11097         !loopHasNoSideEffects(L))
11098       return getCouldNotCompute();
11099   } else if (!Stride->isOne() &&
11100              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11101     // Avoid proven overflow cases: this will ensure that the backedge taken
11102     // count will not generate any unsigned overflow. Relaxed no-overflow
11103     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11104     // undefined behaviors like the case of C language.
11105     return getCouldNotCompute();
11106 
11107   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11108                                       : ICmpInst::ICMP_ULT;
11109   const SCEV *Start = IV->getStart();
11110   const SCEV *End = RHS;
11111   // When the RHS is not invariant, we do not know the end bound of the loop and
11112   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11113   // calculate the MaxBECount, given the start, stride and max value for the end
11114   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11115   // checked above).
11116   if (!isLoopInvariant(RHS, L)) {
11117     const SCEV *MaxBECount = computeMaxBECountForLT(
11118         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11119     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11120                      false /*MaxOrZero*/, Predicates);
11121   }
11122   // If the backedge is taken at least once, then it will be taken
11123   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11124   // is the LHS value of the less-than comparison the first time it is evaluated
11125   // and End is the RHS.
11126   const SCEV *BECountIfBackedgeTaken =
11127     computeBECount(getMinusSCEV(End, Start), Stride, false);
11128   // If the loop entry is guarded by the result of the backedge test of the
11129   // first loop iteration, then we know the backedge will be taken at least
11130   // once and so the backedge taken count is as above. If not then we use the
11131   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11132   // as if the backedge is taken at least once max(End,Start) is End and so the
11133   // result is as above, and if not max(End,Start) is Start so we get a backedge
11134   // count of zero.
11135   const SCEV *BECount;
11136   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11137     BECount = BECountIfBackedgeTaken;
11138   else {
11139     // If we know that RHS >= Start in the context of loop, then we know that
11140     // max(RHS, Start) = RHS at this point.
11141     if (isLoopEntryGuardedByCond(
11142             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11143       End = RHS;
11144     else
11145       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11146     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11147   }
11148 
11149   const SCEV *MaxBECount;
11150   bool MaxOrZero = false;
11151   if (isa<SCEVConstant>(BECount))
11152     MaxBECount = BECount;
11153   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11154     // If we know exactly how many times the backedge will be taken if it's
11155     // taken at least once, then the backedge count will either be that or
11156     // zero.
11157     MaxBECount = BECountIfBackedgeTaken;
11158     MaxOrZero = true;
11159   } else {
11160     MaxBECount = computeMaxBECountForLT(
11161         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11162   }
11163 
11164   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11165       !isa<SCEVCouldNotCompute>(BECount))
11166     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11167 
11168   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11169 }
11170 
11171 ScalarEvolution::ExitLimit
11172 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11173                                      const Loop *L, bool IsSigned,
11174                                      bool ControlsExit, bool AllowPredicates) {
11175   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11176   // We handle only IV > Invariant
11177   if (!isLoopInvariant(RHS, L))
11178     return getCouldNotCompute();
11179 
11180   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11181   if (!IV && AllowPredicates)
11182     // Try to make this an AddRec using runtime tests, in the first X
11183     // iterations of this loop, where X is the SCEV expression found by the
11184     // algorithm below.
11185     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11186 
11187   // Avoid weird loops
11188   if (!IV || IV->getLoop() != L || !IV->isAffine())
11189     return getCouldNotCompute();
11190 
11191   bool NoWrap = ControlsExit &&
11192                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11193 
11194   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11195 
11196   // Avoid negative or zero stride values
11197   if (!isKnownPositive(Stride))
11198     return getCouldNotCompute();
11199 
11200   // Avoid proven overflow cases: this will ensure that the backedge taken count
11201   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11202   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11203   // behaviors like the case of C language.
11204   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11205     return getCouldNotCompute();
11206 
11207   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11208                                       : ICmpInst::ICMP_UGT;
11209 
11210   const SCEV *Start = IV->getStart();
11211   const SCEV *End = RHS;
11212   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11213     // If we know that Start >= RHS in the context of loop, then we know that
11214     // min(RHS, Start) = RHS at this point.
11215     if (isLoopEntryGuardedByCond(
11216             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11217       End = RHS;
11218     else
11219       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11220   }
11221 
11222   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11223 
11224   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11225                             : getUnsignedRangeMax(Start);
11226 
11227   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11228                              : getUnsignedRangeMin(Stride);
11229 
11230   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11231   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11232                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11233 
11234   // Although End can be a MIN expression we estimate MinEnd considering only
11235   // the case End = RHS. This is safe because in the other case (Start - End)
11236   // is zero, leading to a zero maximum backedge taken count.
11237   APInt MinEnd =
11238     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11239              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11240 
11241   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11242                                ? BECount
11243                                : computeBECount(getConstant(MaxStart - MinEnd),
11244                                                 getConstant(MinStride), false);
11245 
11246   if (isa<SCEVCouldNotCompute>(MaxBECount))
11247     MaxBECount = BECount;
11248 
11249   return ExitLimit(BECount, MaxBECount, false, Predicates);
11250 }
11251 
11252 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11253                                                     ScalarEvolution &SE) const {
11254   if (Range.isFullSet())  // Infinite loop.
11255     return SE.getCouldNotCompute();
11256 
11257   // If the start is a non-zero constant, shift the range to simplify things.
11258   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11259     if (!SC->getValue()->isZero()) {
11260       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
11261       Operands[0] = SE.getZero(SC->getType());
11262       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11263                                              getNoWrapFlags(FlagNW));
11264       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11265         return ShiftedAddRec->getNumIterationsInRange(
11266             Range.subtract(SC->getAPInt()), SE);
11267       // This is strange and shouldn't happen.
11268       return SE.getCouldNotCompute();
11269     }
11270 
11271   // The only time we can solve this is when we have all constant indices.
11272   // Otherwise, we cannot determine the overflow conditions.
11273   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11274     return SE.getCouldNotCompute();
11275 
11276   // Okay at this point we know that all elements of the chrec are constants and
11277   // that the start element is zero.
11278 
11279   // First check to see if the range contains zero.  If not, the first
11280   // iteration exits.
11281   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11282   if (!Range.contains(APInt(BitWidth, 0)))
11283     return SE.getZero(getType());
11284 
11285   if (isAffine()) {
11286     // If this is an affine expression then we have this situation:
11287     //   Solve {0,+,A} in Range  ===  Ax in Range
11288 
11289     // We know that zero is in the range.  If A is positive then we know that
11290     // the upper value of the range must be the first possible exit value.
11291     // If A is negative then the lower of the range is the last possible loop
11292     // value.  Also note that we already checked for a full range.
11293     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11294     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11295 
11296     // The exit value should be (End+A)/A.
11297     APInt ExitVal = (End + A).udiv(A);
11298     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11299 
11300     // Evaluate at the exit value.  If we really did fall out of the valid
11301     // range, then we computed our trip count, otherwise wrap around or other
11302     // things must have happened.
11303     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11304     if (Range.contains(Val->getValue()))
11305       return SE.getCouldNotCompute();  // Something strange happened
11306 
11307     // Ensure that the previous value is in the range.  This is a sanity check.
11308     assert(Range.contains(
11309            EvaluateConstantChrecAtConstant(this,
11310            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11311            "Linear scev computation is off in a bad way!");
11312     return SE.getConstant(ExitValue);
11313   }
11314 
11315   if (isQuadratic()) {
11316     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11317       return SE.getConstant(S.getValue());
11318   }
11319 
11320   return SE.getCouldNotCompute();
11321 }
11322 
11323 const SCEVAddRecExpr *
11324 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11325   assert(getNumOperands() > 1 && "AddRec with zero step?");
11326   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11327   // but in this case we cannot guarantee that the value returned will be an
11328   // AddRec because SCEV does not have a fixed point where it stops
11329   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11330   // may happen if we reach arithmetic depth limit while simplifying. So we
11331   // construct the returned value explicitly.
11332   SmallVector<const SCEV *, 3> Ops;
11333   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11334   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11335   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11336     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11337   // We know that the last operand is not a constant zero (otherwise it would
11338   // have been popped out earlier). This guarantees us that if the result has
11339   // the same last operand, then it will also not be popped out, meaning that
11340   // the returned value will be an AddRec.
11341   const SCEV *Last = getOperand(getNumOperands() - 1);
11342   assert(!Last->isZero() && "Recurrency with zero step?");
11343   Ops.push_back(Last);
11344   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11345                                                SCEV::FlagAnyWrap));
11346 }
11347 
11348 // Return true when S contains at least an undef value.
11349 static inline bool containsUndefs(const SCEV *S) {
11350   return SCEVExprContains(S, [](const SCEV *S) {
11351     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11352       return isa<UndefValue>(SU->getValue());
11353     return false;
11354   });
11355 }
11356 
11357 namespace {
11358 
11359 // Collect all steps of SCEV expressions.
11360 struct SCEVCollectStrides {
11361   ScalarEvolution &SE;
11362   SmallVectorImpl<const SCEV *> &Strides;
11363 
11364   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11365       : SE(SE), Strides(S) {}
11366 
11367   bool follow(const SCEV *S) {
11368     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11369       Strides.push_back(AR->getStepRecurrence(SE));
11370     return true;
11371   }
11372 
11373   bool isDone() const { return false; }
11374 };
11375 
11376 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11377 struct SCEVCollectTerms {
11378   SmallVectorImpl<const SCEV *> &Terms;
11379 
11380   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11381 
11382   bool follow(const SCEV *S) {
11383     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11384         isa<SCEVSignExtendExpr>(S)) {
11385       if (!containsUndefs(S))
11386         Terms.push_back(S);
11387 
11388       // Stop recursion: once we collected a term, do not walk its operands.
11389       return false;
11390     }
11391 
11392     // Keep looking.
11393     return true;
11394   }
11395 
11396   bool isDone() const { return false; }
11397 };
11398 
11399 // Check if a SCEV contains an AddRecExpr.
11400 struct SCEVHasAddRec {
11401   bool &ContainsAddRec;
11402 
11403   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11404     ContainsAddRec = false;
11405   }
11406 
11407   bool follow(const SCEV *S) {
11408     if (isa<SCEVAddRecExpr>(S)) {
11409       ContainsAddRec = true;
11410 
11411       // Stop recursion: once we collected a term, do not walk its operands.
11412       return false;
11413     }
11414 
11415     // Keep looking.
11416     return true;
11417   }
11418 
11419   bool isDone() const { return false; }
11420 };
11421 
11422 // Find factors that are multiplied with an expression that (possibly as a
11423 // subexpression) contains an AddRecExpr. In the expression:
11424 //
11425 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11426 //
11427 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11428 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11429 // parameters as they form a product with an induction variable.
11430 //
11431 // This collector expects all array size parameters to be in the same MulExpr.
11432 // It might be necessary to later add support for collecting parameters that are
11433 // spread over different nested MulExpr.
11434 struct SCEVCollectAddRecMultiplies {
11435   SmallVectorImpl<const SCEV *> &Terms;
11436   ScalarEvolution &SE;
11437 
11438   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11439       : Terms(T), SE(SE) {}
11440 
11441   bool follow(const SCEV *S) {
11442     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11443       bool HasAddRec = false;
11444       SmallVector<const SCEV *, 0> Operands;
11445       for (auto Op : Mul->operands()) {
11446         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11447         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11448           Operands.push_back(Op);
11449         } else if (Unknown) {
11450           HasAddRec = true;
11451         } else {
11452           bool ContainsAddRec = false;
11453           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11454           visitAll(Op, ContiansAddRec);
11455           HasAddRec |= ContainsAddRec;
11456         }
11457       }
11458       if (Operands.size() == 0)
11459         return true;
11460 
11461       if (!HasAddRec)
11462         return false;
11463 
11464       Terms.push_back(SE.getMulExpr(Operands));
11465       // Stop recursion: once we collected a term, do not walk its operands.
11466       return false;
11467     }
11468 
11469     // Keep looking.
11470     return true;
11471   }
11472 
11473   bool isDone() const { return false; }
11474 };
11475 
11476 } // end anonymous namespace
11477 
11478 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11479 /// two places:
11480 ///   1) The strides of AddRec expressions.
11481 ///   2) Unknowns that are multiplied with AddRec expressions.
11482 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11483     SmallVectorImpl<const SCEV *> &Terms) {
11484   SmallVector<const SCEV *, 4> Strides;
11485   SCEVCollectStrides StrideCollector(*this, Strides);
11486   visitAll(Expr, StrideCollector);
11487 
11488   LLVM_DEBUG({
11489     dbgs() << "Strides:\n";
11490     for (const SCEV *S : Strides)
11491       dbgs() << *S << "\n";
11492   });
11493 
11494   for (const SCEV *S : Strides) {
11495     SCEVCollectTerms TermCollector(Terms);
11496     visitAll(S, TermCollector);
11497   }
11498 
11499   LLVM_DEBUG({
11500     dbgs() << "Terms:\n";
11501     for (const SCEV *T : Terms)
11502       dbgs() << *T << "\n";
11503   });
11504 
11505   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11506   visitAll(Expr, MulCollector);
11507 }
11508 
11509 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11510                                    SmallVectorImpl<const SCEV *> &Terms,
11511                                    SmallVectorImpl<const SCEV *> &Sizes) {
11512   int Last = Terms.size() - 1;
11513   const SCEV *Step = Terms[Last];
11514 
11515   // End of recursion.
11516   if (Last == 0) {
11517     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11518       SmallVector<const SCEV *, 2> Qs;
11519       for (const SCEV *Op : M->operands())
11520         if (!isa<SCEVConstant>(Op))
11521           Qs.push_back(Op);
11522 
11523       Step = SE.getMulExpr(Qs);
11524     }
11525 
11526     Sizes.push_back(Step);
11527     return true;
11528   }
11529 
11530   for (const SCEV *&Term : Terms) {
11531     // Normalize the terms before the next call to findArrayDimensionsRec.
11532     const SCEV *Q, *R;
11533     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11534 
11535     // Bail out when GCD does not evenly divide one of the terms.
11536     if (!R->isZero())
11537       return false;
11538 
11539     Term = Q;
11540   }
11541 
11542   // Remove all SCEVConstants.
11543   Terms.erase(
11544       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11545       Terms.end());
11546 
11547   if (Terms.size() > 0)
11548     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11549       return false;
11550 
11551   Sizes.push_back(Step);
11552   return true;
11553 }
11554 
11555 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11556 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11557   for (const SCEV *T : Terms)
11558     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11559       return true;
11560 
11561   return false;
11562 }
11563 
11564 // Return the number of product terms in S.
11565 static inline int numberOfTerms(const SCEV *S) {
11566   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11567     return Expr->getNumOperands();
11568   return 1;
11569 }
11570 
11571 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11572   if (isa<SCEVConstant>(T))
11573     return nullptr;
11574 
11575   if (isa<SCEVUnknown>(T))
11576     return T;
11577 
11578   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11579     SmallVector<const SCEV *, 2> Factors;
11580     for (const SCEV *Op : M->operands())
11581       if (!isa<SCEVConstant>(Op))
11582         Factors.push_back(Op);
11583 
11584     return SE.getMulExpr(Factors);
11585   }
11586 
11587   return T;
11588 }
11589 
11590 /// Return the size of an element read or written by Inst.
11591 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11592   Type *Ty;
11593   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11594     Ty = Store->getValueOperand()->getType();
11595   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11596     Ty = Load->getType();
11597   else
11598     return nullptr;
11599 
11600   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11601   return getSizeOfExpr(ETy, Ty);
11602 }
11603 
11604 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11605                                           SmallVectorImpl<const SCEV *> &Sizes,
11606                                           const SCEV *ElementSize) {
11607   if (Terms.size() < 1 || !ElementSize)
11608     return;
11609 
11610   // Early return when Terms do not contain parameters: we do not delinearize
11611   // non parametric SCEVs.
11612   if (!containsParameters(Terms))
11613     return;
11614 
11615   LLVM_DEBUG({
11616     dbgs() << "Terms:\n";
11617     for (const SCEV *T : Terms)
11618       dbgs() << *T << "\n";
11619   });
11620 
11621   // Remove duplicates.
11622   array_pod_sort(Terms.begin(), Terms.end());
11623   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11624 
11625   // Put larger terms first.
11626   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11627     return numberOfTerms(LHS) > numberOfTerms(RHS);
11628   });
11629 
11630   // Try to divide all terms by the element size. If term is not divisible by
11631   // element size, proceed with the original term.
11632   for (const SCEV *&Term : Terms) {
11633     const SCEV *Q, *R;
11634     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11635     if (!Q->isZero())
11636       Term = Q;
11637   }
11638 
11639   SmallVector<const SCEV *, 4> NewTerms;
11640 
11641   // Remove constant factors.
11642   for (const SCEV *T : Terms)
11643     if (const SCEV *NewT = removeConstantFactors(*this, T))
11644       NewTerms.push_back(NewT);
11645 
11646   LLVM_DEBUG({
11647     dbgs() << "Terms after sorting:\n";
11648     for (const SCEV *T : NewTerms)
11649       dbgs() << *T << "\n";
11650   });
11651 
11652   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11653     Sizes.clear();
11654     return;
11655   }
11656 
11657   // The last element to be pushed into Sizes is the size of an element.
11658   Sizes.push_back(ElementSize);
11659 
11660   LLVM_DEBUG({
11661     dbgs() << "Sizes:\n";
11662     for (const SCEV *S : Sizes)
11663       dbgs() << *S << "\n";
11664   });
11665 }
11666 
11667 void ScalarEvolution::computeAccessFunctions(
11668     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11669     SmallVectorImpl<const SCEV *> &Sizes) {
11670   // Early exit in case this SCEV is not an affine multivariate function.
11671   if (Sizes.empty())
11672     return;
11673 
11674   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11675     if (!AR->isAffine())
11676       return;
11677 
11678   const SCEV *Res = Expr;
11679   int Last = Sizes.size() - 1;
11680   for (int i = Last; i >= 0; i--) {
11681     const SCEV *Q, *R;
11682     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11683 
11684     LLVM_DEBUG({
11685       dbgs() << "Res: " << *Res << "\n";
11686       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11687       dbgs() << "Res divided by Sizes[i]:\n";
11688       dbgs() << "Quotient: " << *Q << "\n";
11689       dbgs() << "Remainder: " << *R << "\n";
11690     });
11691 
11692     Res = Q;
11693 
11694     // Do not record the last subscript corresponding to the size of elements in
11695     // the array.
11696     if (i == Last) {
11697 
11698       // Bail out if the remainder is too complex.
11699       if (isa<SCEVAddRecExpr>(R)) {
11700         Subscripts.clear();
11701         Sizes.clear();
11702         return;
11703       }
11704 
11705       continue;
11706     }
11707 
11708     // Record the access function for the current subscript.
11709     Subscripts.push_back(R);
11710   }
11711 
11712   // Also push in last position the remainder of the last division: it will be
11713   // the access function of the innermost dimension.
11714   Subscripts.push_back(Res);
11715 
11716   std::reverse(Subscripts.begin(), Subscripts.end());
11717 
11718   LLVM_DEBUG({
11719     dbgs() << "Subscripts:\n";
11720     for (const SCEV *S : Subscripts)
11721       dbgs() << *S << "\n";
11722   });
11723 }
11724 
11725 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11726 /// sizes of an array access. Returns the remainder of the delinearization that
11727 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11728 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11729 /// expressions in the stride and base of a SCEV corresponding to the
11730 /// computation of a GCD (greatest common divisor) of base and stride.  When
11731 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11732 ///
11733 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11734 ///
11735 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11736 ///
11737 ///    for (long i = 0; i < n; i++)
11738 ///      for (long j = 0; j < m; j++)
11739 ///        for (long k = 0; k < o; k++)
11740 ///          A[i][j][k] = 1.0;
11741 ///  }
11742 ///
11743 /// the delinearization input is the following AddRec SCEV:
11744 ///
11745 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11746 ///
11747 /// From this SCEV, we are able to say that the base offset of the access is %A
11748 /// because it appears as an offset that does not divide any of the strides in
11749 /// the loops:
11750 ///
11751 ///  CHECK: Base offset: %A
11752 ///
11753 /// and then SCEV->delinearize determines the size of some of the dimensions of
11754 /// the array as these are the multiples by which the strides are happening:
11755 ///
11756 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11757 ///
11758 /// Note that the outermost dimension remains of UnknownSize because there are
11759 /// no strides that would help identifying the size of the last dimension: when
11760 /// the array has been statically allocated, one could compute the size of that
11761 /// dimension by dividing the overall size of the array by the size of the known
11762 /// dimensions: %m * %o * 8.
11763 ///
11764 /// Finally delinearize provides the access functions for the array reference
11765 /// that does correspond to A[i][j][k] of the above C testcase:
11766 ///
11767 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11768 ///
11769 /// The testcases are checking the output of a function pass:
11770 /// DelinearizationPass that walks through all loads and stores of a function
11771 /// asking for the SCEV of the memory access with respect to all enclosing
11772 /// loops, calling SCEV->delinearize on that and printing the results.
11773 void ScalarEvolution::delinearize(const SCEV *Expr,
11774                                  SmallVectorImpl<const SCEV *> &Subscripts,
11775                                  SmallVectorImpl<const SCEV *> &Sizes,
11776                                  const SCEV *ElementSize) {
11777   // First step: collect parametric terms.
11778   SmallVector<const SCEV *, 4> Terms;
11779   collectParametricTerms(Expr, Terms);
11780 
11781   if (Terms.empty())
11782     return;
11783 
11784   // Second step: find subscript sizes.
11785   findArrayDimensions(Terms, Sizes, ElementSize);
11786 
11787   if (Sizes.empty())
11788     return;
11789 
11790   // Third step: compute the access functions for each subscript.
11791   computeAccessFunctions(Expr, Subscripts, Sizes);
11792 
11793   if (Subscripts.empty())
11794     return;
11795 
11796   LLVM_DEBUG({
11797     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11798     dbgs() << "ArrayDecl[UnknownSize]";
11799     for (const SCEV *S : Sizes)
11800       dbgs() << "[" << *S << "]";
11801 
11802     dbgs() << "\nArrayRef";
11803     for (const SCEV *S : Subscripts)
11804       dbgs() << "[" << *S << "]";
11805     dbgs() << "\n";
11806   });
11807 }
11808 
11809 bool ScalarEvolution::getIndexExpressionsFromGEP(
11810     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
11811     SmallVectorImpl<int> &Sizes) {
11812   assert(Subscripts.empty() && Sizes.empty() &&
11813          "Expected output lists to be empty on entry to this function.");
11814   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
11815   Type *Ty = GEP->getPointerOperandType();
11816   bool DroppedFirstDim = false;
11817   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
11818     const SCEV *Expr = getSCEV(GEP->getOperand(i));
11819     if (i == 1) {
11820       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
11821         Ty = PtrTy->getElementType();
11822       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
11823         Ty = ArrayTy->getElementType();
11824       } else {
11825         Subscripts.clear();
11826         Sizes.clear();
11827         return false;
11828       }
11829       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
11830         if (Const->getValue()->isZero()) {
11831           DroppedFirstDim = true;
11832           continue;
11833         }
11834       Subscripts.push_back(Expr);
11835       continue;
11836     }
11837 
11838     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
11839     if (!ArrayTy) {
11840       Subscripts.clear();
11841       Sizes.clear();
11842       return false;
11843     }
11844 
11845     Subscripts.push_back(Expr);
11846     if (!(DroppedFirstDim && i == 2))
11847       Sizes.push_back(ArrayTy->getNumElements());
11848 
11849     Ty = ArrayTy->getElementType();
11850   }
11851   return !Subscripts.empty();
11852 }
11853 
11854 //===----------------------------------------------------------------------===//
11855 //                   SCEVCallbackVH Class Implementation
11856 //===----------------------------------------------------------------------===//
11857 
11858 void ScalarEvolution::SCEVCallbackVH::deleted() {
11859   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11860   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11861     SE->ConstantEvolutionLoopExitValue.erase(PN);
11862   SE->eraseValueFromMap(getValPtr());
11863   // this now dangles!
11864 }
11865 
11866 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11867   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11868 
11869   // Forget all the expressions associated with users of the old value,
11870   // so that future queries will recompute the expressions using the new
11871   // value.
11872   Value *Old = getValPtr();
11873   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11874   SmallPtrSet<User *, 8> Visited;
11875   while (!Worklist.empty()) {
11876     User *U = Worklist.pop_back_val();
11877     // Deleting the Old value will cause this to dangle. Postpone
11878     // that until everything else is done.
11879     if (U == Old)
11880       continue;
11881     if (!Visited.insert(U).second)
11882       continue;
11883     if (PHINode *PN = dyn_cast<PHINode>(U))
11884       SE->ConstantEvolutionLoopExitValue.erase(PN);
11885     SE->eraseValueFromMap(U);
11886     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11887   }
11888   // Delete the Old value.
11889   if (PHINode *PN = dyn_cast<PHINode>(Old))
11890     SE->ConstantEvolutionLoopExitValue.erase(PN);
11891   SE->eraseValueFromMap(Old);
11892   // this now dangles!
11893 }
11894 
11895 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11896   : CallbackVH(V), SE(se) {}
11897 
11898 //===----------------------------------------------------------------------===//
11899 //                   ScalarEvolution Class Implementation
11900 //===----------------------------------------------------------------------===//
11901 
11902 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11903                                  AssumptionCache &AC, DominatorTree &DT,
11904                                  LoopInfo &LI)
11905     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11906       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11907       LoopDispositions(64), BlockDispositions(64) {
11908   // To use guards for proving predicates, we need to scan every instruction in
11909   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11910   // time if the IR does not actually contain any calls to
11911   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11912   //
11913   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11914   // to _add_ guards to the module when there weren't any before, and wants
11915   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11916   // efficient in lieu of being smart in that rather obscure case.
11917 
11918   auto *GuardDecl = F.getParent()->getFunction(
11919       Intrinsic::getName(Intrinsic::experimental_guard));
11920   HasGuards = GuardDecl && !GuardDecl->use_empty();
11921 }
11922 
11923 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11924     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11925       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11926       ValueExprMap(std::move(Arg.ValueExprMap)),
11927       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11928       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11929       PendingMerges(std::move(Arg.PendingMerges)),
11930       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11931       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11932       PredicatedBackedgeTakenCounts(
11933           std::move(Arg.PredicatedBackedgeTakenCounts)),
11934       ConstantEvolutionLoopExitValue(
11935           std::move(Arg.ConstantEvolutionLoopExitValue)),
11936       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11937       LoopDispositions(std::move(Arg.LoopDispositions)),
11938       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11939       BlockDispositions(std::move(Arg.BlockDispositions)),
11940       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11941       SignedRanges(std::move(Arg.SignedRanges)),
11942       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11943       UniquePreds(std::move(Arg.UniquePreds)),
11944       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11945       LoopUsers(std::move(Arg.LoopUsers)),
11946       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11947       FirstUnknown(Arg.FirstUnknown) {
11948   Arg.FirstUnknown = nullptr;
11949 }
11950 
11951 ScalarEvolution::~ScalarEvolution() {
11952   // Iterate through all the SCEVUnknown instances and call their
11953   // destructors, so that they release their references to their values.
11954   for (SCEVUnknown *U = FirstUnknown; U;) {
11955     SCEVUnknown *Tmp = U;
11956     U = U->Next;
11957     Tmp->~SCEVUnknown();
11958   }
11959   FirstUnknown = nullptr;
11960 
11961   ExprValueMap.clear();
11962   ValueExprMap.clear();
11963   HasRecMap.clear();
11964 
11965   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11966   // that a loop had multiple computable exits.
11967   for (auto &BTCI : BackedgeTakenCounts)
11968     BTCI.second.clear();
11969   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11970     BTCI.second.clear();
11971 
11972   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11973   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11974   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11975   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11976   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11977 }
11978 
11979 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11980   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11981 }
11982 
11983 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11984                           const Loop *L) {
11985   // Print all inner loops first
11986   for (Loop *I : *L)
11987     PrintLoopInfo(OS, SE, I);
11988 
11989   OS << "Loop ";
11990   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11991   OS << ": ";
11992 
11993   SmallVector<BasicBlock *, 8> ExitingBlocks;
11994   L->getExitingBlocks(ExitingBlocks);
11995   if (ExitingBlocks.size() != 1)
11996     OS << "<multiple exits> ";
11997 
11998   if (SE->hasLoopInvariantBackedgeTakenCount(L))
11999     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12000   else
12001     OS << "Unpredictable backedge-taken count.\n";
12002 
12003   if (ExitingBlocks.size() > 1)
12004     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12005       OS << "  exit count for " << ExitingBlock->getName() << ": "
12006          << *SE->getExitCount(L, ExitingBlock) << "\n";
12007     }
12008 
12009   OS << "Loop ";
12010   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12011   OS << ": ";
12012 
12013   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12014     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12015     if (SE->isBackedgeTakenCountMaxOrZero(L))
12016       OS << ", actual taken count either this or zero.";
12017   } else {
12018     OS << "Unpredictable max backedge-taken count. ";
12019   }
12020 
12021   OS << "\n"
12022         "Loop ";
12023   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12024   OS << ": ";
12025 
12026   SCEVUnionPredicate Pred;
12027   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12028   if (!isa<SCEVCouldNotCompute>(PBT)) {
12029     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12030     OS << " Predicates:\n";
12031     Pred.print(OS, 4);
12032   } else {
12033     OS << "Unpredictable predicated backedge-taken count. ";
12034   }
12035   OS << "\n";
12036 
12037   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12038     OS << "Loop ";
12039     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12040     OS << ": ";
12041     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12042   }
12043 }
12044 
12045 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12046   switch (LD) {
12047   case ScalarEvolution::LoopVariant:
12048     return "Variant";
12049   case ScalarEvolution::LoopInvariant:
12050     return "Invariant";
12051   case ScalarEvolution::LoopComputable:
12052     return "Computable";
12053   }
12054   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12055 }
12056 
12057 void ScalarEvolution::print(raw_ostream &OS) const {
12058   // ScalarEvolution's implementation of the print method is to print
12059   // out SCEV values of all instructions that are interesting. Doing
12060   // this potentially causes it to create new SCEV objects though,
12061   // which technically conflicts with the const qualifier. This isn't
12062   // observable from outside the class though, so casting away the
12063   // const isn't dangerous.
12064   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12065 
12066   if (ClassifyExpressions) {
12067     OS << "Classifying expressions for: ";
12068     F.printAsOperand(OS, /*PrintType=*/false);
12069     OS << "\n";
12070     for (Instruction &I : instructions(F))
12071       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12072         OS << I << '\n';
12073         OS << "  -->  ";
12074         const SCEV *SV = SE.getSCEV(&I);
12075         SV->print(OS);
12076         if (!isa<SCEVCouldNotCompute>(SV)) {
12077           OS << " U: ";
12078           SE.getUnsignedRange(SV).print(OS);
12079           OS << " S: ";
12080           SE.getSignedRange(SV).print(OS);
12081         }
12082 
12083         const Loop *L = LI.getLoopFor(I.getParent());
12084 
12085         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12086         if (AtUse != SV) {
12087           OS << "  -->  ";
12088           AtUse->print(OS);
12089           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12090             OS << " U: ";
12091             SE.getUnsignedRange(AtUse).print(OS);
12092             OS << " S: ";
12093             SE.getSignedRange(AtUse).print(OS);
12094           }
12095         }
12096 
12097         if (L) {
12098           OS << "\t\t" "Exits: ";
12099           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12100           if (!SE.isLoopInvariant(ExitValue, L)) {
12101             OS << "<<Unknown>>";
12102           } else {
12103             OS << *ExitValue;
12104           }
12105 
12106           bool First = true;
12107           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12108             if (First) {
12109               OS << "\t\t" "LoopDispositions: { ";
12110               First = false;
12111             } else {
12112               OS << ", ";
12113             }
12114 
12115             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12116             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12117           }
12118 
12119           for (auto *InnerL : depth_first(L)) {
12120             if (InnerL == L)
12121               continue;
12122             if (First) {
12123               OS << "\t\t" "LoopDispositions: { ";
12124               First = false;
12125             } else {
12126               OS << ", ";
12127             }
12128 
12129             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12130             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12131           }
12132 
12133           OS << " }";
12134         }
12135 
12136         OS << "\n";
12137       }
12138   }
12139 
12140   OS << "Determining loop execution counts for: ";
12141   F.printAsOperand(OS, /*PrintType=*/false);
12142   OS << "\n";
12143   for (Loop *I : LI)
12144     PrintLoopInfo(OS, &SE, I);
12145 }
12146 
12147 ScalarEvolution::LoopDisposition
12148 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12149   auto &Values = LoopDispositions[S];
12150   for (auto &V : Values) {
12151     if (V.getPointer() == L)
12152       return V.getInt();
12153   }
12154   Values.emplace_back(L, LoopVariant);
12155   LoopDisposition D = computeLoopDisposition(S, L);
12156   auto &Values2 = LoopDispositions[S];
12157   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12158     if (V.getPointer() == L) {
12159       V.setInt(D);
12160       break;
12161     }
12162   }
12163   return D;
12164 }
12165 
12166 ScalarEvolution::LoopDisposition
12167 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12168   switch (S->getSCEVType()) {
12169   case scConstant:
12170     return LoopInvariant;
12171   case scPtrToInt:
12172   case scTruncate:
12173   case scZeroExtend:
12174   case scSignExtend:
12175     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12176   case scAddRecExpr: {
12177     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12178 
12179     // If L is the addrec's loop, it's computable.
12180     if (AR->getLoop() == L)
12181       return LoopComputable;
12182 
12183     // Add recurrences are never invariant in the function-body (null loop).
12184     if (!L)
12185       return LoopVariant;
12186 
12187     // Everything that is not defined at loop entry is variant.
12188     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12189       return LoopVariant;
12190     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12191            " dominate the contained loop's header?");
12192 
12193     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12194     if (AR->getLoop()->contains(L))
12195       return LoopInvariant;
12196 
12197     // This recurrence is variant w.r.t. L if any of its operands
12198     // are variant.
12199     for (auto *Op : AR->operands())
12200       if (!isLoopInvariant(Op, L))
12201         return LoopVariant;
12202 
12203     // Otherwise it's loop-invariant.
12204     return LoopInvariant;
12205   }
12206   case scAddExpr:
12207   case scMulExpr:
12208   case scUMaxExpr:
12209   case scSMaxExpr:
12210   case scUMinExpr:
12211   case scSMinExpr: {
12212     bool HasVarying = false;
12213     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12214       LoopDisposition D = getLoopDisposition(Op, L);
12215       if (D == LoopVariant)
12216         return LoopVariant;
12217       if (D == LoopComputable)
12218         HasVarying = true;
12219     }
12220     return HasVarying ? LoopComputable : LoopInvariant;
12221   }
12222   case scUDivExpr: {
12223     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12224     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12225     if (LD == LoopVariant)
12226       return LoopVariant;
12227     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12228     if (RD == LoopVariant)
12229       return LoopVariant;
12230     return (LD == LoopInvariant && RD == LoopInvariant) ?
12231            LoopInvariant : LoopComputable;
12232   }
12233   case scUnknown:
12234     // All non-instruction values are loop invariant.  All instructions are loop
12235     // invariant if they are not contained in the specified loop.
12236     // Instructions are never considered invariant in the function body
12237     // (null loop) because they are defined within the "loop".
12238     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12239       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12240     return LoopInvariant;
12241   case scCouldNotCompute:
12242     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12243   }
12244   llvm_unreachable("Unknown SCEV kind!");
12245 }
12246 
12247 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12248   return getLoopDisposition(S, L) == LoopInvariant;
12249 }
12250 
12251 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12252   return getLoopDisposition(S, L) == LoopComputable;
12253 }
12254 
12255 ScalarEvolution::BlockDisposition
12256 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12257   auto &Values = BlockDispositions[S];
12258   for (auto &V : Values) {
12259     if (V.getPointer() == BB)
12260       return V.getInt();
12261   }
12262   Values.emplace_back(BB, DoesNotDominateBlock);
12263   BlockDisposition D = computeBlockDisposition(S, BB);
12264   auto &Values2 = BlockDispositions[S];
12265   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12266     if (V.getPointer() == BB) {
12267       V.setInt(D);
12268       break;
12269     }
12270   }
12271   return D;
12272 }
12273 
12274 ScalarEvolution::BlockDisposition
12275 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12276   switch (S->getSCEVType()) {
12277   case scConstant:
12278     return ProperlyDominatesBlock;
12279   case scPtrToInt:
12280   case scTruncate:
12281   case scZeroExtend:
12282   case scSignExtend:
12283     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12284   case scAddRecExpr: {
12285     // This uses a "dominates" query instead of "properly dominates" query
12286     // to test for proper dominance too, because the instruction which
12287     // produces the addrec's value is a PHI, and a PHI effectively properly
12288     // dominates its entire containing block.
12289     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12290     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12291       return DoesNotDominateBlock;
12292 
12293     // Fall through into SCEVNAryExpr handling.
12294     LLVM_FALLTHROUGH;
12295   }
12296   case scAddExpr:
12297   case scMulExpr:
12298   case scUMaxExpr:
12299   case scSMaxExpr:
12300   case scUMinExpr:
12301   case scSMinExpr: {
12302     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12303     bool Proper = true;
12304     for (const SCEV *NAryOp : NAry->operands()) {
12305       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12306       if (D == DoesNotDominateBlock)
12307         return DoesNotDominateBlock;
12308       if (D == DominatesBlock)
12309         Proper = false;
12310     }
12311     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12312   }
12313   case scUDivExpr: {
12314     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12315     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12316     BlockDisposition LD = getBlockDisposition(LHS, BB);
12317     if (LD == DoesNotDominateBlock)
12318       return DoesNotDominateBlock;
12319     BlockDisposition RD = getBlockDisposition(RHS, BB);
12320     if (RD == DoesNotDominateBlock)
12321       return DoesNotDominateBlock;
12322     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12323       ProperlyDominatesBlock : DominatesBlock;
12324   }
12325   case scUnknown:
12326     if (Instruction *I =
12327           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12328       if (I->getParent() == BB)
12329         return DominatesBlock;
12330       if (DT.properlyDominates(I->getParent(), BB))
12331         return ProperlyDominatesBlock;
12332       return DoesNotDominateBlock;
12333     }
12334     return ProperlyDominatesBlock;
12335   case scCouldNotCompute:
12336     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12337   }
12338   llvm_unreachable("Unknown SCEV kind!");
12339 }
12340 
12341 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12342   return getBlockDisposition(S, BB) >= DominatesBlock;
12343 }
12344 
12345 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12346   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12347 }
12348 
12349 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12350   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12351 }
12352 
12353 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12354   auto IsS = [&](const SCEV *X) { return S == X; };
12355   auto ContainsS = [&](const SCEV *X) {
12356     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12357   };
12358   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12359 }
12360 
12361 void
12362 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12363   ValuesAtScopes.erase(S);
12364   LoopDispositions.erase(S);
12365   BlockDispositions.erase(S);
12366   UnsignedRanges.erase(S);
12367   SignedRanges.erase(S);
12368   ExprValueMap.erase(S);
12369   HasRecMap.erase(S);
12370   MinTrailingZerosCache.erase(S);
12371 
12372   for (auto I = PredicatedSCEVRewrites.begin();
12373        I != PredicatedSCEVRewrites.end();) {
12374     std::pair<const SCEV *, const Loop *> Entry = I->first;
12375     if (Entry.first == S)
12376       PredicatedSCEVRewrites.erase(I++);
12377     else
12378       ++I;
12379   }
12380 
12381   auto RemoveSCEVFromBackedgeMap =
12382       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12383         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12384           BackedgeTakenInfo &BEInfo = I->second;
12385           if (BEInfo.hasOperand(S, this)) {
12386             BEInfo.clear();
12387             Map.erase(I++);
12388           } else
12389             ++I;
12390         }
12391       };
12392 
12393   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12394   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12395 }
12396 
12397 void
12398 ScalarEvolution::getUsedLoops(const SCEV *S,
12399                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12400   struct FindUsedLoops {
12401     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12402         : LoopsUsed(LoopsUsed) {}
12403     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12404     bool follow(const SCEV *S) {
12405       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12406         LoopsUsed.insert(AR->getLoop());
12407       return true;
12408     }
12409 
12410     bool isDone() const { return false; }
12411   };
12412 
12413   FindUsedLoops F(LoopsUsed);
12414   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12415 }
12416 
12417 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12418   SmallPtrSet<const Loop *, 8> LoopsUsed;
12419   getUsedLoops(S, LoopsUsed);
12420   for (auto *L : LoopsUsed)
12421     LoopUsers[L].push_back(S);
12422 }
12423 
12424 void ScalarEvolution::verify() const {
12425   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12426   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12427 
12428   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12429 
12430   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12431   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12432     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12433 
12434     const SCEV *visitConstant(const SCEVConstant *Constant) {
12435       return SE.getConstant(Constant->getAPInt());
12436     }
12437 
12438     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12439       return SE.getUnknown(Expr->getValue());
12440     }
12441 
12442     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12443       return SE.getCouldNotCompute();
12444     }
12445   };
12446 
12447   SCEVMapper SCM(SE2);
12448 
12449   while (!LoopStack.empty()) {
12450     auto *L = LoopStack.pop_back_val();
12451     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
12452 
12453     auto *CurBECount = SCM.visit(
12454         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12455     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12456 
12457     if (CurBECount == SE2.getCouldNotCompute() ||
12458         NewBECount == SE2.getCouldNotCompute()) {
12459       // NB! This situation is legal, but is very suspicious -- whatever pass
12460       // change the loop to make a trip count go from could not compute to
12461       // computable or vice-versa *should have* invalidated SCEV.  However, we
12462       // choose not to assert here (for now) since we don't want false
12463       // positives.
12464       continue;
12465     }
12466 
12467     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12468       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12469       // not propagate undef aggressively).  This means we can (and do) fail
12470       // verification in cases where a transform makes the trip count of a loop
12471       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12472       // both cases the loop iterates "undef" times, but SCEV thinks we
12473       // increased the trip count of the loop by 1 incorrectly.
12474       continue;
12475     }
12476 
12477     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12478         SE.getTypeSizeInBits(NewBECount->getType()))
12479       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12480     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12481              SE.getTypeSizeInBits(NewBECount->getType()))
12482       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12483 
12484     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12485 
12486     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12487     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12488       dbgs() << "Trip Count for " << *L << " Changed!\n";
12489       dbgs() << "Old: " << *CurBECount << "\n";
12490       dbgs() << "New: " << *NewBECount << "\n";
12491       dbgs() << "Delta: " << *Delta << "\n";
12492       std::abort();
12493     }
12494   }
12495 
12496   // Collect all valid loops currently in LoopInfo.
12497   SmallPtrSet<Loop *, 32> ValidLoops;
12498   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12499   while (!Worklist.empty()) {
12500     Loop *L = Worklist.pop_back_val();
12501     if (ValidLoops.contains(L))
12502       continue;
12503     ValidLoops.insert(L);
12504     Worklist.append(L->begin(), L->end());
12505   }
12506   // Check for SCEV expressions referencing invalid/deleted loops.
12507   for (auto &KV : ValueExprMap) {
12508     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12509     if (!AR)
12510       continue;
12511     assert(ValidLoops.contains(AR->getLoop()) &&
12512            "AddRec references invalid loop");
12513   }
12514 }
12515 
12516 bool ScalarEvolution::invalidate(
12517     Function &F, const PreservedAnalyses &PA,
12518     FunctionAnalysisManager::Invalidator &Inv) {
12519   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12520   // of its dependencies is invalidated.
12521   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12522   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12523          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12524          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12525          Inv.invalidate<LoopAnalysis>(F, PA);
12526 }
12527 
12528 AnalysisKey ScalarEvolutionAnalysis::Key;
12529 
12530 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12531                                              FunctionAnalysisManager &AM) {
12532   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12533                          AM.getResult<AssumptionAnalysis>(F),
12534                          AM.getResult<DominatorTreeAnalysis>(F),
12535                          AM.getResult<LoopAnalysis>(F));
12536 }
12537 
12538 PreservedAnalyses
12539 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12540   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12541   return PreservedAnalyses::all();
12542 }
12543 
12544 PreservedAnalyses
12545 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12546   // For compatibility with opt's -analyze feature under legacy pass manager
12547   // which was not ported to NPM. This keeps tests using
12548   // update_analyze_test_checks.py working.
12549   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12550      << F.getName() << "':\n";
12551   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12552   return PreservedAnalyses::all();
12553 }
12554 
12555 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12556                       "Scalar Evolution Analysis", false, true)
12557 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12558 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12559 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12560 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12561 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12562                     "Scalar Evolution Analysis", false, true)
12563 
12564 char ScalarEvolutionWrapperPass::ID = 0;
12565 
12566 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12567   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12568 }
12569 
12570 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12571   SE.reset(new ScalarEvolution(
12572       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12573       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12574       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12575       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12576   return false;
12577 }
12578 
12579 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12580 
12581 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12582   SE->print(OS);
12583 }
12584 
12585 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12586   if (!VerifySCEV)
12587     return;
12588 
12589   SE->verify();
12590 }
12591 
12592 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12593   AU.setPreservesAll();
12594   AU.addRequiredTransitive<AssumptionCacheTracker>();
12595   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12596   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12597   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12598 }
12599 
12600 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12601                                                         const SCEV *RHS) {
12602   FoldingSetNodeID ID;
12603   assert(LHS->getType() == RHS->getType() &&
12604          "Type mismatch between LHS and RHS");
12605   // Unique this node based on the arguments
12606   ID.AddInteger(SCEVPredicate::P_Equal);
12607   ID.AddPointer(LHS);
12608   ID.AddPointer(RHS);
12609   void *IP = nullptr;
12610   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12611     return S;
12612   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12613       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12614   UniquePreds.InsertNode(Eq, IP);
12615   return Eq;
12616 }
12617 
12618 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12619     const SCEVAddRecExpr *AR,
12620     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12621   FoldingSetNodeID ID;
12622   // Unique this node based on the arguments
12623   ID.AddInteger(SCEVPredicate::P_Wrap);
12624   ID.AddPointer(AR);
12625   ID.AddInteger(AddedFlags);
12626   void *IP = nullptr;
12627   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12628     return S;
12629   auto *OF = new (SCEVAllocator)
12630       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12631   UniquePreds.InsertNode(OF, IP);
12632   return OF;
12633 }
12634 
12635 namespace {
12636 
12637 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12638 public:
12639 
12640   /// Rewrites \p S in the context of a loop L and the SCEV predication
12641   /// infrastructure.
12642   ///
12643   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12644   /// equivalences present in \p Pred.
12645   ///
12646   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12647   /// \p NewPreds such that the result will be an AddRecExpr.
12648   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12649                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12650                              SCEVUnionPredicate *Pred) {
12651     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12652     return Rewriter.visit(S);
12653   }
12654 
12655   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12656     if (Pred) {
12657       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12658       for (auto *Pred : ExprPreds)
12659         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12660           if (IPred->getLHS() == Expr)
12661             return IPred->getRHS();
12662     }
12663     return convertToAddRecWithPreds(Expr);
12664   }
12665 
12666   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12667     const SCEV *Operand = visit(Expr->getOperand());
12668     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12669     if (AR && AR->getLoop() == L && AR->isAffine()) {
12670       // This couldn't be folded because the operand didn't have the nuw
12671       // flag. Add the nusw flag as an assumption that we could make.
12672       const SCEV *Step = AR->getStepRecurrence(SE);
12673       Type *Ty = Expr->getType();
12674       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12675         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12676                                 SE.getSignExtendExpr(Step, Ty), L,
12677                                 AR->getNoWrapFlags());
12678     }
12679     return SE.getZeroExtendExpr(Operand, Expr->getType());
12680   }
12681 
12682   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12683     const SCEV *Operand = visit(Expr->getOperand());
12684     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12685     if (AR && AR->getLoop() == L && AR->isAffine()) {
12686       // This couldn't be folded because the operand didn't have the nsw
12687       // flag. Add the nssw flag as an assumption that we could make.
12688       const SCEV *Step = AR->getStepRecurrence(SE);
12689       Type *Ty = Expr->getType();
12690       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12691         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12692                                 SE.getSignExtendExpr(Step, Ty), L,
12693                                 AR->getNoWrapFlags());
12694     }
12695     return SE.getSignExtendExpr(Operand, Expr->getType());
12696   }
12697 
12698 private:
12699   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12700                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12701                         SCEVUnionPredicate *Pred)
12702       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12703 
12704   bool addOverflowAssumption(const SCEVPredicate *P) {
12705     if (!NewPreds) {
12706       // Check if we've already made this assumption.
12707       return Pred && Pred->implies(P);
12708     }
12709     NewPreds->insert(P);
12710     return true;
12711   }
12712 
12713   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12714                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12715     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12716     return addOverflowAssumption(A);
12717   }
12718 
12719   // If \p Expr represents a PHINode, we try to see if it can be represented
12720   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12721   // to add this predicate as a runtime overflow check, we return the AddRec.
12722   // If \p Expr does not meet these conditions (is not a PHI node, or we
12723   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12724   // return \p Expr.
12725   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12726     if (!isa<PHINode>(Expr->getValue()))
12727       return Expr;
12728     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12729     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12730     if (!PredicatedRewrite)
12731       return Expr;
12732     for (auto *P : PredicatedRewrite->second){
12733       // Wrap predicates from outer loops are not supported.
12734       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12735         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12736         if (L != AR->getLoop())
12737           return Expr;
12738       }
12739       if (!addOverflowAssumption(P))
12740         return Expr;
12741     }
12742     return PredicatedRewrite->first;
12743   }
12744 
12745   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12746   SCEVUnionPredicate *Pred;
12747   const Loop *L;
12748 };
12749 
12750 } // end anonymous namespace
12751 
12752 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12753                                                    SCEVUnionPredicate &Preds) {
12754   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12755 }
12756 
12757 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12758     const SCEV *S, const Loop *L,
12759     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12760   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12761   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12762   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12763 
12764   if (!AddRec)
12765     return nullptr;
12766 
12767   // Since the transformation was successful, we can now transfer the SCEV
12768   // predicates.
12769   for (auto *P : TransformPreds)
12770     Preds.insert(P);
12771 
12772   return AddRec;
12773 }
12774 
12775 /// SCEV predicates
12776 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12777                              SCEVPredicateKind Kind)
12778     : FastID(ID), Kind(Kind) {}
12779 
12780 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12781                                        const SCEV *LHS, const SCEV *RHS)
12782     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12783   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12784   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12785 }
12786 
12787 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12788   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12789 
12790   if (!Op)
12791     return false;
12792 
12793   return Op->LHS == LHS && Op->RHS == RHS;
12794 }
12795 
12796 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12797 
12798 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12799 
12800 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12801   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12802 }
12803 
12804 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12805                                      const SCEVAddRecExpr *AR,
12806                                      IncrementWrapFlags Flags)
12807     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12808 
12809 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12810 
12811 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12812   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12813 
12814   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12815 }
12816 
12817 bool SCEVWrapPredicate::isAlwaysTrue() const {
12818   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12819   IncrementWrapFlags IFlags = Flags;
12820 
12821   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12822     IFlags = clearFlags(IFlags, IncrementNSSW);
12823 
12824   return IFlags == IncrementAnyWrap;
12825 }
12826 
12827 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12828   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12829   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12830     OS << "<nusw>";
12831   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12832     OS << "<nssw>";
12833   OS << "\n";
12834 }
12835 
12836 SCEVWrapPredicate::IncrementWrapFlags
12837 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12838                                    ScalarEvolution &SE) {
12839   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12840   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12841 
12842   // We can safely transfer the NSW flag as NSSW.
12843   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12844     ImpliedFlags = IncrementNSSW;
12845 
12846   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12847     // If the increment is positive, the SCEV NUW flag will also imply the
12848     // WrapPredicate NUSW flag.
12849     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12850       if (Step->getValue()->getValue().isNonNegative())
12851         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12852   }
12853 
12854   return ImpliedFlags;
12855 }
12856 
12857 /// Union predicates don't get cached so create a dummy set ID for it.
12858 SCEVUnionPredicate::SCEVUnionPredicate()
12859     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12860 
12861 bool SCEVUnionPredicate::isAlwaysTrue() const {
12862   return all_of(Preds,
12863                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12864 }
12865 
12866 ArrayRef<const SCEVPredicate *>
12867 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12868   auto I = SCEVToPreds.find(Expr);
12869   if (I == SCEVToPreds.end())
12870     return ArrayRef<const SCEVPredicate *>();
12871   return I->second;
12872 }
12873 
12874 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12875   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12876     return all_of(Set->Preds,
12877                   [this](const SCEVPredicate *I) { return this->implies(I); });
12878 
12879   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12880   if (ScevPredsIt == SCEVToPreds.end())
12881     return false;
12882   auto &SCEVPreds = ScevPredsIt->second;
12883 
12884   return any_of(SCEVPreds,
12885                 [N](const SCEVPredicate *I) { return I->implies(N); });
12886 }
12887 
12888 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12889 
12890 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12891   for (auto Pred : Preds)
12892     Pred->print(OS, Depth);
12893 }
12894 
12895 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12896   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12897     for (auto Pred : Set->Preds)
12898       add(Pred);
12899     return;
12900   }
12901 
12902   if (implies(N))
12903     return;
12904 
12905   const SCEV *Key = N->getExpr();
12906   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12907                 " associated expression!");
12908 
12909   SCEVToPreds[Key].push_back(N);
12910   Preds.push_back(N);
12911 }
12912 
12913 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12914                                                      Loop &L)
12915     : SE(SE), L(L) {}
12916 
12917 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12918   const SCEV *Expr = SE.getSCEV(V);
12919   RewriteEntry &Entry = RewriteMap[Expr];
12920 
12921   // If we already have an entry and the version matches, return it.
12922   if (Entry.second && Generation == Entry.first)
12923     return Entry.second;
12924 
12925   // We found an entry but it's stale. Rewrite the stale entry
12926   // according to the current predicate.
12927   if (Entry.second)
12928     Expr = Entry.second;
12929 
12930   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12931   Entry = {Generation, NewSCEV};
12932 
12933   return NewSCEV;
12934 }
12935 
12936 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12937   if (!BackedgeCount) {
12938     SCEVUnionPredicate BackedgePred;
12939     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12940     addPredicate(BackedgePred);
12941   }
12942   return BackedgeCount;
12943 }
12944 
12945 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12946   if (Preds.implies(&Pred))
12947     return;
12948   Preds.add(&Pred);
12949   updateGeneration();
12950 }
12951 
12952 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12953   return Preds;
12954 }
12955 
12956 void PredicatedScalarEvolution::updateGeneration() {
12957   // If the generation number wrapped recompute everything.
12958   if (++Generation == 0) {
12959     for (auto &II : RewriteMap) {
12960       const SCEV *Rewritten = II.second.second;
12961       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12962     }
12963   }
12964 }
12965 
12966 void PredicatedScalarEvolution::setNoOverflow(
12967     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12968   const SCEV *Expr = getSCEV(V);
12969   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12970 
12971   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12972 
12973   // Clear the statically implied flags.
12974   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12975   addPredicate(*SE.getWrapPredicate(AR, Flags));
12976 
12977   auto II = FlagsMap.insert({V, Flags});
12978   if (!II.second)
12979     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12980 }
12981 
12982 bool PredicatedScalarEvolution::hasNoOverflow(
12983     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12984   const SCEV *Expr = getSCEV(V);
12985   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12986 
12987   Flags = SCEVWrapPredicate::clearFlags(
12988       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12989 
12990   auto II = FlagsMap.find(V);
12991 
12992   if (II != FlagsMap.end())
12993     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12994 
12995   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12996 }
12997 
12998 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12999   const SCEV *Expr = this->getSCEV(V);
13000   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13001   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13002 
13003   if (!New)
13004     return nullptr;
13005 
13006   for (auto *P : NewPreds)
13007     Preds.add(P);
13008 
13009   updateGeneration();
13010   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13011   return New;
13012 }
13013 
13014 PredicatedScalarEvolution::PredicatedScalarEvolution(
13015     const PredicatedScalarEvolution &Init)
13016     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13017       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13018   for (auto I : Init.FlagsMap)
13019     FlagsMap.insert(I);
13020 }
13021 
13022 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13023   // For each block.
13024   for (auto *BB : L.getBlocks())
13025     for (auto &I : *BB) {
13026       if (!SE.isSCEVable(I.getType()))
13027         continue;
13028 
13029       auto *Expr = SE.getSCEV(&I);
13030       auto II = RewriteMap.find(Expr);
13031 
13032       if (II == RewriteMap.end())
13033         continue;
13034 
13035       // Don't print things that are not interesting.
13036       if (II->second.second == Expr)
13037         continue;
13038 
13039       OS.indent(Depth) << "[PSE]" << I << ":\n";
13040       OS.indent(Depth + 2) << *Expr << "\n";
13041       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13042     }
13043 }
13044 
13045 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13046 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13047 // for URem with constant power-of-2 second operands.
13048 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13049 // 4, A / B becomes X / 8).
13050 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13051                                 const SCEV *&RHS) {
13052   // Try to match 'zext (trunc A to iB) to iY', which is used
13053   // for URem with constant power-of-2 second operands. Make sure the size of
13054   // the operand A matches the size of the whole expressions.
13055   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13056     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13057       LHS = Trunc->getOperand();
13058       if (LHS->getType() != Expr->getType())
13059         LHS = getZeroExtendExpr(LHS, Expr->getType());
13060       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13061                         << getTypeSizeInBits(Trunc->getType()));
13062       return true;
13063     }
13064   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13065   if (Add == nullptr || Add->getNumOperands() != 2)
13066     return false;
13067 
13068   const SCEV *A = Add->getOperand(1);
13069   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13070 
13071   if (Mul == nullptr)
13072     return false;
13073 
13074   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13075     // (SomeExpr + (-(SomeExpr / B) * B)).
13076     if (Expr == getURemExpr(A, B)) {
13077       LHS = A;
13078       RHS = B;
13079       return true;
13080     }
13081     return false;
13082   };
13083 
13084   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13085   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13086     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13087            MatchURemWithDivisor(Mul->getOperand(2));
13088 
13089   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13090   if (Mul->getNumOperands() == 2)
13091     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13092            MatchURemWithDivisor(Mul->getOperand(0)) ||
13093            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13094            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13095   return false;
13096 }
13097 
13098 const SCEV *
13099 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13100   SmallVector<BasicBlock*, 16> ExitingBlocks;
13101   L->getExitingBlocks(ExitingBlocks);
13102 
13103   // Form an expression for the maximum exit count possible for this loop. We
13104   // merge the max and exact information to approximate a version of
13105   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13106   SmallVector<const SCEV*, 4> ExitCounts;
13107   for (BasicBlock *ExitingBB : ExitingBlocks) {
13108     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13109     if (isa<SCEVCouldNotCompute>(ExitCount))
13110       ExitCount = getExitCount(L, ExitingBB,
13111                                   ScalarEvolution::ConstantMaximum);
13112     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13113       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13114              "We should only have known counts for exiting blocks that "
13115              "dominate latch!");
13116       ExitCounts.push_back(ExitCount);
13117     }
13118   }
13119   if (ExitCounts.empty())
13120     return getCouldNotCompute();
13121   return getUMinFromMismatchedTypes(ExitCounts);
13122 }
13123 
13124 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13125 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13126 /// we cannot guarantee that the replacement is loop invariant in the loop of
13127 /// the AddRec.
13128 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13129   ValueToSCEVMapTy &Map;
13130 
13131 public:
13132   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13133       : SCEVRewriteVisitor(SE), Map(M) {}
13134 
13135   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13136 
13137   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13138     auto I = Map.find(Expr->getValue());
13139     if (I == Map.end())
13140       return Expr;
13141     return I->second;
13142   }
13143 };
13144 
13145 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13146   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13147                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13148     if (!isa<SCEVUnknown>(LHS)) {
13149       std::swap(LHS, RHS);
13150       Predicate = CmpInst::getSwappedPredicate(Predicate);
13151     }
13152 
13153     // For now, limit to conditions that provide information about unknown
13154     // expressions.
13155     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13156     if (!LHSUnknown)
13157       return;
13158 
13159     // TODO: use information from more predicates.
13160     switch (Predicate) {
13161     case CmpInst::ICMP_ULT: {
13162       if (!containsAddRecurrence(RHS)) {
13163         const SCEV *Base = LHS;
13164         auto I = RewriteMap.find(LHSUnknown->getValue());
13165         if (I != RewriteMap.end())
13166           Base = I->second;
13167 
13168         RewriteMap[LHSUnknown->getValue()] =
13169             getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13170       }
13171       break;
13172     }
13173     case CmpInst::ICMP_ULE: {
13174       if (!containsAddRecurrence(RHS)) {
13175         const SCEV *Base = LHS;
13176         auto I = RewriteMap.find(LHSUnknown->getValue());
13177         if (I != RewriteMap.end())
13178           Base = I->second;
13179         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13180       }
13181       break;
13182     }
13183     case CmpInst::ICMP_EQ:
13184       if (isa<SCEVConstant>(RHS))
13185         RewriteMap[LHSUnknown->getValue()] = RHS;
13186       break;
13187     case CmpInst::ICMP_NE:
13188       if (isa<SCEVConstant>(RHS) &&
13189           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13190         RewriteMap[LHSUnknown->getValue()] =
13191             getUMaxExpr(LHS, getOne(RHS->getType()));
13192       break;
13193     default:
13194       break;
13195     }
13196   };
13197   // Starting at the loop predecessor, climb up the predecessor chain, as long
13198   // as there are predecessors that can be found that have unique successors
13199   // leading to the original header.
13200   // TODO: share this logic with isLoopEntryGuardedByCond.
13201   ValueToSCEVMapTy RewriteMap;
13202   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13203            L->getLoopPredecessor(), L->getHeader());
13204        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13205 
13206     const BranchInst *LoopEntryPredicate =
13207         dyn_cast<BranchInst>(Pair.first->getTerminator());
13208     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13209       continue;
13210 
13211     // TODO: use information from more complex conditions, e.g. AND expressions.
13212     auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13213     if (!Cmp)
13214       continue;
13215 
13216     auto Predicate = Cmp->getPredicate();
13217     if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13218       Predicate = CmpInst::getInversePredicate(Predicate);
13219     CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13220                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13221   }
13222 
13223   // Also collect information from assumptions dominating the loop.
13224   for (auto &AssumeVH : AC.assumptions()) {
13225     if (!AssumeVH)
13226       continue;
13227     auto *AssumeI = cast<CallInst>(AssumeVH);
13228     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13229     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13230       continue;
13231     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13232                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13233   }
13234 
13235   if (RewriteMap.empty())
13236     return Expr;
13237   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13238   return Rewriter.visit(Expr);
13239 }
13240