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 using namespace PatternMatch;
139 
140 #define DEBUG_TYPE "scalar-evolution"
141 
142 STATISTIC(NumArrayLenItCounts,
143           "Number of trip counts computed with array length");
144 STATISTIC(NumTripCountsComputed,
145           "Number of loops with predictable loop counts");
146 STATISTIC(NumTripCountsNotComputed,
147           "Number of loops without predictable loop counts");
148 STATISTIC(NumBruteForceTripCountsComputed,
149           "Number of loops with trip counts computed by force");
150 
151 static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153                         cl::ZeroOrMore,
154                         cl::desc("Maximum number of iterations SCEV will "
155                                  "symbolically execute a constant "
156                                  "derived loop"),
157                         cl::init(100));
158 
159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
160 static cl::opt<bool> VerifySCEV(
161     "verify-scev", cl::Hidden,
162     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 static cl::opt<bool> VerifySCEVStrict(
164     "verify-scev-strict", cl::Hidden,
165     cl::desc("Enable stricter verification with -verify-scev is passed"));
166 static cl::opt<bool>
167     VerifySCEVMap("verify-scev-maps", cl::Hidden,
168                   cl::desc("Verify no dangling value in ScalarEvolution's "
169                            "ExprValueMap (slow)"));
170 
171 static cl::opt<bool> VerifyIR(
172     "scev-verify-ir", cl::Hidden,
173     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
174     cl::init(false));
175 
176 static cl::opt<unsigned> MulOpsInlineThreshold(
177     "scev-mulops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
179     cl::init(32));
180 
181 static cl::opt<unsigned> AddOpsInlineThreshold(
182     "scev-addops-inline-threshold", cl::Hidden,
183     cl::desc("Threshold for inlining addition operands into a SCEV"),
184     cl::init(500));
185 
186 static cl::opt<unsigned> MaxSCEVCompareDepth(
187     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
189     cl::init(32));
190 
191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
192     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
194     cl::init(2));
195 
196 static cl::opt<unsigned> MaxValueCompareDepth(
197     "scalar-evolution-max-value-compare-depth", cl::Hidden,
198     cl::desc("Maximum depth of recursive value complexity comparisons"),
199     cl::init(2));
200 
201 static cl::opt<unsigned>
202     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
203                   cl::desc("Maximum depth of recursive arithmetics"),
204                   cl::init(32));
205 
206 static cl::opt<unsigned> MaxConstantEvolvingDepth(
207     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
208     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
209 
210 static cl::opt<unsigned>
211     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
212                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
213                  cl::init(8));
214 
215 static cl::opt<unsigned>
216     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
217                   cl::desc("Max coefficients in AddRec during evolving"),
218                   cl::init(8));
219 
220 static cl::opt<unsigned>
221     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
222                   cl::desc("Size of the expression which is considered huge"),
223                   cl::init(4096));
224 
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227     cl::Hidden, cl::init(true),
228     cl::desc("When printing analysis, include information on every instruction"));
229 
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232     cl::init(false),
233     cl::desc("Use more powerful methods of sharpening expression ranges. May "
234              "be costly in terms of compile time"));
235 
236 //===----------------------------------------------------------------------===//
237 //                           SCEV class definitions
238 //===----------------------------------------------------------------------===//
239 
240 //===----------------------------------------------------------------------===//
241 // Implementation of the SCEV class.
242 //
243 
244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
245 LLVM_DUMP_METHOD void SCEV::dump() const {
246   print(dbgs());
247   dbgs() << '\n';
248 }
249 #endif
250 
251 void SCEV::print(raw_ostream &OS) const {
252   switch (getSCEVType()) {
253   case scConstant:
254     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
255     return;
256   case scPtrToInt: {
257     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
258     const SCEV *Op = PtrToInt->getOperand();
259     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
260        << *PtrToInt->getType() << ")";
261     return;
262   }
263   case scTruncate: {
264     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
265     const SCEV *Op = Trunc->getOperand();
266     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
267        << *Trunc->getType() << ")";
268     return;
269   }
270   case scZeroExtend: {
271     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
272     const SCEV *Op = ZExt->getOperand();
273     OS << "(zext " << *Op->getType() << " " << *Op << " to "
274        << *ZExt->getType() << ")";
275     return;
276   }
277   case scSignExtend: {
278     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
279     const SCEV *Op = SExt->getOperand();
280     OS << "(sext " << *Op->getType() << " " << *Op << " to "
281        << *SExt->getType() << ")";
282     return;
283   }
284   case scAddRecExpr: {
285     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
286     OS << "{" << *AR->getOperand(0);
287     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
288       OS << ",+," << *AR->getOperand(i);
289     OS << "}<";
290     if (AR->hasNoUnsignedWrap())
291       OS << "nuw><";
292     if (AR->hasNoSignedWrap())
293       OS << "nsw><";
294     if (AR->hasNoSelfWrap() &&
295         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
296       OS << "nw><";
297     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
298     OS << ">";
299     return;
300   }
301   case scAddExpr:
302   case scMulExpr:
303   case scUMaxExpr:
304   case scSMaxExpr:
305   case scUMinExpr:
306   case scSMinExpr: {
307     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
308     const char *OpStr = nullptr;
309     switch (NAry->getSCEVType()) {
310     case scAddExpr: OpStr = " + "; break;
311     case scMulExpr: OpStr = " * "; break;
312     case scUMaxExpr: OpStr = " umax "; break;
313     case scSMaxExpr: OpStr = " smax "; break;
314     case scUMinExpr:
315       OpStr = " umin ";
316       break;
317     case scSMinExpr:
318       OpStr = " smin ";
319       break;
320     default:
321       llvm_unreachable("There are no other nary expression types.");
322     }
323     OS << "(";
324     ListSeparator LS(OpStr);
325     for (const SCEV *Op : NAry->operands())
326       OS << LS << *Op;
327     OS << ")";
328     switch (NAry->getSCEVType()) {
329     case scAddExpr:
330     case scMulExpr:
331       if (NAry->hasNoUnsignedWrap())
332         OS << "<nuw>";
333       if (NAry->hasNoSignedWrap())
334         OS << "<nsw>";
335       break;
336     default:
337       // Nothing to print for other nary expressions.
338       break;
339     }
340     return;
341   }
342   case scUDivExpr: {
343     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
344     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
345     return;
346   }
347   case scUnknown: {
348     const SCEVUnknown *U = cast<SCEVUnknown>(this);
349     Type *AllocTy;
350     if (U->isSizeOf(AllocTy)) {
351       OS << "sizeof(" << *AllocTy << ")";
352       return;
353     }
354     if (U->isAlignOf(AllocTy)) {
355       OS << "alignof(" << *AllocTy << ")";
356       return;
357     }
358 
359     Type *CTy;
360     Constant *FieldNo;
361     if (U->isOffsetOf(CTy, FieldNo)) {
362       OS << "offsetof(" << *CTy << ", ";
363       FieldNo->printAsOperand(OS, false);
364       OS << ")";
365       return;
366     }
367 
368     // Otherwise just print it normally.
369     U->getValue()->printAsOperand(OS, false);
370     return;
371   }
372   case scCouldNotCompute:
373     OS << "***COULDNOTCOMPUTE***";
374     return;
375   }
376   llvm_unreachable("Unknown SCEV kind!");
377 }
378 
379 Type *SCEV::getType() const {
380   switch (getSCEVType()) {
381   case scConstant:
382     return cast<SCEVConstant>(this)->getType();
383   case scPtrToInt:
384   case scTruncate:
385   case scZeroExtend:
386   case scSignExtend:
387     return cast<SCEVCastExpr>(this)->getType();
388   case scAddRecExpr:
389     return cast<SCEVAddRecExpr>(this)->getType();
390   case scMulExpr:
391     return cast<SCEVMulExpr>(this)->getType();
392   case scUMaxExpr:
393   case scSMaxExpr:
394   case scUMinExpr:
395   case scSMinExpr:
396     return cast<SCEVMinMaxExpr>(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 // If the max analysis depth was reached, return None, assuming we do not know
692 // if they are equivalent for sure.
693 static Optional<int>
694 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
695                       EquivalenceClasses<const Value *> &EqCacheValue,
696                       const LoopInfo *const LI, const SCEV *LHS,
697                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
698   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
699   if (LHS == RHS)
700     return 0;
701 
702   // Primarily, sort the SCEVs by their getSCEVType().
703   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
704   if (LType != RType)
705     return (int)LType - (int)RType;
706 
707   if (EqCacheSCEV.isEquivalent(LHS, RHS))
708     return 0;
709 
710   if (Depth > MaxSCEVCompareDepth)
711     return None;
712 
713   // Aside from the getSCEVType() ordering, the particular ordering
714   // isn't very important except that it's beneficial to be consistent,
715   // so that (a + b) and (b + a) don't end up as different expressions.
716   switch (LType) {
717   case scUnknown: {
718     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
719     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
720 
721     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
722                                    RU->getValue(), Depth + 1);
723     if (X == 0)
724       EqCacheSCEV.unionSets(LHS, RHS);
725     return X;
726   }
727 
728   case scConstant: {
729     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
730     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
731 
732     // Compare constant values.
733     const APInt &LA = LC->getAPInt();
734     const APInt &RA = RC->getAPInt();
735     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
736     if (LBitWidth != RBitWidth)
737       return (int)LBitWidth - (int)RBitWidth;
738     return LA.ult(RA) ? -1 : 1;
739   }
740 
741   case scAddRecExpr: {
742     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
743     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
744 
745     // There is always a dominance between two recs that are used by one SCEV,
746     // so we can safely sort recs by loop header dominance. We require such
747     // order in getAddExpr.
748     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
749     if (LLoop != RLoop) {
750       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
751       assert(LHead != RHead && "Two loops share the same header?");
752       if (DT.dominates(LHead, RHead))
753         return 1;
754       else
755         assert(DT.dominates(RHead, LHead) &&
756                "No dominance between recurrences used by one SCEV?");
757       return -1;
758     }
759 
760     // Addrec complexity grows with operand count.
761     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
762     if (LNumOps != RNumOps)
763       return (int)LNumOps - (int)RNumOps;
764 
765     // Lexicographically compare.
766     for (unsigned i = 0; i != LNumOps; ++i) {
767       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
768                                      LA->getOperand(i), RA->getOperand(i), DT,
769                                      Depth + 1);
770       if (X != 0)
771         return X;
772     }
773     EqCacheSCEV.unionSets(LHS, RHS);
774     return 0;
775   }
776 
777   case scAddExpr:
778   case scMulExpr:
779   case scSMaxExpr:
780   case scUMaxExpr:
781   case scSMinExpr:
782   case scUMinExpr: {
783     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
784     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
785 
786     // Lexicographically compare n-ary expressions.
787     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
788     if (LNumOps != RNumOps)
789       return (int)LNumOps - (int)RNumOps;
790 
791     for (unsigned i = 0; i != LNumOps; ++i) {
792       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
793                                      LC->getOperand(i), RC->getOperand(i), DT,
794                                      Depth + 1);
795       if (X != 0)
796         return X;
797     }
798     EqCacheSCEV.unionSets(LHS, RHS);
799     return 0;
800   }
801 
802   case scUDivExpr: {
803     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
804     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
805 
806     // Lexicographically compare udiv expressions.
807     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
808                                    RC->getLHS(), DT, Depth + 1);
809     if (X != 0)
810       return X;
811     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
812                               RC->getRHS(), DT, Depth + 1);
813     if (X == 0)
814       EqCacheSCEV.unionSets(LHS, RHS);
815     return X;
816   }
817 
818   case scPtrToInt:
819   case scTruncate:
820   case scZeroExtend:
821   case scSignExtend: {
822     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
823     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
824 
825     // Compare cast expressions by operand.
826     auto X =
827         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
828                               RC->getOperand(), DT, Depth + 1);
829     if (X == 0)
830       EqCacheSCEV.unionSets(LHS, RHS);
831     return X;
832   }
833 
834   case scCouldNotCompute:
835     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
836   }
837   llvm_unreachable("Unknown SCEV kind!");
838 }
839 
840 /// Given a list of SCEV objects, order them by their complexity, and group
841 /// objects of the same complexity together by value.  When this routine is
842 /// finished, we know that any duplicates in the vector are consecutive and that
843 /// complexity is monotonically increasing.
844 ///
845 /// Note that we go take special precautions to ensure that we get deterministic
846 /// results from this routine.  In other words, we don't want the results of
847 /// this to depend on where the addresses of various SCEV objects happened to
848 /// land in memory.
849 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
850                               LoopInfo *LI, DominatorTree &DT) {
851   if (Ops.size() < 2) return;  // Noop
852 
853   EquivalenceClasses<const SCEV *> EqCacheSCEV;
854   EquivalenceClasses<const Value *> EqCacheValue;
855 
856   // Whether LHS has provably less complexity than RHS.
857   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
858     auto Complexity =
859         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
860     return Complexity && *Complexity < 0;
861   };
862   if (Ops.size() == 2) {
863     // This is the common case, which also happens to be trivially simple.
864     // Special case it.
865     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
866     if (IsLessComplex(RHS, LHS))
867       std::swap(LHS, RHS);
868     return;
869   }
870 
871   // Do the rough sort by complexity.
872   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
873     return IsLessComplex(LHS, RHS);
874   });
875 
876   // Now that we are sorted by complexity, group elements of the same
877   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
878   // be extremely short in practice.  Note that we take this approach because we
879   // do not want to depend on the addresses of the objects we are grouping.
880   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
881     const SCEV *S = Ops[i];
882     unsigned Complexity = S->getSCEVType();
883 
884     // If there are any objects of the same complexity and same value as this
885     // one, group them.
886     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
887       if (Ops[j] == S) { // Found a duplicate.
888         // Move it to immediately after i'th element.
889         std::swap(Ops[i+1], Ops[j]);
890         ++i;   // no need to rescan it.
891         if (i == e-2) return;  // Done!
892       }
893     }
894   }
895 }
896 
897 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
898 /// least HugeExprThreshold nodes).
899 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
900   return any_of(Ops, [](const SCEV *S) {
901     return S->getExpressionSize() >= HugeExprThreshold;
902   });
903 }
904 
905 //===----------------------------------------------------------------------===//
906 //                      Simple SCEV method implementations
907 //===----------------------------------------------------------------------===//
908 
909 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
910 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
911                                        ScalarEvolution &SE,
912                                        Type *ResultTy) {
913   // Handle the simplest case efficiently.
914   if (K == 1)
915     return SE.getTruncateOrZeroExtend(It, ResultTy);
916 
917   // We are using the following formula for BC(It, K):
918   //
919   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
920   //
921   // Suppose, W is the bitwidth of the return value.  We must be prepared for
922   // overflow.  Hence, we must assure that the result of our computation is
923   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
924   // safe in modular arithmetic.
925   //
926   // However, this code doesn't use exactly that formula; the formula it uses
927   // is something like the following, where T is the number of factors of 2 in
928   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
929   // exponentiation:
930   //
931   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
932   //
933   // This formula is trivially equivalent to the previous formula.  However,
934   // this formula can be implemented much more efficiently.  The trick is that
935   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
936   // arithmetic.  To do exact division in modular arithmetic, all we have
937   // to do is multiply by the inverse.  Therefore, this step can be done at
938   // width W.
939   //
940   // The next issue is how to safely do the division by 2^T.  The way this
941   // is done is by doing the multiplication step at a width of at least W + T
942   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
943   // when we perform the division by 2^T (which is equivalent to a right shift
944   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
945   // truncated out after the division by 2^T.
946   //
947   // In comparison to just directly using the first formula, this technique
948   // is much more efficient; using the first formula requires W * K bits,
949   // but this formula less than W + K bits. Also, the first formula requires
950   // a division step, whereas this formula only requires multiplies and shifts.
951   //
952   // It doesn't matter whether the subtraction step is done in the calculation
953   // width or the input iteration count's width; if the subtraction overflows,
954   // the result must be zero anyway.  We prefer here to do it in the width of
955   // the induction variable because it helps a lot for certain cases; CodeGen
956   // isn't smart enough to ignore the overflow, which leads to much less
957   // efficient code if the width of the subtraction is wider than the native
958   // register width.
959   //
960   // (It's possible to not widen at all by pulling out factors of 2 before
961   // the multiplication; for example, K=2 can be calculated as
962   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
963   // extra arithmetic, so it's not an obvious win, and it gets
964   // much more complicated for K > 3.)
965 
966   // Protection from insane SCEVs; this bound is conservative,
967   // but it probably doesn't matter.
968   if (K > 1000)
969     return SE.getCouldNotCompute();
970 
971   unsigned W = SE.getTypeSizeInBits(ResultTy);
972 
973   // Calculate K! / 2^T and T; we divide out the factors of two before
974   // multiplying for calculating K! / 2^T to avoid overflow.
975   // Other overflow doesn't matter because we only care about the bottom
976   // W bits of the result.
977   APInt OddFactorial(W, 1);
978   unsigned T = 1;
979   for (unsigned i = 3; i <= K; ++i) {
980     APInt Mult(W, i);
981     unsigned TwoFactors = Mult.countTrailingZeros();
982     T += TwoFactors;
983     Mult.lshrInPlace(TwoFactors);
984     OddFactorial *= Mult;
985   }
986 
987   // We need at least W + T bits for the multiplication step
988   unsigned CalculationBits = W + T;
989 
990   // Calculate 2^T, at width T+W.
991   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
992 
993   // Calculate the multiplicative inverse of K! / 2^T;
994   // this multiplication factor will perform the exact division by
995   // K! / 2^T.
996   APInt Mod = APInt::getSignedMinValue(W+1);
997   APInt MultiplyFactor = OddFactorial.zext(W+1);
998   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
999   MultiplyFactor = MultiplyFactor.trunc(W);
1000 
1001   // Calculate the product, at width T+W
1002   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1003                                                       CalculationBits);
1004   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1005   for (unsigned i = 1; i != K; ++i) {
1006     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1007     Dividend = SE.getMulExpr(Dividend,
1008                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1009   }
1010 
1011   // Divide by 2^T
1012   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1013 
1014   // Truncate the result, and divide by K! / 2^T.
1015 
1016   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1017                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1018 }
1019 
1020 /// Return the value of this chain of recurrences at the specified iteration
1021 /// number.  We can evaluate this recurrence by multiplying each element in the
1022 /// chain by the binomial coefficient corresponding to it.  In other words, we
1023 /// can evaluate {A,+,B,+,C,+,D} as:
1024 ///
1025 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1026 ///
1027 /// where BC(It, k) stands for binomial coefficient.
1028 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1029                                                 ScalarEvolution &SE) const {
1030   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1031 }
1032 
1033 const SCEV *
1034 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1035                                     const SCEV *It, ScalarEvolution &SE) {
1036   assert(Operands.size() > 0);
1037   const SCEV *Result = Operands[0];
1038   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1039     // The computation is correct in the face of overflow provided that the
1040     // multiplication is performed _after_ the evaluation of the binomial
1041     // coefficient.
1042     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1043     if (isa<SCEVCouldNotCompute>(Coeff))
1044       return Coeff;
1045 
1046     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1047   }
1048   return Result;
1049 }
1050 
1051 //===----------------------------------------------------------------------===//
1052 //                    SCEV Expression folder implementations
1053 //===----------------------------------------------------------------------===//
1054 
1055 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1056                                                      unsigned Depth) {
1057   assert(Depth <= 1 &&
1058          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1059 
1060   // We could be called with an integer-typed operands during SCEV rewrites.
1061   // Since the operand is an integer already, just perform zext/trunc/self cast.
1062   if (!Op->getType()->isPointerTy())
1063     return Op;
1064 
1065   // What would be an ID for such a SCEV cast expression?
1066   FoldingSetNodeID ID;
1067   ID.AddInteger(scPtrToInt);
1068   ID.AddPointer(Op);
1069 
1070   void *IP = nullptr;
1071 
1072   // Is there already an expression for such a cast?
1073   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1074     return S;
1075 
1076   // It isn't legal for optimizations to construct new ptrtoint expressions
1077   // for non-integral pointers.
1078   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1079     return getCouldNotCompute();
1080 
1081   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1082 
1083   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1084   // is sufficiently wide to represent all possible pointer values.
1085   // We could theoretically teach SCEV to truncate wider pointers, but
1086   // that isn't implemented for now.
1087   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1088       getDataLayout().getTypeSizeInBits(IntPtrTy))
1089     return getCouldNotCompute();
1090 
1091   // If not, is this expression something we can't reduce any further?
1092   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1093     // Perform some basic constant folding. If the operand of the ptr2int cast
1094     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1095     // left as-is), but produce a zero constant.
1096     // NOTE: We could handle a more general case, but lack motivational cases.
1097     if (isa<ConstantPointerNull>(U->getValue()))
1098       return getZero(IntPtrTy);
1099 
1100     // Create an explicit cast node.
1101     // We can reuse the existing insert position since if we get here,
1102     // we won't have made any changes which would invalidate it.
1103     SCEV *S = new (SCEVAllocator)
1104         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1105     UniqueSCEVs.InsertNode(S, IP);
1106     addToLoopUseLists(S);
1107     return S;
1108   }
1109 
1110   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1111                        "non-SCEVUnknown's.");
1112 
1113   // Otherwise, we've got some expression that is more complex than just a
1114   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1115   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1116   // only, and the expressions must otherwise be integer-typed.
1117   // So sink the cast down to the SCEVUnknown's.
1118 
1119   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1120   /// which computes a pointer-typed value, and rewrites the whole expression
1121   /// tree so that *all* the computations are done on integers, and the only
1122   /// pointer-typed operands in the expression are SCEVUnknown.
1123   class SCEVPtrToIntSinkingRewriter
1124       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1125     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1126 
1127   public:
1128     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1129 
1130     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1131       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1132       return Rewriter.visit(Scev);
1133     }
1134 
1135     const SCEV *visit(const SCEV *S) {
1136       Type *STy = S->getType();
1137       // If the expression is not pointer-typed, just keep it as-is.
1138       if (!STy->isPointerTy())
1139         return S;
1140       // Else, recursively sink the cast down into it.
1141       return Base::visit(S);
1142     }
1143 
1144     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1145       SmallVector<const SCEV *, 2> Operands;
1146       bool Changed = false;
1147       for (auto *Op : Expr->operands()) {
1148         Operands.push_back(visit(Op));
1149         Changed |= Op != Operands.back();
1150       }
1151       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1152     }
1153 
1154     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1155       SmallVector<const SCEV *, 2> Operands;
1156       bool Changed = false;
1157       for (auto *Op : Expr->operands()) {
1158         Operands.push_back(visit(Op));
1159         Changed |= Op != Operands.back();
1160       }
1161       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1162     }
1163 
1164     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1165       assert(Expr->getType()->isPointerTy() &&
1166              "Should only reach pointer-typed SCEVUnknown's.");
1167       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1168     }
1169   };
1170 
1171   // And actually perform the cast sinking.
1172   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1173   assert(IntOp->getType()->isIntegerTy() &&
1174          "We must have succeeded in sinking the cast, "
1175          "and ending up with an integer-typed expression!");
1176   return IntOp;
1177 }
1178 
1179 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1180   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1181 
1182   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1183   if (isa<SCEVCouldNotCompute>(IntOp))
1184     return IntOp;
1185 
1186   return getTruncateOrZeroExtend(IntOp, Ty);
1187 }
1188 
1189 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1190                                              unsigned Depth) {
1191   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1192          "This is not a truncating conversion!");
1193   assert(isSCEVable(Ty) &&
1194          "This is not a conversion to a SCEVable type!");
1195   Ty = getEffectiveSCEVType(Ty);
1196 
1197   FoldingSetNodeID ID;
1198   ID.AddInteger(scTruncate);
1199   ID.AddPointer(Op);
1200   ID.AddPointer(Ty);
1201   void *IP = nullptr;
1202   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1203 
1204   // Fold if the operand is constant.
1205   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1206     return getConstant(
1207       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1208 
1209   // trunc(trunc(x)) --> trunc(x)
1210   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1211     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1212 
1213   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1214   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1215     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1216 
1217   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1218   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1219     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1220 
1221   if (Depth > MaxCastDepth) {
1222     SCEV *S =
1223         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1224     UniqueSCEVs.InsertNode(S, IP);
1225     addToLoopUseLists(S);
1226     return S;
1227   }
1228 
1229   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1230   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1231   // if after transforming we have at most one truncate, not counting truncates
1232   // that replace other casts.
1233   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1234     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1235     SmallVector<const SCEV *, 4> Operands;
1236     unsigned numTruncs = 0;
1237     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1238          ++i) {
1239       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1240       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1241           isa<SCEVTruncateExpr>(S))
1242         numTruncs++;
1243       Operands.push_back(S);
1244     }
1245     if (numTruncs < 2) {
1246       if (isa<SCEVAddExpr>(Op))
1247         return getAddExpr(Operands);
1248       else if (isa<SCEVMulExpr>(Op))
1249         return getMulExpr(Operands);
1250       else
1251         llvm_unreachable("Unexpected SCEV type for Op.");
1252     }
1253     // Although we checked in the beginning that ID is not in the cache, it is
1254     // possible that during recursion and different modification ID was inserted
1255     // into the cache. So if we find it, just return it.
1256     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1257       return S;
1258   }
1259 
1260   // If the input value is a chrec scev, truncate the chrec's operands.
1261   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1262     SmallVector<const SCEV *, 4> Operands;
1263     for (const SCEV *Op : AddRec->operands())
1264       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1265     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1266   }
1267 
1268   // Return zero if truncating to known zeros.
1269   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1270   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1271     return getZero(Ty);
1272 
1273   // The cast wasn't folded; create an explicit cast node. We can reuse
1274   // the existing insert position since if we get here, we won't have
1275   // made any changes which would invalidate it.
1276   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1277                                                  Op, Ty);
1278   UniqueSCEVs.InsertNode(S, IP);
1279   addToLoopUseLists(S);
1280   return S;
1281 }
1282 
1283 // Get the limit of a recurrence such that incrementing by Step cannot cause
1284 // signed overflow as long as the value of the recurrence within the
1285 // loop does not exceed this limit before incrementing.
1286 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1287                                                  ICmpInst::Predicate *Pred,
1288                                                  ScalarEvolution *SE) {
1289   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1290   if (SE->isKnownPositive(Step)) {
1291     *Pred = ICmpInst::ICMP_SLT;
1292     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1293                            SE->getSignedRangeMax(Step));
1294   }
1295   if (SE->isKnownNegative(Step)) {
1296     *Pred = ICmpInst::ICMP_SGT;
1297     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1298                            SE->getSignedRangeMin(Step));
1299   }
1300   return nullptr;
1301 }
1302 
1303 // Get the limit of a recurrence such that incrementing by Step cannot cause
1304 // unsigned overflow as long as the value of the recurrence within the loop does
1305 // not exceed this limit before incrementing.
1306 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1307                                                    ICmpInst::Predicate *Pred,
1308                                                    ScalarEvolution *SE) {
1309   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1310   *Pred = ICmpInst::ICMP_ULT;
1311 
1312   return SE->getConstant(APInt::getMinValue(BitWidth) -
1313                          SE->getUnsignedRangeMax(Step));
1314 }
1315 
1316 namespace {
1317 
1318 struct ExtendOpTraitsBase {
1319   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1320                                                           unsigned);
1321 };
1322 
1323 // Used to make code generic over signed and unsigned overflow.
1324 template <typename ExtendOp> struct ExtendOpTraits {
1325   // Members present:
1326   //
1327   // static const SCEV::NoWrapFlags WrapType;
1328   //
1329   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1330   //
1331   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1332   //                                           ICmpInst::Predicate *Pred,
1333   //                                           ScalarEvolution *SE);
1334 };
1335 
1336 template <>
1337 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1338   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1339 
1340   static const GetExtendExprTy GetExtendExpr;
1341 
1342   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1343                                              ICmpInst::Predicate *Pred,
1344                                              ScalarEvolution *SE) {
1345     return getSignedOverflowLimitForStep(Step, Pred, SE);
1346   }
1347 };
1348 
1349 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1350     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1351 
1352 template <>
1353 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1354   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1355 
1356   static const GetExtendExprTy GetExtendExpr;
1357 
1358   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1359                                              ICmpInst::Predicate *Pred,
1360                                              ScalarEvolution *SE) {
1361     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1362   }
1363 };
1364 
1365 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1366     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1367 
1368 } // end anonymous namespace
1369 
1370 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1371 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1372 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1373 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1374 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1375 // expression "Step + sext/zext(PreIncAR)" is congruent with
1376 // "sext/zext(PostIncAR)"
1377 template <typename ExtendOpTy>
1378 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1379                                         ScalarEvolution *SE, unsigned Depth) {
1380   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1381   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1382 
1383   const Loop *L = AR->getLoop();
1384   const SCEV *Start = AR->getStart();
1385   const SCEV *Step = AR->getStepRecurrence(*SE);
1386 
1387   // Check for a simple looking step prior to loop entry.
1388   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1389   if (!SA)
1390     return nullptr;
1391 
1392   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1393   // subtraction is expensive. For this purpose, perform a quick and dirty
1394   // difference, by checking for Step in the operand list.
1395   SmallVector<const SCEV *, 4> DiffOps;
1396   for (const SCEV *Op : SA->operands())
1397     if (Op != Step)
1398       DiffOps.push_back(Op);
1399 
1400   if (DiffOps.size() == SA->getNumOperands())
1401     return nullptr;
1402 
1403   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1404   // `Step`:
1405 
1406   // 1. NSW/NUW flags on the step increment.
1407   auto PreStartFlags =
1408     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1409   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1410   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1411       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1412 
1413   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1414   // "S+X does not sign/unsign-overflow".
1415   //
1416 
1417   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1418   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1419       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1420     return PreStart;
1421 
1422   // 2. Direct overflow check on the step operation's expression.
1423   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1424   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1425   const SCEV *OperandExtendedStart =
1426       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1427                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1428   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1429     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1430       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1431       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1432       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1433       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1434     }
1435     return PreStart;
1436   }
1437 
1438   // 3. Loop precondition.
1439   ICmpInst::Predicate Pred;
1440   const SCEV *OverflowLimit =
1441       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1442 
1443   if (OverflowLimit &&
1444       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1445     return PreStart;
1446 
1447   return nullptr;
1448 }
1449 
1450 // Get the normalized zero or sign extended expression for this AddRec's Start.
1451 template <typename ExtendOpTy>
1452 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1453                                         ScalarEvolution *SE,
1454                                         unsigned Depth) {
1455   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1456 
1457   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1458   if (!PreStart)
1459     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1460 
1461   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1462                                              Depth),
1463                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1464 }
1465 
1466 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1467 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1468 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1469 //
1470 // Formally:
1471 //
1472 //     {S,+,X} == {S-T,+,X} + T
1473 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1474 //
1475 // If ({S-T,+,X} + T) does not overflow  ... (1)
1476 //
1477 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1478 //
1479 // If {S-T,+,X} does not overflow  ... (2)
1480 //
1481 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1482 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1483 //
1484 // If (S-T)+T does not overflow  ... (3)
1485 //
1486 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1487 //      == {Ext(S),+,Ext(X)} == LHS
1488 //
1489 // Thus, if (1), (2) and (3) are true for some T, then
1490 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1491 //
1492 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1493 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1494 // to check for (1) and (2).
1495 //
1496 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1497 // is `Delta` (defined below).
1498 template <typename ExtendOpTy>
1499 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1500                                                 const SCEV *Step,
1501                                                 const Loop *L) {
1502   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1503 
1504   // We restrict `Start` to a constant to prevent SCEV from spending too much
1505   // time here.  It is correct (but more expensive) to continue with a
1506   // non-constant `Start` and do a general SCEV subtraction to compute
1507   // `PreStart` below.
1508   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1509   if (!StartC)
1510     return false;
1511 
1512   APInt StartAI = StartC->getAPInt();
1513 
1514   for (unsigned Delta : {-2, -1, 1, 2}) {
1515     const SCEV *PreStart = getConstant(StartAI - Delta);
1516 
1517     FoldingSetNodeID ID;
1518     ID.AddInteger(scAddRecExpr);
1519     ID.AddPointer(PreStart);
1520     ID.AddPointer(Step);
1521     ID.AddPointer(L);
1522     void *IP = nullptr;
1523     const auto *PreAR =
1524       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1525 
1526     // Give up if we don't already have the add recurrence we need because
1527     // actually constructing an add recurrence is relatively expensive.
1528     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1529       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1530       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1531       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1532           DeltaS, &Pred, this);
1533       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1534         return true;
1535     }
1536   }
1537 
1538   return false;
1539 }
1540 
1541 // Finds an integer D for an expression (C + x + y + ...) such that the top
1542 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1543 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1544 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1545 // the (C + x + y + ...) expression is \p WholeAddExpr.
1546 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1547                                             const SCEVConstant *ConstantTerm,
1548                                             const SCEVAddExpr *WholeAddExpr) {
1549   const APInt &C = ConstantTerm->getAPInt();
1550   const unsigned BitWidth = C.getBitWidth();
1551   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1552   uint32_t TZ = BitWidth;
1553   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1554     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1555   if (TZ) {
1556     // Set D to be as many least significant bits of C as possible while still
1557     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1558     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1559   }
1560   return APInt(BitWidth, 0);
1561 }
1562 
1563 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1564 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1565 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1566 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1567 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1568                                             const APInt &ConstantStart,
1569                                             const SCEV *Step) {
1570   const unsigned BitWidth = ConstantStart.getBitWidth();
1571   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1572   if (TZ)
1573     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1574                          : ConstantStart;
1575   return APInt(BitWidth, 0);
1576 }
1577 
1578 const SCEV *
1579 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1580   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1581          "This is not an extending conversion!");
1582   assert(isSCEVable(Ty) &&
1583          "This is not a conversion to a SCEVable type!");
1584   Ty = getEffectiveSCEVType(Ty);
1585 
1586   // Fold if the operand is constant.
1587   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1588     return getConstant(
1589       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1590 
1591   // zext(zext(x)) --> zext(x)
1592   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1593     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1594 
1595   // Before doing any expensive analysis, check to see if we've already
1596   // computed a SCEV for this Op and Ty.
1597   FoldingSetNodeID ID;
1598   ID.AddInteger(scZeroExtend);
1599   ID.AddPointer(Op);
1600   ID.AddPointer(Ty);
1601   void *IP = nullptr;
1602   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1603   if (Depth > MaxCastDepth) {
1604     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1605                                                      Op, Ty);
1606     UniqueSCEVs.InsertNode(S, IP);
1607     addToLoopUseLists(S);
1608     return S;
1609   }
1610 
1611   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1612   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1613     // It's possible the bits taken off by the truncate were all zero bits. If
1614     // so, we should be able to simplify this further.
1615     const SCEV *X = ST->getOperand();
1616     ConstantRange CR = getUnsignedRange(X);
1617     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1618     unsigned NewBits = getTypeSizeInBits(Ty);
1619     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1620             CR.zextOrTrunc(NewBits)))
1621       return getTruncateOrZeroExtend(X, Ty, Depth);
1622   }
1623 
1624   // If the input value is a chrec scev, and we can prove that the value
1625   // did not overflow the old, smaller, value, we can zero extend all of the
1626   // operands (often constants).  This allows analysis of something like
1627   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1628   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1629     if (AR->isAffine()) {
1630       const SCEV *Start = AR->getStart();
1631       const SCEV *Step = AR->getStepRecurrence(*this);
1632       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1633       const Loop *L = AR->getLoop();
1634 
1635       if (!AR->hasNoUnsignedWrap()) {
1636         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1637         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1638       }
1639 
1640       // If we have special knowledge that this addrec won't overflow,
1641       // we don't need to do any further analysis.
1642       if (AR->hasNoUnsignedWrap())
1643         return getAddRecExpr(
1644             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1645             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1646 
1647       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1648       // Note that this serves two purposes: It filters out loops that are
1649       // simply not analyzable, and it covers the case where this code is
1650       // being called from within backedge-taken count analysis, such that
1651       // attempting to ask for the backedge-taken count would likely result
1652       // in infinite recursion. In the later case, the analysis code will
1653       // cope with a conservative value, and it will take care to purge
1654       // that value once it has finished.
1655       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1656       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1657         // Manually compute the final value for AR, checking for overflow.
1658 
1659         // Check whether the backedge-taken count can be losslessly casted to
1660         // the addrec's type. The count is always unsigned.
1661         const SCEV *CastedMaxBECount =
1662             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1663         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1664             CastedMaxBECount, MaxBECount->getType(), Depth);
1665         if (MaxBECount == RecastedMaxBECount) {
1666           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1667           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1668           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1669                                         SCEV::FlagAnyWrap, Depth + 1);
1670           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1671                                                           SCEV::FlagAnyWrap,
1672                                                           Depth + 1),
1673                                                WideTy, Depth + 1);
1674           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1675           const SCEV *WideMaxBECount =
1676             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1677           const SCEV *OperandExtendedAdd =
1678             getAddExpr(WideStart,
1679                        getMulExpr(WideMaxBECount,
1680                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1681                                   SCEV::FlagAnyWrap, Depth + 1),
1682                        SCEV::FlagAnyWrap, Depth + 1);
1683           if (ZAdd == OperandExtendedAdd) {
1684             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1685             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1686             // Return the expression with the addrec on the outside.
1687             return getAddRecExpr(
1688                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1689                                                          Depth + 1),
1690                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1691                 AR->getNoWrapFlags());
1692           }
1693           // Similar to above, only this time treat the step value as signed.
1694           // This covers loops that count down.
1695           OperandExtendedAdd =
1696             getAddExpr(WideStart,
1697                        getMulExpr(WideMaxBECount,
1698                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1699                                   SCEV::FlagAnyWrap, Depth + 1),
1700                        SCEV::FlagAnyWrap, Depth + 1);
1701           if (ZAdd == OperandExtendedAdd) {
1702             // Cache knowledge of AR NW, which is propagated to this AddRec.
1703             // Negative step causes unsigned wrap, but it still can't self-wrap.
1704             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), 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       // Normally, in the cases we can prove no-overflow via a
1716       // backedge guarding condition, we can also compute a backedge
1717       // taken count for the loop.  The exceptions are assumptions and
1718       // guards present in the loop -- SCEV is not great at exploiting
1719       // these to compute max backedge taken counts, but can still use
1720       // these to prove lack of overflow.  Use this fact to avoid
1721       // doing extra work that may not pay off.
1722       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1723           !AC.assumptions().empty()) {
1724 
1725         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1726         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1727         if (AR->hasNoUnsignedWrap()) {
1728           // Same as nuw case above - duplicated here to avoid a compile time
1729           // issue.  It's not clear that the order of checks does matter, but
1730           // it's one of two issue possible causes for a change which was
1731           // reverted.  Be conservative for the moment.
1732           return getAddRecExpr(
1733                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1734                                                          Depth + 1),
1735                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1736                 AR->getNoWrapFlags());
1737         }
1738 
1739         // For a negative step, we can extend the operands iff doing so only
1740         // traverses values in the range zext([0,UINT_MAX]).
1741         if (isKnownNegative(Step)) {
1742           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1743                                       getSignedRangeMin(Step));
1744           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1745               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1746             // Cache knowledge of AR NW, which is propagated to this
1747             // AddRec.  Negative step causes unsigned wrap, but it
1748             // still can't self-wrap.
1749             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1750             // Return the expression with the addrec on the outside.
1751             return getAddRecExpr(
1752                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1753                                                          Depth + 1),
1754                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1755                 AR->getNoWrapFlags());
1756           }
1757         }
1758       }
1759 
1760       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1761       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1762       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1763       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1764         const APInt &C = SC->getAPInt();
1765         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1766         if (D != 0) {
1767           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1768           const SCEV *SResidual =
1769               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1770           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1771           return getAddExpr(SZExtD, SZExtR,
1772                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1773                             Depth + 1);
1774         }
1775       }
1776 
1777       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1778         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1779         return getAddRecExpr(
1780             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1781             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1782       }
1783     }
1784 
1785   // zext(A % B) --> zext(A) % zext(B)
1786   {
1787     const SCEV *LHS;
1788     const SCEV *RHS;
1789     if (matchURem(Op, LHS, RHS))
1790       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1791                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1792   }
1793 
1794   // zext(A / B) --> zext(A) / zext(B).
1795   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1796     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1797                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1798 
1799   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1800     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1801     if (SA->hasNoUnsignedWrap()) {
1802       // If the addition does not unsign overflow then we can, by definition,
1803       // commute the zero extension with the addition operation.
1804       SmallVector<const SCEV *, 4> Ops;
1805       for (const auto *Op : SA->operands())
1806         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1807       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1808     }
1809 
1810     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1811     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1812     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1813     //
1814     // Often address arithmetics contain expressions like
1815     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1816     // This transformation is useful while proving that such expressions are
1817     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1818     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1819       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1820       if (D != 0) {
1821         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1822         const SCEV *SResidual =
1823             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1824         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1825         return getAddExpr(SZExtD, SZExtR,
1826                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1827                           Depth + 1);
1828       }
1829     }
1830   }
1831 
1832   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1833     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1834     if (SM->hasNoUnsignedWrap()) {
1835       // If the multiply does not unsign overflow then we can, by definition,
1836       // commute the zero extension with the multiply operation.
1837       SmallVector<const SCEV *, 4> Ops;
1838       for (const auto *Op : SM->operands())
1839         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1840       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1841     }
1842 
1843     // zext(2^K * (trunc X to iN)) to iM ->
1844     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1845     //
1846     // Proof:
1847     //
1848     //     zext(2^K * (trunc X to iN)) to iM
1849     //   = zext((trunc X to iN) << K) to iM
1850     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1851     //     (because shl removes the top K bits)
1852     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1853     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1854     //
1855     if (SM->getNumOperands() == 2)
1856       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1857         if (MulLHS->getAPInt().isPowerOf2())
1858           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1859             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1860                                MulLHS->getAPInt().logBase2();
1861             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1862             return getMulExpr(
1863                 getZeroExtendExpr(MulLHS, Ty),
1864                 getZeroExtendExpr(
1865                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1866                 SCEV::FlagNUW, Depth + 1);
1867           }
1868   }
1869 
1870   // The cast wasn't folded; create an explicit cast node.
1871   // Recompute the insert position, as it may have been invalidated.
1872   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1873   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1874                                                    Op, Ty);
1875   UniqueSCEVs.InsertNode(S, IP);
1876   addToLoopUseLists(S);
1877   return S;
1878 }
1879 
1880 const SCEV *
1881 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1882   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1883          "This is not an extending conversion!");
1884   assert(isSCEVable(Ty) &&
1885          "This is not a conversion to a SCEVable type!");
1886   Ty = getEffectiveSCEVType(Ty);
1887 
1888   // Fold if the operand is constant.
1889   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1890     return getConstant(
1891       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1892 
1893   // sext(sext(x)) --> sext(x)
1894   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1895     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1896 
1897   // sext(zext(x)) --> zext(x)
1898   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1899     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1900 
1901   // Before doing any expensive analysis, check to see if we've already
1902   // computed a SCEV for this Op and Ty.
1903   FoldingSetNodeID ID;
1904   ID.AddInteger(scSignExtend);
1905   ID.AddPointer(Op);
1906   ID.AddPointer(Ty);
1907   void *IP = nullptr;
1908   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1909   // Limit recursion depth.
1910   if (Depth > MaxCastDepth) {
1911     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1912                                                      Op, Ty);
1913     UniqueSCEVs.InsertNode(S, IP);
1914     addToLoopUseLists(S);
1915     return S;
1916   }
1917 
1918   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1919   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1920     // It's possible the bits taken off by the truncate were all sign bits. If
1921     // so, we should be able to simplify this further.
1922     const SCEV *X = ST->getOperand();
1923     ConstantRange CR = getSignedRange(X);
1924     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1925     unsigned NewBits = getTypeSizeInBits(Ty);
1926     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1927             CR.sextOrTrunc(NewBits)))
1928       return getTruncateOrSignExtend(X, Ty, Depth);
1929   }
1930 
1931   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1932     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1933     if (SA->hasNoSignedWrap()) {
1934       // If the addition does not sign overflow then we can, by definition,
1935       // commute the sign extension with the addition operation.
1936       SmallVector<const SCEV *, 4> Ops;
1937       for (const auto *Op : SA->operands())
1938         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1939       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1940     }
1941 
1942     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1943     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1944     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1945     //
1946     // For instance, this will bring two seemingly different expressions:
1947     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1948     //         sext(6 + 20 * %x + 24 * %y)
1949     // to the same form:
1950     //     2 + sext(4 + 20 * %x + 24 * %y)
1951     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1952       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1953       if (D != 0) {
1954         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1955         const SCEV *SResidual =
1956             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1957         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1958         return getAddExpr(SSExtD, SSExtR,
1959                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1960                           Depth + 1);
1961       }
1962     }
1963   }
1964   // If the input value is a chrec scev, and we can prove that the value
1965   // did not overflow the old, smaller, value, we can sign extend all of the
1966   // operands (often constants).  This allows analysis of something like
1967   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1968   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1969     if (AR->isAffine()) {
1970       const SCEV *Start = AR->getStart();
1971       const SCEV *Step = AR->getStepRecurrence(*this);
1972       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1973       const Loop *L = AR->getLoop();
1974 
1975       if (!AR->hasNoSignedWrap()) {
1976         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1977         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1978       }
1979 
1980       // If we have special knowledge that this addrec won't overflow,
1981       // we don't need to do any further analysis.
1982       if (AR->hasNoSignedWrap())
1983         return getAddRecExpr(
1984             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1985             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1986 
1987       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1988       // Note that this serves two purposes: It filters out loops that are
1989       // simply not analyzable, and it covers the case where this code is
1990       // being called from within backedge-taken count analysis, such that
1991       // attempting to ask for the backedge-taken count would likely result
1992       // in infinite recursion. In the later case, the analysis code will
1993       // cope with a conservative value, and it will take care to purge
1994       // that value once it has finished.
1995       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1996       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1997         // Manually compute the final value for AR, checking for
1998         // overflow.
1999 
2000         // Check whether the backedge-taken count can be losslessly casted to
2001         // the addrec's type. The count is always unsigned.
2002         const SCEV *CastedMaxBECount =
2003             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2004         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2005             CastedMaxBECount, MaxBECount->getType(), Depth);
2006         if (MaxBECount == RecastedMaxBECount) {
2007           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2008           // Check whether Start+Step*MaxBECount has no signed overflow.
2009           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2010                                         SCEV::FlagAnyWrap, Depth + 1);
2011           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2012                                                           SCEV::FlagAnyWrap,
2013                                                           Depth + 1),
2014                                                WideTy, Depth + 1);
2015           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2016           const SCEV *WideMaxBECount =
2017             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2018           const SCEV *OperandExtendedAdd =
2019             getAddExpr(WideStart,
2020                        getMulExpr(WideMaxBECount,
2021                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2022                                   SCEV::FlagAnyWrap, Depth + 1),
2023                        SCEV::FlagAnyWrap, Depth + 1);
2024           if (SAdd == OperandExtendedAdd) {
2025             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2026             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2027             // Return the expression with the addrec on the outside.
2028             return getAddRecExpr(
2029                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2030                                                          Depth + 1),
2031                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2032                 AR->getNoWrapFlags());
2033           }
2034           // Similar to above, only this time treat the step value as unsigned.
2035           // This covers loops that count up with an unsigned step.
2036           OperandExtendedAdd =
2037             getAddExpr(WideStart,
2038                        getMulExpr(WideMaxBECount,
2039                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2040                                   SCEV::FlagAnyWrap, Depth + 1),
2041                        SCEV::FlagAnyWrap, Depth + 1);
2042           if (SAdd == OperandExtendedAdd) {
2043             // If AR wraps around then
2044             //
2045             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2046             // => SAdd != OperandExtendedAdd
2047             //
2048             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2049             // (SAdd == OperandExtendedAdd => AR is NW)
2050 
2051             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2052 
2053             // Return the expression with the addrec on the outside.
2054             return getAddRecExpr(
2055                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2056                                                          Depth + 1),
2057                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2058                 AR->getNoWrapFlags());
2059           }
2060         }
2061       }
2062 
2063       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2064       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2065       if (AR->hasNoSignedWrap()) {
2066         // Same as nsw case above - duplicated here to avoid a compile time
2067         // issue.  It's not clear that the order of checks does matter, but
2068         // it's one of two issue possible causes for a change which was
2069         // reverted.  Be conservative for the moment.
2070         return getAddRecExpr(
2071             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2072             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2073       }
2074 
2075       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2076       // if D + (C - D + Step * n) could be proven to not signed wrap
2077       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2078       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2079         const APInt &C = SC->getAPInt();
2080         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2081         if (D != 0) {
2082           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2083           const SCEV *SResidual =
2084               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2085           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2086           return getAddExpr(SSExtD, SSExtR,
2087                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2088                             Depth + 1);
2089         }
2090       }
2091 
2092       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2093         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2094         return getAddRecExpr(
2095             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2096             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2097       }
2098     }
2099 
2100   // If the input value is provably positive and we could not simplify
2101   // away the sext build a zext instead.
2102   if (isKnownNonNegative(Op))
2103     return getZeroExtendExpr(Op, Ty, Depth + 1);
2104 
2105   // The cast wasn't folded; create an explicit cast node.
2106   // Recompute the insert position, as it may have been invalidated.
2107   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2108   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2109                                                    Op, Ty);
2110   UniqueSCEVs.InsertNode(S, IP);
2111   addToLoopUseLists(S);
2112   return S;
2113 }
2114 
2115 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2116 /// unspecified bits out to the given type.
2117 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2118                                               Type *Ty) {
2119   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2120          "This is not an extending conversion!");
2121   assert(isSCEVable(Ty) &&
2122          "This is not a conversion to a SCEVable type!");
2123   Ty = getEffectiveSCEVType(Ty);
2124 
2125   // Sign-extend negative constants.
2126   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2127     if (SC->getAPInt().isNegative())
2128       return getSignExtendExpr(Op, Ty);
2129 
2130   // Peel off a truncate cast.
2131   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2132     const SCEV *NewOp = T->getOperand();
2133     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2134       return getAnyExtendExpr(NewOp, Ty);
2135     return getTruncateOrNoop(NewOp, Ty);
2136   }
2137 
2138   // Next try a zext cast. If the cast is folded, use it.
2139   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2140   if (!isa<SCEVZeroExtendExpr>(ZExt))
2141     return ZExt;
2142 
2143   // Next try a sext cast. If the cast is folded, use it.
2144   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2145   if (!isa<SCEVSignExtendExpr>(SExt))
2146     return SExt;
2147 
2148   // Force the cast to be folded into the operands of an addrec.
2149   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2150     SmallVector<const SCEV *, 4> Ops;
2151     for (const SCEV *Op : AR->operands())
2152       Ops.push_back(getAnyExtendExpr(Op, Ty));
2153     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2154   }
2155 
2156   // If the expression is obviously signed, use the sext cast value.
2157   if (isa<SCEVSMaxExpr>(Op))
2158     return SExt;
2159 
2160   // Absent any other information, use the zext cast value.
2161   return ZExt;
2162 }
2163 
2164 /// Process the given Ops list, which is a list of operands to be added under
2165 /// the given scale, update the given map. This is a helper function for
2166 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2167 /// that would form an add expression like this:
2168 ///
2169 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2170 ///
2171 /// where A and B are constants, update the map with these values:
2172 ///
2173 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2174 ///
2175 /// and add 13 + A*B*29 to AccumulatedConstant.
2176 /// This will allow getAddRecExpr to produce this:
2177 ///
2178 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2179 ///
2180 /// This form often exposes folding opportunities that are hidden in
2181 /// the original operand list.
2182 ///
2183 /// Return true iff it appears that any interesting folding opportunities
2184 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2185 /// the common case where no interesting opportunities are present, and
2186 /// is also used as a check to avoid infinite recursion.
2187 static bool
2188 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2189                              SmallVectorImpl<const SCEV *> &NewOps,
2190                              APInt &AccumulatedConstant,
2191                              const SCEV *const *Ops, size_t NumOperands,
2192                              const APInt &Scale,
2193                              ScalarEvolution &SE) {
2194   bool Interesting = false;
2195 
2196   // Iterate over the add operands. They are sorted, with constants first.
2197   unsigned i = 0;
2198   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2199     ++i;
2200     // Pull a buried constant out to the outside.
2201     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2202       Interesting = true;
2203     AccumulatedConstant += Scale * C->getAPInt();
2204   }
2205 
2206   // Next comes everything else. We're especially interested in multiplies
2207   // here, but they're in the middle, so just visit the rest with one loop.
2208   for (; i != NumOperands; ++i) {
2209     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2210     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2211       APInt NewScale =
2212           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2213       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2214         // A multiplication of a constant with another add; recurse.
2215         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2216         Interesting |=
2217           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2218                                        Add->op_begin(), Add->getNumOperands(),
2219                                        NewScale, SE);
2220       } else {
2221         // A multiplication of a constant with some other value. Update
2222         // the map.
2223         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2224         const SCEV *Key = SE.getMulExpr(MulOps);
2225         auto Pair = M.insert({Key, NewScale});
2226         if (Pair.second) {
2227           NewOps.push_back(Pair.first->first);
2228         } else {
2229           Pair.first->second += NewScale;
2230           // The map already had an entry for this value, which may indicate
2231           // a folding opportunity.
2232           Interesting = true;
2233         }
2234       }
2235     } else {
2236       // An ordinary operand. Update the map.
2237       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2238           M.insert({Ops[i], Scale});
2239       if (Pair.second) {
2240         NewOps.push_back(Pair.first->first);
2241       } else {
2242         Pair.first->second += Scale;
2243         // The map already had an entry for this value, which may indicate
2244         // a folding opportunity.
2245         Interesting = true;
2246       }
2247     }
2248   }
2249 
2250   return Interesting;
2251 }
2252 
2253 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2254                                       const SCEV *LHS, const SCEV *RHS) {
2255   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2256                                             SCEV::NoWrapFlags, unsigned);
2257   switch (BinOp) {
2258   default:
2259     llvm_unreachable("Unsupported binary op");
2260   case Instruction::Add:
2261     Operation = &ScalarEvolution::getAddExpr;
2262     break;
2263   case Instruction::Sub:
2264     Operation = &ScalarEvolution::getMinusSCEV;
2265     break;
2266   case Instruction::Mul:
2267     Operation = &ScalarEvolution::getMulExpr;
2268     break;
2269   }
2270 
2271   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2272       Signed ? &ScalarEvolution::getSignExtendExpr
2273              : &ScalarEvolution::getZeroExtendExpr;
2274 
2275   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2276   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2277   auto *WideTy =
2278       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2279 
2280   const SCEV *A = (this->*Extension)(
2281       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2282   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2283                                      (this->*Extension)(RHS, WideTy, 0),
2284                                      SCEV::FlagAnyWrap, 0);
2285   return A == B;
2286 }
2287 
2288 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2289 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2290     const OverflowingBinaryOperator *OBO) {
2291   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2292 
2293   if (OBO->hasNoUnsignedWrap())
2294     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2295   if (OBO->hasNoSignedWrap())
2296     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2297 
2298   bool Deduced = false;
2299 
2300   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2301     return {Flags, Deduced};
2302 
2303   if (OBO->getOpcode() != Instruction::Add &&
2304       OBO->getOpcode() != Instruction::Sub &&
2305       OBO->getOpcode() != Instruction::Mul)
2306     return {Flags, Deduced};
2307 
2308   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2309   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2310 
2311   if (!OBO->hasNoUnsignedWrap() &&
2312       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2313                       /* Signed */ false, LHS, RHS)) {
2314     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2315     Deduced = true;
2316   }
2317 
2318   if (!OBO->hasNoSignedWrap() &&
2319       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2320                       /* Signed */ true, LHS, RHS)) {
2321     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2322     Deduced = true;
2323   }
2324 
2325   return {Flags, Deduced};
2326 }
2327 
2328 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2329 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2330 // can't-overflow flags for the operation if possible.
2331 static SCEV::NoWrapFlags
2332 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2333                       const ArrayRef<const SCEV *> Ops,
2334                       SCEV::NoWrapFlags Flags) {
2335   using namespace std::placeholders;
2336 
2337   using OBO = OverflowingBinaryOperator;
2338 
2339   bool CanAnalyze =
2340       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2341   (void)CanAnalyze;
2342   assert(CanAnalyze && "don't call from other places!");
2343 
2344   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2345   SCEV::NoWrapFlags SignOrUnsignWrap =
2346       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2347 
2348   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2349   auto IsKnownNonNegative = [&](const SCEV *S) {
2350     return SE->isKnownNonNegative(S);
2351   };
2352 
2353   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2354     Flags =
2355         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2356 
2357   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2358 
2359   if (SignOrUnsignWrap != SignOrUnsignMask &&
2360       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2361       isa<SCEVConstant>(Ops[0])) {
2362 
2363     auto Opcode = [&] {
2364       switch (Type) {
2365       case scAddExpr:
2366         return Instruction::Add;
2367       case scMulExpr:
2368         return Instruction::Mul;
2369       default:
2370         llvm_unreachable("Unexpected SCEV op.");
2371       }
2372     }();
2373 
2374     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2375 
2376     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2377     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2378       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2379           Opcode, C, OBO::NoSignedWrap);
2380       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2381         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2382     }
2383 
2384     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2385     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2386       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2387           Opcode, C, OBO::NoUnsignedWrap);
2388       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2389         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2390     }
2391   }
2392 
2393   return Flags;
2394 }
2395 
2396 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2397   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2398 }
2399 
2400 /// Get a canonical add expression, or something simpler if possible.
2401 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2402                                         SCEV::NoWrapFlags OrigFlags,
2403                                         unsigned Depth) {
2404   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2405          "only nuw or nsw allowed");
2406   assert(!Ops.empty() && "Cannot get empty add!");
2407   if (Ops.size() == 1) return Ops[0];
2408 #ifndef NDEBUG
2409   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2410   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2411     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2412            "SCEVAddExpr operand types don't match!");
2413 #endif
2414 
2415   // Sort by complexity, this groups all similar expression types together.
2416   GroupByComplexity(Ops, &LI, DT);
2417 
2418   // If there are any constants, fold them together.
2419   unsigned Idx = 0;
2420   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2421     ++Idx;
2422     assert(Idx < Ops.size());
2423     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2424       // We found two constants, fold them together!
2425       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2426       if (Ops.size() == 2) return Ops[0];
2427       Ops.erase(Ops.begin()+1);  // Erase the folded element
2428       LHSC = cast<SCEVConstant>(Ops[0]);
2429     }
2430 
2431     // If we are left with a constant zero being added, strip it off.
2432     if (LHSC->getValue()->isZero()) {
2433       Ops.erase(Ops.begin());
2434       --Idx;
2435     }
2436 
2437     if (Ops.size() == 1) return Ops[0];
2438   }
2439 
2440   // Delay expensive flag strengthening until necessary.
2441   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2442     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2443   };
2444 
2445   // Limit recursion calls depth.
2446   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2447     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2448 
2449   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2450     // Don't strengthen flags if we have no new information.
2451     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2452     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2453       Add->setNoWrapFlags(ComputeFlags(Ops));
2454     return S;
2455   }
2456 
2457   // Okay, check to see if the same value occurs in the operand list more than
2458   // once.  If so, merge them together into an multiply expression.  Since we
2459   // sorted the list, these values are required to be adjacent.
2460   Type *Ty = Ops[0]->getType();
2461   bool FoundMatch = false;
2462   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2463     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2464       // Scan ahead to count how many equal operands there are.
2465       unsigned Count = 2;
2466       while (i+Count != e && Ops[i+Count] == Ops[i])
2467         ++Count;
2468       // Merge the values into a multiply.
2469       const SCEV *Scale = getConstant(Ty, Count);
2470       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2471       if (Ops.size() == Count)
2472         return Mul;
2473       Ops[i] = Mul;
2474       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2475       --i; e -= Count - 1;
2476       FoundMatch = true;
2477     }
2478   if (FoundMatch)
2479     return getAddExpr(Ops, OrigFlags, Depth + 1);
2480 
2481   // Check for truncates. If all the operands are truncated from the same
2482   // type, see if factoring out the truncate would permit the result to be
2483   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2484   // if the contents of the resulting outer trunc fold to something simple.
2485   auto FindTruncSrcType = [&]() -> Type * {
2486     // We're ultimately looking to fold an addrec of truncs and muls of only
2487     // constants and truncs, so if we find any other types of SCEV
2488     // as operands of the addrec then we bail and return nullptr here.
2489     // Otherwise, we return the type of the operand of a trunc that we find.
2490     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2491       return T->getOperand()->getType();
2492     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2493       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2494       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2495         return T->getOperand()->getType();
2496     }
2497     return nullptr;
2498   };
2499   if (auto *SrcType = FindTruncSrcType()) {
2500     SmallVector<const SCEV *, 8> LargeOps;
2501     bool Ok = true;
2502     // Check all the operands to see if they can be represented in the
2503     // source type of the truncate.
2504     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2505       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2506         if (T->getOperand()->getType() != SrcType) {
2507           Ok = false;
2508           break;
2509         }
2510         LargeOps.push_back(T->getOperand());
2511       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2512         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2513       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2514         SmallVector<const SCEV *, 8> LargeMulOps;
2515         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2516           if (const SCEVTruncateExpr *T =
2517                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2518             if (T->getOperand()->getType() != SrcType) {
2519               Ok = false;
2520               break;
2521             }
2522             LargeMulOps.push_back(T->getOperand());
2523           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2524             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2525           } else {
2526             Ok = false;
2527             break;
2528           }
2529         }
2530         if (Ok)
2531           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2532       } else {
2533         Ok = false;
2534         break;
2535       }
2536     }
2537     if (Ok) {
2538       // Evaluate the expression in the larger type.
2539       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2540       // If it folds to something simple, use it. Otherwise, don't.
2541       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2542         return getTruncateExpr(Fold, Ty);
2543     }
2544   }
2545 
2546   if (Ops.size() == 2) {
2547     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2548     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2549     // C1).
2550     const SCEV *A = Ops[0];
2551     const SCEV *B = Ops[1];
2552     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2553     auto *C = dyn_cast<SCEVConstant>(A);
2554     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2555       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2556       auto C2 = C->getAPInt();
2557       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2558 
2559       APInt ConstAdd = C1 + C2;
2560       auto AddFlags = AddExpr->getNoWrapFlags();
2561       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2562       if (ScalarEvolution::maskFlags(AddFlags, SCEV::FlagNUW) ==
2563               SCEV::FlagNUW &&
2564           ConstAdd.ule(C1)) {
2565         PreservedFlags =
2566             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2567       }
2568 
2569       // Adding a constant with the same sign and small magnitude is NSW, if the
2570       // original AddExpr was NSW.
2571       if (ScalarEvolution::maskFlags(AddFlags, SCEV::FlagNSW) ==
2572               SCEV::FlagNSW &&
2573           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2574           ConstAdd.abs().ule(C1.abs())) {
2575         PreservedFlags =
2576             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2577       }
2578 
2579       if (PreservedFlags != SCEV::FlagAnyWrap) {
2580         SmallVector<const SCEV *, 4> NewOps(AddExpr->op_begin(),
2581                                             AddExpr->op_end());
2582         NewOps[0] = getConstant(ConstAdd);
2583         return getAddExpr(NewOps, PreservedFlags);
2584       }
2585     }
2586   }
2587 
2588   // Skip past any other cast SCEVs.
2589   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2590     ++Idx;
2591 
2592   // If there are add operands they would be next.
2593   if (Idx < Ops.size()) {
2594     bool DeletedAdd = false;
2595     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2596     // common NUW flag for expression after inlining. Other flags cannot be
2597     // preserved, because they may depend on the original order of operations.
2598     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2599     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2600       if (Ops.size() > AddOpsInlineThreshold ||
2601           Add->getNumOperands() > AddOpsInlineThreshold)
2602         break;
2603       // If we have an add, expand the add operands onto the end of the operands
2604       // list.
2605       Ops.erase(Ops.begin()+Idx);
2606       Ops.append(Add->op_begin(), Add->op_end());
2607       DeletedAdd = true;
2608       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2609     }
2610 
2611     // If we deleted at least one add, we added operands to the end of the list,
2612     // and they are not necessarily sorted.  Recurse to resort and resimplify
2613     // any operands we just acquired.
2614     if (DeletedAdd)
2615       return getAddExpr(Ops, CommonFlags, Depth + 1);
2616   }
2617 
2618   // Skip over the add expression until we get to a multiply.
2619   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2620     ++Idx;
2621 
2622   // Check to see if there are any folding opportunities present with
2623   // operands multiplied by constant values.
2624   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2625     uint64_t BitWidth = getTypeSizeInBits(Ty);
2626     DenseMap<const SCEV *, APInt> M;
2627     SmallVector<const SCEV *, 8> NewOps;
2628     APInt AccumulatedConstant(BitWidth, 0);
2629     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2630                                      Ops.data(), Ops.size(),
2631                                      APInt(BitWidth, 1), *this)) {
2632       struct APIntCompare {
2633         bool operator()(const APInt &LHS, const APInt &RHS) const {
2634           return LHS.ult(RHS);
2635         }
2636       };
2637 
2638       // Some interesting folding opportunity is present, so its worthwhile to
2639       // re-generate the operands list. Group the operands by constant scale,
2640       // to avoid multiplying by the same constant scale multiple times.
2641       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2642       for (const SCEV *NewOp : NewOps)
2643         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2644       // Re-generate the operands list.
2645       Ops.clear();
2646       if (AccumulatedConstant != 0)
2647         Ops.push_back(getConstant(AccumulatedConstant));
2648       for (auto &MulOp : MulOpLists)
2649         if (MulOp.first != 0)
2650           Ops.push_back(getMulExpr(
2651               getConstant(MulOp.first),
2652               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2653               SCEV::FlagAnyWrap, Depth + 1));
2654       if (Ops.empty())
2655         return getZero(Ty);
2656       if (Ops.size() == 1)
2657         return Ops[0];
2658       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2659     }
2660   }
2661 
2662   // If we are adding something to a multiply expression, make sure the
2663   // something is not already an operand of the multiply.  If so, merge it into
2664   // the multiply.
2665   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2666     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2667     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2668       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2669       if (isa<SCEVConstant>(MulOpSCEV))
2670         continue;
2671       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2672         if (MulOpSCEV == Ops[AddOp]) {
2673           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2674           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2675           if (Mul->getNumOperands() != 2) {
2676             // If the multiply has more than two operands, we must get the
2677             // Y*Z term.
2678             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2679                                                 Mul->op_begin()+MulOp);
2680             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2681             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2682           }
2683           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2684           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2685           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2686                                             SCEV::FlagAnyWrap, Depth + 1);
2687           if (Ops.size() == 2) return OuterMul;
2688           if (AddOp < Idx) {
2689             Ops.erase(Ops.begin()+AddOp);
2690             Ops.erase(Ops.begin()+Idx-1);
2691           } else {
2692             Ops.erase(Ops.begin()+Idx);
2693             Ops.erase(Ops.begin()+AddOp-1);
2694           }
2695           Ops.push_back(OuterMul);
2696           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2697         }
2698 
2699       // Check this multiply against other multiplies being added together.
2700       for (unsigned OtherMulIdx = Idx+1;
2701            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2702            ++OtherMulIdx) {
2703         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2704         // If MulOp occurs in OtherMul, we can fold the two multiplies
2705         // together.
2706         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2707              OMulOp != e; ++OMulOp)
2708           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2709             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2710             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2711             if (Mul->getNumOperands() != 2) {
2712               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2713                                                   Mul->op_begin()+MulOp);
2714               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2715               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2716             }
2717             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2718             if (OtherMul->getNumOperands() != 2) {
2719               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2720                                                   OtherMul->op_begin()+OMulOp);
2721               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2722               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2723             }
2724             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2725             const SCEV *InnerMulSum =
2726                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2727             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2728                                               SCEV::FlagAnyWrap, Depth + 1);
2729             if (Ops.size() == 2) return OuterMul;
2730             Ops.erase(Ops.begin()+Idx);
2731             Ops.erase(Ops.begin()+OtherMulIdx-1);
2732             Ops.push_back(OuterMul);
2733             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2734           }
2735       }
2736     }
2737   }
2738 
2739   // If there are any add recurrences in the operands list, see if any other
2740   // added values are loop invariant.  If so, we can fold them into the
2741   // recurrence.
2742   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2743     ++Idx;
2744 
2745   // Scan over all recurrences, trying to fold loop invariants into them.
2746   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2747     // Scan all of the other operands to this add and add them to the vector if
2748     // they are loop invariant w.r.t. the recurrence.
2749     SmallVector<const SCEV *, 8> LIOps;
2750     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2751     const Loop *AddRecLoop = AddRec->getLoop();
2752     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2753       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2754         LIOps.push_back(Ops[i]);
2755         Ops.erase(Ops.begin()+i);
2756         --i; --e;
2757       }
2758 
2759     // If we found some loop invariants, fold them into the recurrence.
2760     if (!LIOps.empty()) {
2761       // Compute nowrap flags for the addition of the loop-invariant ops and
2762       // the addrec. Temporarily push it as an operand for that purpose.
2763       LIOps.push_back(AddRec);
2764       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2765       LIOps.pop_back();
2766 
2767       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2768       LIOps.push_back(AddRec->getStart());
2769 
2770       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2771       // This follows from the fact that the no-wrap flags on the outer add
2772       // expression are applicable on the 0th iteration, when the add recurrence
2773       // will be equal to its start value.
2774       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2775 
2776       // Build the new addrec. Propagate the NUW and NSW flags if both the
2777       // outer add and the inner addrec are guaranteed to have no overflow.
2778       // Always propagate NW.
2779       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2780       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2781 
2782       // If all of the other operands were loop invariant, we are done.
2783       if (Ops.size() == 1) return NewRec;
2784 
2785       // Otherwise, add the folded AddRec by the non-invariant parts.
2786       for (unsigned i = 0;; ++i)
2787         if (Ops[i] == AddRec) {
2788           Ops[i] = NewRec;
2789           break;
2790         }
2791       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2792     }
2793 
2794     // Okay, if there weren't any loop invariants to be folded, check to see if
2795     // there are multiple AddRec's with the same loop induction variable being
2796     // added together.  If so, we can fold them.
2797     for (unsigned OtherIdx = Idx+1;
2798          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2799          ++OtherIdx) {
2800       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2801       // so that the 1st found AddRecExpr is dominated by all others.
2802       assert(DT.dominates(
2803            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2804            AddRec->getLoop()->getHeader()) &&
2805         "AddRecExprs are not sorted in reverse dominance order?");
2806       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2807         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2808         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2809         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2810              ++OtherIdx) {
2811           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2812           if (OtherAddRec->getLoop() == AddRecLoop) {
2813             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2814                  i != e; ++i) {
2815               if (i >= AddRecOps.size()) {
2816                 AddRecOps.append(OtherAddRec->op_begin()+i,
2817                                  OtherAddRec->op_end());
2818                 break;
2819               }
2820               SmallVector<const SCEV *, 2> TwoOps = {
2821                   AddRecOps[i], OtherAddRec->getOperand(i)};
2822               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2823             }
2824             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2825           }
2826         }
2827         // Step size has changed, so we cannot guarantee no self-wraparound.
2828         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2829         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2830       }
2831     }
2832 
2833     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2834     // next one.
2835   }
2836 
2837   // Okay, it looks like we really DO need an add expr.  Check to see if we
2838   // already have one, otherwise create a new one.
2839   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2840 }
2841 
2842 const SCEV *
2843 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2844                                     SCEV::NoWrapFlags Flags) {
2845   FoldingSetNodeID ID;
2846   ID.AddInteger(scAddExpr);
2847   for (const SCEV *Op : Ops)
2848     ID.AddPointer(Op);
2849   void *IP = nullptr;
2850   SCEVAddExpr *S =
2851       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2852   if (!S) {
2853     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2854     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2855     S = new (SCEVAllocator)
2856         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2857     UniqueSCEVs.InsertNode(S, IP);
2858     addToLoopUseLists(S);
2859   }
2860   S->setNoWrapFlags(Flags);
2861   return S;
2862 }
2863 
2864 const SCEV *
2865 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2866                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2867   FoldingSetNodeID ID;
2868   ID.AddInteger(scAddRecExpr);
2869   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2870     ID.AddPointer(Ops[i]);
2871   ID.AddPointer(L);
2872   void *IP = nullptr;
2873   SCEVAddRecExpr *S =
2874       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2875   if (!S) {
2876     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2877     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2878     S = new (SCEVAllocator)
2879         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2880     UniqueSCEVs.InsertNode(S, IP);
2881     addToLoopUseLists(S);
2882   }
2883   setNoWrapFlags(S, Flags);
2884   return S;
2885 }
2886 
2887 const SCEV *
2888 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2889                                     SCEV::NoWrapFlags Flags) {
2890   FoldingSetNodeID ID;
2891   ID.AddInteger(scMulExpr);
2892   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2893     ID.AddPointer(Ops[i]);
2894   void *IP = nullptr;
2895   SCEVMulExpr *S =
2896     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2897   if (!S) {
2898     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2899     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2900     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2901                                         O, Ops.size());
2902     UniqueSCEVs.InsertNode(S, IP);
2903     addToLoopUseLists(S);
2904   }
2905   S->setNoWrapFlags(Flags);
2906   return S;
2907 }
2908 
2909 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2910   uint64_t k = i*j;
2911   if (j > 1 && k / j != i) Overflow = true;
2912   return k;
2913 }
2914 
2915 /// Compute the result of "n choose k", the binomial coefficient.  If an
2916 /// intermediate computation overflows, Overflow will be set and the return will
2917 /// be garbage. Overflow is not cleared on absence of overflow.
2918 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2919   // We use the multiplicative formula:
2920   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2921   // At each iteration, we take the n-th term of the numeral and divide by the
2922   // (k-n)th term of the denominator.  This division will always produce an
2923   // integral result, and helps reduce the chance of overflow in the
2924   // intermediate computations. However, we can still overflow even when the
2925   // final result would fit.
2926 
2927   if (n == 0 || n == k) return 1;
2928   if (k > n) return 0;
2929 
2930   if (k > n/2)
2931     k = n-k;
2932 
2933   uint64_t r = 1;
2934   for (uint64_t i = 1; i <= k; ++i) {
2935     r = umul_ov(r, n-(i-1), Overflow);
2936     r /= i;
2937   }
2938   return r;
2939 }
2940 
2941 /// Determine if any of the operands in this SCEV are a constant or if
2942 /// any of the add or multiply expressions in this SCEV contain a constant.
2943 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2944   struct FindConstantInAddMulChain {
2945     bool FoundConstant = false;
2946 
2947     bool follow(const SCEV *S) {
2948       FoundConstant |= isa<SCEVConstant>(S);
2949       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2950     }
2951 
2952     bool isDone() const {
2953       return FoundConstant;
2954     }
2955   };
2956 
2957   FindConstantInAddMulChain F;
2958   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2959   ST.visitAll(StartExpr);
2960   return F.FoundConstant;
2961 }
2962 
2963 /// Get a canonical multiply expression, or something simpler if possible.
2964 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2965                                         SCEV::NoWrapFlags OrigFlags,
2966                                         unsigned Depth) {
2967   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2968          "only nuw or nsw allowed");
2969   assert(!Ops.empty() && "Cannot get empty mul!");
2970   if (Ops.size() == 1) return Ops[0];
2971 #ifndef NDEBUG
2972   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2973   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2974     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2975            "SCEVMulExpr operand types don't match!");
2976 #endif
2977 
2978   // Sort by complexity, this groups all similar expression types together.
2979   GroupByComplexity(Ops, &LI, DT);
2980 
2981   // If there are any constants, fold them together.
2982   unsigned Idx = 0;
2983   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2984     ++Idx;
2985     assert(Idx < Ops.size());
2986     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2987       // We found two constants, fold them together!
2988       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2989       if (Ops.size() == 2) return Ops[0];
2990       Ops.erase(Ops.begin()+1);  // Erase the folded element
2991       LHSC = cast<SCEVConstant>(Ops[0]);
2992     }
2993 
2994     // If we have a multiply of zero, it will always be zero.
2995     if (LHSC->getValue()->isZero())
2996       return LHSC;
2997 
2998     // If we are left with a constant one being multiplied, strip it off.
2999     if (LHSC->getValue()->isOne()) {
3000       Ops.erase(Ops.begin());
3001       --Idx;
3002     }
3003 
3004     if (Ops.size() == 1)
3005       return Ops[0];
3006   }
3007 
3008   // Delay expensive flag strengthening until necessary.
3009   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3010     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3011   };
3012 
3013   // Limit recursion calls depth.
3014   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3015     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3016 
3017   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
3018     // Don't strengthen flags if we have no new information.
3019     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3020     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3021       Mul->setNoWrapFlags(ComputeFlags(Ops));
3022     return S;
3023   }
3024 
3025   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3026     if (Ops.size() == 2) {
3027       // C1*(C2+V) -> C1*C2 + C1*V
3028       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3029         // If any of Add's ops are Adds or Muls with a constant, apply this
3030         // transformation as well.
3031         //
3032         // TODO: There are some cases where this transformation is not
3033         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3034         // this transformation should be narrowed down.
3035         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
3036           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
3037                                        SCEV::FlagAnyWrap, Depth + 1),
3038                             getMulExpr(LHSC, Add->getOperand(1),
3039                                        SCEV::FlagAnyWrap, Depth + 1),
3040                             SCEV::FlagAnyWrap, Depth + 1);
3041 
3042       if (Ops[0]->isAllOnesValue()) {
3043         // If we have a mul by -1 of an add, try distributing the -1 among the
3044         // add operands.
3045         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3046           SmallVector<const SCEV *, 4> NewOps;
3047           bool AnyFolded = false;
3048           for (const SCEV *AddOp : Add->operands()) {
3049             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3050                                          Depth + 1);
3051             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3052             NewOps.push_back(Mul);
3053           }
3054           if (AnyFolded)
3055             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3056         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3057           // Negation preserves a recurrence's no self-wrap property.
3058           SmallVector<const SCEV *, 4> Operands;
3059           for (const SCEV *AddRecOp : AddRec->operands())
3060             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3061                                           Depth + 1));
3062 
3063           return getAddRecExpr(Operands, AddRec->getLoop(),
3064                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3065         }
3066       }
3067     }
3068   }
3069 
3070   // Skip over the add expression until we get to a multiply.
3071   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3072     ++Idx;
3073 
3074   // If there are mul operands inline them all into this expression.
3075   if (Idx < Ops.size()) {
3076     bool DeletedMul = false;
3077     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3078       if (Ops.size() > MulOpsInlineThreshold)
3079         break;
3080       // If we have an mul, expand the mul operands onto the end of the
3081       // operands list.
3082       Ops.erase(Ops.begin()+Idx);
3083       Ops.append(Mul->op_begin(), Mul->op_end());
3084       DeletedMul = true;
3085     }
3086 
3087     // If we deleted at least one mul, we added operands to the end of the
3088     // list, and they are not necessarily sorted.  Recurse to resort and
3089     // resimplify any operands we just acquired.
3090     if (DeletedMul)
3091       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3092   }
3093 
3094   // If there are any add recurrences in the operands list, see if any other
3095   // added values are loop invariant.  If so, we can fold them into the
3096   // recurrence.
3097   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3098     ++Idx;
3099 
3100   // Scan over all recurrences, trying to fold loop invariants into them.
3101   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3102     // Scan all of the other operands to this mul and add them to the vector
3103     // if they are loop invariant w.r.t. the recurrence.
3104     SmallVector<const SCEV *, 8> LIOps;
3105     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3106     const Loop *AddRecLoop = AddRec->getLoop();
3107     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3108       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3109         LIOps.push_back(Ops[i]);
3110         Ops.erase(Ops.begin()+i);
3111         --i; --e;
3112       }
3113 
3114     // If we found some loop invariants, fold them into the recurrence.
3115     if (!LIOps.empty()) {
3116       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3117       SmallVector<const SCEV *, 4> NewOps;
3118       NewOps.reserve(AddRec->getNumOperands());
3119       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3120       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3121         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3122                                     SCEV::FlagAnyWrap, Depth + 1));
3123 
3124       // Build the new addrec. Propagate the NUW and NSW flags if both the
3125       // outer mul and the inner addrec are guaranteed to have no overflow.
3126       //
3127       // No self-wrap cannot be guaranteed after changing the step size, but
3128       // will be inferred if either NUW or NSW is true.
3129       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3130       const SCEV *NewRec = getAddRecExpr(
3131           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3132 
3133       // If all of the other operands were loop invariant, we are done.
3134       if (Ops.size() == 1) return NewRec;
3135 
3136       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3137       for (unsigned i = 0;; ++i)
3138         if (Ops[i] == AddRec) {
3139           Ops[i] = NewRec;
3140           break;
3141         }
3142       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3143     }
3144 
3145     // Okay, if there weren't any loop invariants to be folded, check to see
3146     // if there are multiple AddRec's with the same loop induction variable
3147     // being multiplied together.  If so, we can fold them.
3148 
3149     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3150     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3151     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3152     //   ]]],+,...up to x=2n}.
3153     // Note that the arguments to choose() are always integers with values
3154     // known at compile time, never SCEV objects.
3155     //
3156     // The implementation avoids pointless extra computations when the two
3157     // addrec's are of different length (mathematically, it's equivalent to
3158     // an infinite stream of zeros on the right).
3159     bool OpsModified = false;
3160     for (unsigned OtherIdx = Idx+1;
3161          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3162          ++OtherIdx) {
3163       const SCEVAddRecExpr *OtherAddRec =
3164         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3165       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3166         continue;
3167 
3168       // Limit max number of arguments to avoid creation of unreasonably big
3169       // SCEVAddRecs with very complex operands.
3170       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3171           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3172         continue;
3173 
3174       bool Overflow = false;
3175       Type *Ty = AddRec->getType();
3176       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3177       SmallVector<const SCEV*, 7> AddRecOps;
3178       for (int x = 0, xe = AddRec->getNumOperands() +
3179              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3180         SmallVector <const SCEV *, 7> SumOps;
3181         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3182           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3183           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3184                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3185                z < ze && !Overflow; ++z) {
3186             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3187             uint64_t Coeff;
3188             if (LargerThan64Bits)
3189               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3190             else
3191               Coeff = Coeff1*Coeff2;
3192             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3193             const SCEV *Term1 = AddRec->getOperand(y-z);
3194             const SCEV *Term2 = OtherAddRec->getOperand(z);
3195             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3196                                         SCEV::FlagAnyWrap, Depth + 1));
3197           }
3198         }
3199         if (SumOps.empty())
3200           SumOps.push_back(getZero(Ty));
3201         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3202       }
3203       if (!Overflow) {
3204         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3205                                               SCEV::FlagAnyWrap);
3206         if (Ops.size() == 2) return NewAddRec;
3207         Ops[Idx] = NewAddRec;
3208         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3209         OpsModified = true;
3210         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3211         if (!AddRec)
3212           break;
3213       }
3214     }
3215     if (OpsModified)
3216       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3217 
3218     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3219     // next one.
3220   }
3221 
3222   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3223   // already have one, otherwise create a new one.
3224   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3225 }
3226 
3227 /// Represents an unsigned remainder expression based on unsigned division.
3228 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3229                                          const SCEV *RHS) {
3230   assert(getEffectiveSCEVType(LHS->getType()) ==
3231          getEffectiveSCEVType(RHS->getType()) &&
3232          "SCEVURemExpr operand types don't match!");
3233 
3234   // Short-circuit easy cases
3235   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3236     // If constant is one, the result is trivial
3237     if (RHSC->getValue()->isOne())
3238       return getZero(LHS->getType()); // X urem 1 --> 0
3239 
3240     // If constant is a power of two, fold into a zext(trunc(LHS)).
3241     if (RHSC->getAPInt().isPowerOf2()) {
3242       Type *FullTy = LHS->getType();
3243       Type *TruncTy =
3244           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3245       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3246     }
3247   }
3248 
3249   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3250   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3251   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3252   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3253 }
3254 
3255 /// Get a canonical unsigned division expression, or something simpler if
3256 /// possible.
3257 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3258                                          const SCEV *RHS) {
3259   assert(getEffectiveSCEVType(LHS->getType()) ==
3260          getEffectiveSCEVType(RHS->getType()) &&
3261          "SCEVUDivExpr operand types don't match!");
3262 
3263   FoldingSetNodeID ID;
3264   ID.AddInteger(scUDivExpr);
3265   ID.AddPointer(LHS);
3266   ID.AddPointer(RHS);
3267   void *IP = nullptr;
3268   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3269     return S;
3270 
3271   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3272     if (RHSC->getValue()->isOne())
3273       return LHS;                               // X udiv 1 --> x
3274     // If the denominator is zero, the result of the udiv is undefined. Don't
3275     // try to analyze it, because the resolution chosen here may differ from
3276     // the resolution chosen in other parts of the compiler.
3277     if (!RHSC->getValue()->isZero()) {
3278       // Determine if the division can be folded into the operands of
3279       // its operands.
3280       // TODO: Generalize this to non-constants by using known-bits information.
3281       Type *Ty = LHS->getType();
3282       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3283       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3284       // For non-power-of-two values, effectively round the value up to the
3285       // nearest power of two.
3286       if (!RHSC->getAPInt().isPowerOf2())
3287         ++MaxShiftAmt;
3288       IntegerType *ExtTy =
3289         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3290       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3291         if (const SCEVConstant *Step =
3292             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3293           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3294           const APInt &StepInt = Step->getAPInt();
3295           const APInt &DivInt = RHSC->getAPInt();
3296           if (!StepInt.urem(DivInt) &&
3297               getZeroExtendExpr(AR, ExtTy) ==
3298               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3299                             getZeroExtendExpr(Step, ExtTy),
3300                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3301             SmallVector<const SCEV *, 4> Operands;
3302             for (const SCEV *Op : AR->operands())
3303               Operands.push_back(getUDivExpr(Op, RHS));
3304             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3305           }
3306           /// Get a canonical UDivExpr for a recurrence.
3307           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3308           // We can currently only fold X%N if X is constant.
3309           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3310           if (StartC && !DivInt.urem(StepInt) &&
3311               getZeroExtendExpr(AR, ExtTy) ==
3312               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3313                             getZeroExtendExpr(Step, ExtTy),
3314                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3315             const APInt &StartInt = StartC->getAPInt();
3316             const APInt &StartRem = StartInt.urem(StepInt);
3317             if (StartRem != 0) {
3318               const SCEV *NewLHS =
3319                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3320                                 AR->getLoop(), SCEV::FlagNW);
3321               if (LHS != NewLHS) {
3322                 LHS = NewLHS;
3323 
3324                 // Reset the ID to include the new LHS, and check if it is
3325                 // already cached.
3326                 ID.clear();
3327                 ID.AddInteger(scUDivExpr);
3328                 ID.AddPointer(LHS);
3329                 ID.AddPointer(RHS);
3330                 IP = nullptr;
3331                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3332                   return S;
3333               }
3334             }
3335           }
3336         }
3337       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3338       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3339         SmallVector<const SCEV *, 4> Operands;
3340         for (const SCEV *Op : M->operands())
3341           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3342         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3343           // Find an operand that's safely divisible.
3344           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3345             const SCEV *Op = M->getOperand(i);
3346             const SCEV *Div = getUDivExpr(Op, RHSC);
3347             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3348               Operands = SmallVector<const SCEV *, 4>(M->operands());
3349               Operands[i] = Div;
3350               return getMulExpr(Operands);
3351             }
3352           }
3353       }
3354 
3355       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3356       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3357         if (auto *DivisorConstant =
3358                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3359           bool Overflow = false;
3360           APInt NewRHS =
3361               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3362           if (Overflow) {
3363             return getConstant(RHSC->getType(), 0, false);
3364           }
3365           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3366         }
3367       }
3368 
3369       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3370       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3371         SmallVector<const SCEV *, 4> Operands;
3372         for (const SCEV *Op : A->operands())
3373           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3374         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3375           Operands.clear();
3376           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3377             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3378             if (isa<SCEVUDivExpr>(Op) ||
3379                 getMulExpr(Op, RHS) != A->getOperand(i))
3380               break;
3381             Operands.push_back(Op);
3382           }
3383           if (Operands.size() == A->getNumOperands())
3384             return getAddExpr(Operands);
3385         }
3386       }
3387 
3388       // Fold if both operands are constant.
3389       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3390         Constant *LHSCV = LHSC->getValue();
3391         Constant *RHSCV = RHSC->getValue();
3392         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3393                                                                    RHSCV)));
3394       }
3395     }
3396   }
3397 
3398   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3399   // changes). Make sure we get a new one.
3400   IP = nullptr;
3401   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3402   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3403                                              LHS, RHS);
3404   UniqueSCEVs.InsertNode(S, IP);
3405   addToLoopUseLists(S);
3406   return S;
3407 }
3408 
3409 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3410   APInt A = C1->getAPInt().abs();
3411   APInt B = C2->getAPInt().abs();
3412   uint32_t ABW = A.getBitWidth();
3413   uint32_t BBW = B.getBitWidth();
3414 
3415   if (ABW > BBW)
3416     B = B.zext(ABW);
3417   else if (ABW < BBW)
3418     A = A.zext(BBW);
3419 
3420   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3421 }
3422 
3423 /// Get a canonical unsigned division expression, or something simpler if
3424 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3425 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3426 /// it's not exact because the udiv may be clearing bits.
3427 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3428                                               const SCEV *RHS) {
3429   // TODO: we could try to find factors in all sorts of things, but for now we
3430   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3431   // end of this file for inspiration.
3432 
3433   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3434   if (!Mul || !Mul->hasNoUnsignedWrap())
3435     return getUDivExpr(LHS, RHS);
3436 
3437   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3438     // If the mulexpr multiplies by a constant, then that constant must be the
3439     // first element of the mulexpr.
3440     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3441       if (LHSCst == RHSCst) {
3442         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3443         return getMulExpr(Operands);
3444       }
3445 
3446       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3447       // that there's a factor provided by one of the other terms. We need to
3448       // check.
3449       APInt Factor = gcd(LHSCst, RHSCst);
3450       if (!Factor.isIntN(1)) {
3451         LHSCst =
3452             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3453         RHSCst =
3454             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3455         SmallVector<const SCEV *, 2> Operands;
3456         Operands.push_back(LHSCst);
3457         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3458         LHS = getMulExpr(Operands);
3459         RHS = RHSCst;
3460         Mul = dyn_cast<SCEVMulExpr>(LHS);
3461         if (!Mul)
3462           return getUDivExactExpr(LHS, RHS);
3463       }
3464     }
3465   }
3466 
3467   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3468     if (Mul->getOperand(i) == RHS) {
3469       SmallVector<const SCEV *, 2> Operands;
3470       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3471       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3472       return getMulExpr(Operands);
3473     }
3474   }
3475 
3476   return getUDivExpr(LHS, RHS);
3477 }
3478 
3479 /// Get an add recurrence expression for the specified loop.  Simplify the
3480 /// expression as much as possible.
3481 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3482                                            const Loop *L,
3483                                            SCEV::NoWrapFlags Flags) {
3484   SmallVector<const SCEV *, 4> Operands;
3485   Operands.push_back(Start);
3486   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3487     if (StepChrec->getLoop() == L) {
3488       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3489       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3490     }
3491 
3492   Operands.push_back(Step);
3493   return getAddRecExpr(Operands, L, Flags);
3494 }
3495 
3496 /// Get an add recurrence expression for the specified loop.  Simplify the
3497 /// expression as much as possible.
3498 const SCEV *
3499 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3500                                const Loop *L, SCEV::NoWrapFlags Flags) {
3501   if (Operands.size() == 1) return Operands[0];
3502 #ifndef NDEBUG
3503   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3504   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3505     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3506            "SCEVAddRecExpr operand types don't match!");
3507   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3508     assert(isLoopInvariant(Operands[i], L) &&
3509            "SCEVAddRecExpr operand is not loop-invariant!");
3510 #endif
3511 
3512   if (Operands.back()->isZero()) {
3513     Operands.pop_back();
3514     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3515   }
3516 
3517   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3518   // use that information to infer NUW and NSW flags. However, computing a
3519   // BE count requires calling getAddRecExpr, so we may not yet have a
3520   // meaningful BE count at this point (and if we don't, we'd be stuck
3521   // with a SCEVCouldNotCompute as the cached BE count).
3522 
3523   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3524 
3525   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3526   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3527     const Loop *NestedLoop = NestedAR->getLoop();
3528     if (L->contains(NestedLoop)
3529             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3530             : (!NestedLoop->contains(L) &&
3531                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3532       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3533       Operands[0] = NestedAR->getStart();
3534       // AddRecs require their operands be loop-invariant with respect to their
3535       // loops. Don't perform this transformation if it would break this
3536       // requirement.
3537       bool AllInvariant = all_of(
3538           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3539 
3540       if (AllInvariant) {
3541         // Create a recurrence for the outer loop with the same step size.
3542         //
3543         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3544         // inner recurrence has the same property.
3545         SCEV::NoWrapFlags OuterFlags =
3546           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3547 
3548         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3549         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3550           return isLoopInvariant(Op, NestedLoop);
3551         });
3552 
3553         if (AllInvariant) {
3554           // Ok, both add recurrences are valid after the transformation.
3555           //
3556           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3557           // the outer recurrence has the same property.
3558           SCEV::NoWrapFlags InnerFlags =
3559             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3560           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3561         }
3562       }
3563       // Reset Operands to its original state.
3564       Operands[0] = NestedAR;
3565     }
3566   }
3567 
3568   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3569   // already have one, otherwise create a new one.
3570   return getOrCreateAddRecExpr(Operands, L, Flags);
3571 }
3572 
3573 const SCEV *
3574 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3575                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3576   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3577   // getSCEV(Base)->getType() has the same address space as Base->getType()
3578   // because SCEV::getType() preserves the address space.
3579   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3580   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3581   // instruction to its SCEV, because the Instruction may be guarded by control
3582   // flow and the no-overflow bits may not be valid for the expression in any
3583   // context. This can be fixed similarly to how these flags are handled for
3584   // adds.
3585   SCEV::NoWrapFlags OffsetWrap =
3586       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3587 
3588   Type *CurTy = GEP->getType();
3589   bool FirstIter = true;
3590   SmallVector<const SCEV *, 4> Offsets;
3591   for (const SCEV *IndexExpr : IndexExprs) {
3592     // Compute the (potentially symbolic) offset in bytes for this index.
3593     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3594       // For a struct, add the member offset.
3595       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3596       unsigned FieldNo = Index->getZExtValue();
3597       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3598       Offsets.push_back(FieldOffset);
3599 
3600       // Update CurTy to the type of the field at Index.
3601       CurTy = STy->getTypeAtIndex(Index);
3602     } else {
3603       // Update CurTy to its element type.
3604       if (FirstIter) {
3605         assert(isa<PointerType>(CurTy) &&
3606                "The first index of a GEP indexes a pointer");
3607         CurTy = GEP->getSourceElementType();
3608         FirstIter = false;
3609       } else {
3610         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3611       }
3612       // For an array, add the element offset, explicitly scaled.
3613       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3614       // Getelementptr indices are signed.
3615       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3616 
3617       // Multiply the index by the element size to compute the element offset.
3618       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3619       Offsets.push_back(LocalOffset);
3620     }
3621   }
3622 
3623   // Handle degenerate case of GEP without offsets.
3624   if (Offsets.empty())
3625     return BaseExpr;
3626 
3627   // Add the offsets together, assuming nsw if inbounds.
3628   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3629   // Add the base address and the offset. We cannot use the nsw flag, as the
3630   // base address is unsigned. However, if we know that the offset is
3631   // non-negative, we can use nuw.
3632   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3633                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3634   return getAddExpr(BaseExpr, Offset, BaseWrap);
3635 }
3636 
3637 std::tuple<SCEV *, FoldingSetNodeID, void *>
3638 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3639                                          ArrayRef<const SCEV *> Ops) {
3640   FoldingSetNodeID ID;
3641   void *IP = nullptr;
3642   ID.AddInteger(SCEVType);
3643   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3644     ID.AddPointer(Ops[i]);
3645   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3646       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3647 }
3648 
3649 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3650   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3651   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3652 }
3653 
3654 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3655                                            SmallVectorImpl<const SCEV *> &Ops) {
3656   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3657   if (Ops.size() == 1) return Ops[0];
3658 #ifndef NDEBUG
3659   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3660   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3661     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3662            "Operand types don't match!");
3663 #endif
3664 
3665   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3666   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3667 
3668   // Sort by complexity, this groups all similar expression types together.
3669   GroupByComplexity(Ops, &LI, DT);
3670 
3671   // Check if we have created the same expression before.
3672   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3673     return S;
3674   }
3675 
3676   // If there are any constants, fold them together.
3677   unsigned Idx = 0;
3678   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3679     ++Idx;
3680     assert(Idx < Ops.size());
3681     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3682       if (Kind == scSMaxExpr)
3683         return APIntOps::smax(LHS, RHS);
3684       else if (Kind == scSMinExpr)
3685         return APIntOps::smin(LHS, RHS);
3686       else if (Kind == scUMaxExpr)
3687         return APIntOps::umax(LHS, RHS);
3688       else if (Kind == scUMinExpr)
3689         return APIntOps::umin(LHS, RHS);
3690       llvm_unreachable("Unknown SCEV min/max opcode");
3691     };
3692 
3693     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3694       // We found two constants, fold them together!
3695       ConstantInt *Fold = ConstantInt::get(
3696           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3697       Ops[0] = getConstant(Fold);
3698       Ops.erase(Ops.begin()+1);  // Erase the folded element
3699       if (Ops.size() == 1) return Ops[0];
3700       LHSC = cast<SCEVConstant>(Ops[0]);
3701     }
3702 
3703     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3704     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3705 
3706     if (IsMax ? IsMinV : IsMaxV) {
3707       // If we are left with a constant minimum(/maximum)-int, strip it off.
3708       Ops.erase(Ops.begin());
3709       --Idx;
3710     } else if (IsMax ? IsMaxV : IsMinV) {
3711       // If we have a max(/min) with a constant maximum(/minimum)-int,
3712       // it will always be the extremum.
3713       return LHSC;
3714     }
3715 
3716     if (Ops.size() == 1) return Ops[0];
3717   }
3718 
3719   // Find the first operation of the same kind
3720   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3721     ++Idx;
3722 
3723   // Check to see if one of the operands is of the same kind. If so, expand its
3724   // operands onto our operand list, and recurse to simplify.
3725   if (Idx < Ops.size()) {
3726     bool DeletedAny = false;
3727     while (Ops[Idx]->getSCEVType() == Kind) {
3728       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3729       Ops.erase(Ops.begin()+Idx);
3730       Ops.append(SMME->op_begin(), SMME->op_end());
3731       DeletedAny = true;
3732     }
3733 
3734     if (DeletedAny)
3735       return getMinMaxExpr(Kind, Ops);
3736   }
3737 
3738   // Okay, check to see if the same value occurs in the operand list twice.  If
3739   // so, delete one.  Since we sorted the list, these values are required to
3740   // be adjacent.
3741   llvm::CmpInst::Predicate GEPred =
3742       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3743   llvm::CmpInst::Predicate LEPred =
3744       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3745   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3746   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3747   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3748     if (Ops[i] == Ops[i + 1] ||
3749         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3750       //  X op Y op Y  -->  X op Y
3751       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3752       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3753       --i;
3754       --e;
3755     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3756                                                Ops[i + 1])) {
3757       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3758       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3759       --i;
3760       --e;
3761     }
3762   }
3763 
3764   if (Ops.size() == 1) return Ops[0];
3765 
3766   assert(!Ops.empty() && "Reduced smax down to nothing!");
3767 
3768   // Okay, it looks like we really DO need an expr.  Check to see if we
3769   // already have one, otherwise create a new one.
3770   const SCEV *ExistingSCEV;
3771   FoldingSetNodeID ID;
3772   void *IP;
3773   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3774   if (ExistingSCEV)
3775     return ExistingSCEV;
3776   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3777   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3778   SCEV *S = new (SCEVAllocator)
3779       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3780 
3781   UniqueSCEVs.InsertNode(S, IP);
3782   addToLoopUseLists(S);
3783   return S;
3784 }
3785 
3786 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3787   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3788   return getSMaxExpr(Ops);
3789 }
3790 
3791 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3792   return getMinMaxExpr(scSMaxExpr, Ops);
3793 }
3794 
3795 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3796   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3797   return getUMaxExpr(Ops);
3798 }
3799 
3800 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3801   return getMinMaxExpr(scUMaxExpr, Ops);
3802 }
3803 
3804 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3805                                          const SCEV *RHS) {
3806   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3807   return getSMinExpr(Ops);
3808 }
3809 
3810 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3811   return getMinMaxExpr(scSMinExpr, Ops);
3812 }
3813 
3814 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3815                                          const SCEV *RHS) {
3816   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3817   return getUMinExpr(Ops);
3818 }
3819 
3820 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3821   return getMinMaxExpr(scUMinExpr, Ops);
3822 }
3823 
3824 const SCEV *
3825 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3826                                              ScalableVectorType *ScalableTy) {
3827   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3828   Constant *One = ConstantInt::get(IntTy, 1);
3829   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3830   // Note that the expression we created is the final expression, we don't
3831   // want to simplify it any further Also, if we call a normal getSCEV(),
3832   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3833   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3834 }
3835 
3836 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3837   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3838     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3839   // We can bypass creating a target-independent constant expression and then
3840   // folding it back into a ConstantInt. This is just a compile-time
3841   // optimization.
3842   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3843 }
3844 
3845 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3846   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3847     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3848   // We can bypass creating a target-independent constant expression and then
3849   // folding it back into a ConstantInt. This is just a compile-time
3850   // optimization.
3851   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3852 }
3853 
3854 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3855                                              StructType *STy,
3856                                              unsigned FieldNo) {
3857   // We can bypass creating a target-independent constant expression and then
3858   // folding it back into a ConstantInt. This is just a compile-time
3859   // optimization.
3860   return getConstant(
3861       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3862 }
3863 
3864 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3865   // Don't attempt to do anything other than create a SCEVUnknown object
3866   // here.  createSCEV only calls getUnknown after checking for all other
3867   // interesting possibilities, and any other code that calls getUnknown
3868   // is doing so in order to hide a value from SCEV canonicalization.
3869 
3870   FoldingSetNodeID ID;
3871   ID.AddInteger(scUnknown);
3872   ID.AddPointer(V);
3873   void *IP = nullptr;
3874   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3875     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3876            "Stale SCEVUnknown in uniquing map!");
3877     return S;
3878   }
3879   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3880                                             FirstUnknown);
3881   FirstUnknown = cast<SCEVUnknown>(S);
3882   UniqueSCEVs.InsertNode(S, IP);
3883   return S;
3884 }
3885 
3886 //===----------------------------------------------------------------------===//
3887 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3888 //
3889 
3890 /// Test if values of the given type are analyzable within the SCEV
3891 /// framework. This primarily includes integer types, and it can optionally
3892 /// include pointer types if the ScalarEvolution class has access to
3893 /// target-specific information.
3894 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3895   // Integers and pointers are always SCEVable.
3896   return Ty->isIntOrPtrTy();
3897 }
3898 
3899 /// Return the size in bits of the specified type, for which isSCEVable must
3900 /// return true.
3901 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3902   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3903   if (Ty->isPointerTy())
3904     return getDataLayout().getIndexTypeSizeInBits(Ty);
3905   return getDataLayout().getTypeSizeInBits(Ty);
3906 }
3907 
3908 /// Return a type with the same bitwidth as the given type and which represents
3909 /// how SCEV will treat the given type, for which isSCEVable must return
3910 /// true. For pointer types, this is the pointer index sized integer type.
3911 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3912   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3913 
3914   if (Ty->isIntegerTy())
3915     return Ty;
3916 
3917   // The only other support type is pointer.
3918   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3919   return getDataLayout().getIndexType(Ty);
3920 }
3921 
3922 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3923   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3924 }
3925 
3926 const SCEV *ScalarEvolution::getCouldNotCompute() {
3927   return CouldNotCompute.get();
3928 }
3929 
3930 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3931   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3932     auto *SU = dyn_cast<SCEVUnknown>(S);
3933     return SU && SU->getValue() == nullptr;
3934   });
3935 
3936   return !ContainsNulls;
3937 }
3938 
3939 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3940   HasRecMapType::iterator I = HasRecMap.find(S);
3941   if (I != HasRecMap.end())
3942     return I->second;
3943 
3944   bool FoundAddRec =
3945       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3946   HasRecMap.insert({S, FoundAddRec});
3947   return FoundAddRec;
3948 }
3949 
3950 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3951 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3952 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3953 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3954   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3955   if (!Add)
3956     return {S, nullptr};
3957 
3958   if (Add->getNumOperands() != 2)
3959     return {S, nullptr};
3960 
3961   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3962   if (!ConstOp)
3963     return {S, nullptr};
3964 
3965   return {Add->getOperand(1), ConstOp->getValue()};
3966 }
3967 
3968 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3969 /// by the value and offset from any ValueOffsetPair in the set.
3970 ScalarEvolution::ValueOffsetPairSetVector *
3971 ScalarEvolution::getSCEVValues(const SCEV *S) {
3972   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3973   if (SI == ExprValueMap.end())
3974     return nullptr;
3975 #ifndef NDEBUG
3976   if (VerifySCEVMap) {
3977     // Check there is no dangling Value in the set returned.
3978     for (const auto &VE : SI->second)
3979       assert(ValueExprMap.count(VE.first));
3980   }
3981 #endif
3982   return &SI->second;
3983 }
3984 
3985 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3986 /// cannot be used separately. eraseValueFromMap should be used to remove
3987 /// V from ValueExprMap and ExprValueMap at the same time.
3988 void ScalarEvolution::eraseValueFromMap(Value *V) {
3989   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3990   if (I != ValueExprMap.end()) {
3991     const SCEV *S = I->second;
3992     // Remove {V, 0} from the set of ExprValueMap[S]
3993     if (auto *SV = getSCEVValues(S))
3994       SV->remove({V, nullptr});
3995 
3996     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3997     const SCEV *Stripped;
3998     ConstantInt *Offset;
3999     std::tie(Stripped, Offset) = splitAddExpr(S);
4000     if (Offset != nullptr) {
4001       if (auto *SV = getSCEVValues(Stripped))
4002         SV->remove({V, Offset});
4003     }
4004     ValueExprMap.erase(V);
4005   }
4006 }
4007 
4008 /// Check whether value has nuw/nsw/exact set but SCEV does not.
4009 /// TODO: In reality it is better to check the poison recursively
4010 /// but this is better than nothing.
4011 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
4012   if (auto *I = dyn_cast<Instruction>(V)) {
4013     if (isa<OverflowingBinaryOperator>(I)) {
4014       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
4015         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
4016           return true;
4017         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
4018           return true;
4019       }
4020     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
4021       return true;
4022   }
4023   return false;
4024 }
4025 
4026 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4027 /// create a new one.
4028 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4029   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4030 
4031   const SCEV *S = getExistingSCEV(V);
4032   if (S == nullptr) {
4033     S = createSCEV(V);
4034     // During PHI resolution, it is possible to create two SCEVs for the same
4035     // V, so it is needed to double check whether V->S is inserted into
4036     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4037     std::pair<ValueExprMapType::iterator, bool> Pair =
4038         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4039     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
4040       ExprValueMap[S].insert({V, nullptr});
4041 
4042       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
4043       // ExprValueMap.
4044       const SCEV *Stripped = S;
4045       ConstantInt *Offset = nullptr;
4046       std::tie(Stripped, Offset) = splitAddExpr(S);
4047       // If stripped is SCEVUnknown, don't bother to save
4048       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
4049       // increase the complexity of the expansion code.
4050       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
4051       // because it may generate add/sub instead of GEP in SCEV expansion.
4052       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
4053           !isa<GetElementPtrInst>(V))
4054         ExprValueMap[Stripped].insert({V, Offset});
4055     }
4056   }
4057   return S;
4058 }
4059 
4060 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4061   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4062 
4063   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4064   if (I != ValueExprMap.end()) {
4065     const SCEV *S = I->second;
4066     if (checkValidity(S))
4067       return S;
4068     eraseValueFromMap(V);
4069     forgetMemoizedResults(S);
4070   }
4071   return nullptr;
4072 }
4073 
4074 /// Return a SCEV corresponding to -V = -1*V
4075 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4076                                              SCEV::NoWrapFlags Flags) {
4077   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4078     return getConstant(
4079                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4080 
4081   Type *Ty = V->getType();
4082   Ty = getEffectiveSCEVType(Ty);
4083   return getMulExpr(V, getMinusOne(Ty), Flags);
4084 }
4085 
4086 /// If Expr computes ~A, return A else return nullptr
4087 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4088   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4089   if (!Add || Add->getNumOperands() != 2 ||
4090       !Add->getOperand(0)->isAllOnesValue())
4091     return nullptr;
4092 
4093   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4094   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4095       !AddRHS->getOperand(0)->isAllOnesValue())
4096     return nullptr;
4097 
4098   return AddRHS->getOperand(1);
4099 }
4100 
4101 /// Return a SCEV corresponding to ~V = -1-V
4102 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4103   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4104     return getConstant(
4105                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4106 
4107   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4108   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4109     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4110       SmallVector<const SCEV *, 2> MatchedOperands;
4111       for (const SCEV *Operand : MME->operands()) {
4112         const SCEV *Matched = MatchNotExpr(Operand);
4113         if (!Matched)
4114           return (const SCEV *)nullptr;
4115         MatchedOperands.push_back(Matched);
4116       }
4117       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4118                            MatchedOperands);
4119     };
4120     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4121       return Replaced;
4122   }
4123 
4124   Type *Ty = V->getType();
4125   Ty = getEffectiveSCEVType(Ty);
4126   return getMinusSCEV(getMinusOne(Ty), V);
4127 }
4128 
4129 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4130                                           SCEV::NoWrapFlags Flags,
4131                                           unsigned Depth) {
4132   // Fast path: X - X --> 0.
4133   if (LHS == RHS)
4134     return getZero(LHS->getType());
4135 
4136   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4137   // makes it so that we cannot make much use of NUW.
4138   auto AddFlags = SCEV::FlagAnyWrap;
4139   const bool RHSIsNotMinSigned =
4140       !getSignedRangeMin(RHS).isMinSignedValue();
4141   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4142     // Let M be the minimum representable signed value. Then (-1)*RHS
4143     // signed-wraps if and only if RHS is M. That can happen even for
4144     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4145     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4146     // (-1)*RHS, we need to prove that RHS != M.
4147     //
4148     // If LHS is non-negative and we know that LHS - RHS does not
4149     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4150     // either by proving that RHS > M or that LHS >= 0.
4151     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4152       AddFlags = SCEV::FlagNSW;
4153     }
4154   }
4155 
4156   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4157   // RHS is NSW and LHS >= 0.
4158   //
4159   // The difficulty here is that the NSW flag may have been proven
4160   // relative to a loop that is to be found in a recurrence in LHS and
4161   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4162   // larger scope than intended.
4163   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4164 
4165   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4166 }
4167 
4168 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4169                                                      unsigned Depth) {
4170   Type *SrcTy = V->getType();
4171   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4172          "Cannot truncate or zero extend with non-integer arguments!");
4173   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4174     return V;  // No conversion
4175   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4176     return getTruncateExpr(V, Ty, Depth);
4177   return getZeroExtendExpr(V, Ty, Depth);
4178 }
4179 
4180 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4181                                                      unsigned Depth) {
4182   Type *SrcTy = V->getType();
4183   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4184          "Cannot truncate or zero extend with non-integer arguments!");
4185   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4186     return V;  // No conversion
4187   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4188     return getTruncateExpr(V, Ty, Depth);
4189   return getSignExtendExpr(V, Ty, Depth);
4190 }
4191 
4192 const SCEV *
4193 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4194   Type *SrcTy = V->getType();
4195   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4196          "Cannot noop or zero extend with non-integer arguments!");
4197   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4198          "getNoopOrZeroExtend cannot truncate!");
4199   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4200     return V;  // No conversion
4201   return getZeroExtendExpr(V, Ty);
4202 }
4203 
4204 const SCEV *
4205 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4206   Type *SrcTy = V->getType();
4207   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4208          "Cannot noop or sign extend with non-integer arguments!");
4209   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4210          "getNoopOrSignExtend cannot truncate!");
4211   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4212     return V;  // No conversion
4213   return getSignExtendExpr(V, Ty);
4214 }
4215 
4216 const SCEV *
4217 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4218   Type *SrcTy = V->getType();
4219   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4220          "Cannot noop or any extend with non-integer arguments!");
4221   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4222          "getNoopOrAnyExtend cannot truncate!");
4223   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4224     return V;  // No conversion
4225   return getAnyExtendExpr(V, Ty);
4226 }
4227 
4228 const SCEV *
4229 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4230   Type *SrcTy = V->getType();
4231   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4232          "Cannot truncate or noop with non-integer arguments!");
4233   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4234          "getTruncateOrNoop cannot extend!");
4235   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4236     return V;  // No conversion
4237   return getTruncateExpr(V, Ty);
4238 }
4239 
4240 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4241                                                         const SCEV *RHS) {
4242   const SCEV *PromotedLHS = LHS;
4243   const SCEV *PromotedRHS = RHS;
4244 
4245   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4246     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4247   else
4248     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4249 
4250   return getUMaxExpr(PromotedLHS, PromotedRHS);
4251 }
4252 
4253 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4254                                                         const SCEV *RHS) {
4255   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4256   return getUMinFromMismatchedTypes(Ops);
4257 }
4258 
4259 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4260     SmallVectorImpl<const SCEV *> &Ops) {
4261   assert(!Ops.empty() && "At least one operand must be!");
4262   // Trivial case.
4263   if (Ops.size() == 1)
4264     return Ops[0];
4265 
4266   // Find the max type first.
4267   Type *MaxType = nullptr;
4268   for (auto *S : Ops)
4269     if (MaxType)
4270       MaxType = getWiderType(MaxType, S->getType());
4271     else
4272       MaxType = S->getType();
4273   assert(MaxType && "Failed to find maximum type!");
4274 
4275   // Extend all ops to max type.
4276   SmallVector<const SCEV *, 2> PromotedOps;
4277   for (auto *S : Ops)
4278     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4279 
4280   // Generate umin.
4281   return getUMinExpr(PromotedOps);
4282 }
4283 
4284 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4285   // A pointer operand may evaluate to a nonpointer expression, such as null.
4286   if (!V->getType()->isPointerTy())
4287     return V;
4288 
4289   while (true) {
4290     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4291       V = AddRec->getStart();
4292     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4293       const SCEV *PtrOp = nullptr;
4294       for (const SCEV *AddOp : Add->operands()) {
4295         if (AddOp->getType()->isPointerTy()) {
4296           // Cannot find the base of an expression with multiple pointer ops.
4297           if (PtrOp)
4298             return V;
4299           PtrOp = AddOp;
4300         }
4301       }
4302       if (!PtrOp) // All operands were non-pointer.
4303         return V;
4304       V = PtrOp;
4305     } else // Not something we can look further into.
4306       return V;
4307   }
4308 }
4309 
4310 /// Push users of the given Instruction onto the given Worklist.
4311 static void
4312 PushDefUseChildren(Instruction *I,
4313                    SmallVectorImpl<Instruction *> &Worklist) {
4314   // Push the def-use children onto the Worklist stack.
4315   for (User *U : I->users())
4316     Worklist.push_back(cast<Instruction>(U));
4317 }
4318 
4319 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4320   SmallVector<Instruction *, 16> Worklist;
4321   PushDefUseChildren(PN, Worklist);
4322 
4323   SmallPtrSet<Instruction *, 8> Visited;
4324   Visited.insert(PN);
4325   while (!Worklist.empty()) {
4326     Instruction *I = Worklist.pop_back_val();
4327     if (!Visited.insert(I).second)
4328       continue;
4329 
4330     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4331     if (It != ValueExprMap.end()) {
4332       const SCEV *Old = It->second;
4333 
4334       // Short-circuit the def-use traversal if the symbolic name
4335       // ceases to appear in expressions.
4336       if (Old != SymName && !hasOperand(Old, SymName))
4337         continue;
4338 
4339       // SCEVUnknown for a PHI either means that it has an unrecognized
4340       // structure, it's a PHI that's in the progress of being computed
4341       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4342       // additional loop trip count information isn't going to change anything.
4343       // In the second case, createNodeForPHI will perform the necessary
4344       // updates on its own when it gets to that point. In the third, we do
4345       // want to forget the SCEVUnknown.
4346       if (!isa<PHINode>(I) ||
4347           !isa<SCEVUnknown>(Old) ||
4348           (I != PN && Old == SymName)) {
4349         eraseValueFromMap(It->first);
4350         forgetMemoizedResults(Old);
4351       }
4352     }
4353 
4354     PushDefUseChildren(I, Worklist);
4355   }
4356 }
4357 
4358 namespace {
4359 
4360 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4361 /// expression in case its Loop is L. If it is not L then
4362 /// if IgnoreOtherLoops is true then use AddRec itself
4363 /// otherwise rewrite cannot be done.
4364 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4365 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4366 public:
4367   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4368                              bool IgnoreOtherLoops = true) {
4369     SCEVInitRewriter Rewriter(L, SE);
4370     const SCEV *Result = Rewriter.visit(S);
4371     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4372       return SE.getCouldNotCompute();
4373     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4374                ? SE.getCouldNotCompute()
4375                : Result;
4376   }
4377 
4378   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4379     if (!SE.isLoopInvariant(Expr, L))
4380       SeenLoopVariantSCEVUnknown = true;
4381     return Expr;
4382   }
4383 
4384   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4385     // Only re-write AddRecExprs for this loop.
4386     if (Expr->getLoop() == L)
4387       return Expr->getStart();
4388     SeenOtherLoops = true;
4389     return Expr;
4390   }
4391 
4392   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4393 
4394   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4395 
4396 private:
4397   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4398       : SCEVRewriteVisitor(SE), L(L) {}
4399 
4400   const Loop *L;
4401   bool SeenLoopVariantSCEVUnknown = false;
4402   bool SeenOtherLoops = false;
4403 };
4404 
4405 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4406 /// increment expression in case its Loop is L. If it is not L then
4407 /// use AddRec itself.
4408 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4409 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4410 public:
4411   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4412     SCEVPostIncRewriter Rewriter(L, SE);
4413     const SCEV *Result = Rewriter.visit(S);
4414     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4415         ? SE.getCouldNotCompute()
4416         : Result;
4417   }
4418 
4419   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4420     if (!SE.isLoopInvariant(Expr, L))
4421       SeenLoopVariantSCEVUnknown = true;
4422     return Expr;
4423   }
4424 
4425   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4426     // Only re-write AddRecExprs for this loop.
4427     if (Expr->getLoop() == L)
4428       return Expr->getPostIncExpr(SE);
4429     SeenOtherLoops = true;
4430     return Expr;
4431   }
4432 
4433   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4434 
4435   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4436 
4437 private:
4438   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4439       : SCEVRewriteVisitor(SE), L(L) {}
4440 
4441   const Loop *L;
4442   bool SeenLoopVariantSCEVUnknown = false;
4443   bool SeenOtherLoops = false;
4444 };
4445 
4446 /// This class evaluates the compare condition by matching it against the
4447 /// condition of loop latch. If there is a match we assume a true value
4448 /// for the condition while building SCEV nodes.
4449 class SCEVBackedgeConditionFolder
4450     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4451 public:
4452   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4453                              ScalarEvolution &SE) {
4454     bool IsPosBECond = false;
4455     Value *BECond = nullptr;
4456     if (BasicBlock *Latch = L->getLoopLatch()) {
4457       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4458       if (BI && BI->isConditional()) {
4459         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4460                "Both outgoing branches should not target same header!");
4461         BECond = BI->getCondition();
4462         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4463       } else {
4464         return S;
4465       }
4466     }
4467     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4468     return Rewriter.visit(S);
4469   }
4470 
4471   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4472     const SCEV *Result = Expr;
4473     bool InvariantF = SE.isLoopInvariant(Expr, L);
4474 
4475     if (!InvariantF) {
4476       Instruction *I = cast<Instruction>(Expr->getValue());
4477       switch (I->getOpcode()) {
4478       case Instruction::Select: {
4479         SelectInst *SI = cast<SelectInst>(I);
4480         Optional<const SCEV *> Res =
4481             compareWithBackedgeCondition(SI->getCondition());
4482         if (Res.hasValue()) {
4483           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4484           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4485         }
4486         break;
4487       }
4488       default: {
4489         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4490         if (Res.hasValue())
4491           Result = Res.getValue();
4492         break;
4493       }
4494       }
4495     }
4496     return Result;
4497   }
4498 
4499 private:
4500   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4501                                        bool IsPosBECond, ScalarEvolution &SE)
4502       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4503         IsPositiveBECond(IsPosBECond) {}
4504 
4505   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4506 
4507   const Loop *L;
4508   /// Loop back condition.
4509   Value *BackedgeCond = nullptr;
4510   /// Set to true if loop back is on positive branch condition.
4511   bool IsPositiveBECond;
4512 };
4513 
4514 Optional<const SCEV *>
4515 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4516 
4517   // If value matches the backedge condition for loop latch,
4518   // then return a constant evolution node based on loopback
4519   // branch taken.
4520   if (BackedgeCond == IC)
4521     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4522                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4523   return None;
4524 }
4525 
4526 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4527 public:
4528   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4529                              ScalarEvolution &SE) {
4530     SCEVShiftRewriter Rewriter(L, SE);
4531     const SCEV *Result = Rewriter.visit(S);
4532     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4533   }
4534 
4535   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4536     // Only allow AddRecExprs for this loop.
4537     if (!SE.isLoopInvariant(Expr, L))
4538       Valid = false;
4539     return Expr;
4540   }
4541 
4542   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4543     if (Expr->getLoop() == L && Expr->isAffine())
4544       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4545     Valid = false;
4546     return Expr;
4547   }
4548 
4549   bool isValid() { return Valid; }
4550 
4551 private:
4552   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4553       : SCEVRewriteVisitor(SE), L(L) {}
4554 
4555   const Loop *L;
4556   bool Valid = true;
4557 };
4558 
4559 } // end anonymous namespace
4560 
4561 SCEV::NoWrapFlags
4562 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4563   if (!AR->isAffine())
4564     return SCEV::FlagAnyWrap;
4565 
4566   using OBO = OverflowingBinaryOperator;
4567 
4568   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4569 
4570   if (!AR->hasNoSignedWrap()) {
4571     ConstantRange AddRecRange = getSignedRange(AR);
4572     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4573 
4574     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4575         Instruction::Add, IncRange, OBO::NoSignedWrap);
4576     if (NSWRegion.contains(AddRecRange))
4577       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4578   }
4579 
4580   if (!AR->hasNoUnsignedWrap()) {
4581     ConstantRange AddRecRange = getUnsignedRange(AR);
4582     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4583 
4584     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4585         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4586     if (NUWRegion.contains(AddRecRange))
4587       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4588   }
4589 
4590   return Result;
4591 }
4592 
4593 SCEV::NoWrapFlags
4594 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4595   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4596 
4597   if (AR->hasNoSignedWrap())
4598     return Result;
4599 
4600   if (!AR->isAffine())
4601     return Result;
4602 
4603   const SCEV *Step = AR->getStepRecurrence(*this);
4604   const Loop *L = AR->getLoop();
4605 
4606   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4607   // Note that this serves two purposes: It filters out loops that are
4608   // simply not analyzable, and it covers the case where this code is
4609   // being called from within backedge-taken count analysis, such that
4610   // attempting to ask for the backedge-taken count would likely result
4611   // in infinite recursion. In the later case, the analysis code will
4612   // cope with a conservative value, and it will take care to purge
4613   // that value once it has finished.
4614   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4615 
4616   // Normally, in the cases we can prove no-overflow via a
4617   // backedge guarding condition, we can also compute a backedge
4618   // taken count for the loop.  The exceptions are assumptions and
4619   // guards present in the loop -- SCEV is not great at exploiting
4620   // these to compute max backedge taken counts, but can still use
4621   // these to prove lack of overflow.  Use this fact to avoid
4622   // doing extra work that may not pay off.
4623 
4624   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4625       AC.assumptions().empty())
4626     return Result;
4627 
4628   // If the backedge is guarded by a comparison with the pre-inc  value the
4629   // addrec is safe. Also, if the entry is guarded by a comparison with the
4630   // start value and the backedge is guarded by a comparison with the post-inc
4631   // value, the addrec is safe.
4632   ICmpInst::Predicate Pred;
4633   const SCEV *OverflowLimit =
4634     getSignedOverflowLimitForStep(Step, &Pred, this);
4635   if (OverflowLimit &&
4636       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4637        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4638     Result = setFlags(Result, SCEV::FlagNSW);
4639   }
4640   return Result;
4641 }
4642 SCEV::NoWrapFlags
4643 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4644   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4645 
4646   if (AR->hasNoUnsignedWrap())
4647     return Result;
4648 
4649   if (!AR->isAffine())
4650     return Result;
4651 
4652   const SCEV *Step = AR->getStepRecurrence(*this);
4653   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4654   const Loop *L = AR->getLoop();
4655 
4656   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4657   // Note that this serves two purposes: It filters out loops that are
4658   // simply not analyzable, and it covers the case where this code is
4659   // being called from within backedge-taken count analysis, such that
4660   // attempting to ask for the backedge-taken count would likely result
4661   // in infinite recursion. In the later case, the analysis code will
4662   // cope with a conservative value, and it will take care to purge
4663   // that value once it has finished.
4664   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4665 
4666   // Normally, in the cases we can prove no-overflow via a
4667   // backedge guarding condition, we can also compute a backedge
4668   // taken count for the loop.  The exceptions are assumptions and
4669   // guards present in the loop -- SCEV is not great at exploiting
4670   // these to compute max backedge taken counts, but can still use
4671   // these to prove lack of overflow.  Use this fact to avoid
4672   // doing extra work that may not pay off.
4673 
4674   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4675       AC.assumptions().empty())
4676     return Result;
4677 
4678   // If the backedge is guarded by a comparison with the pre-inc  value the
4679   // addrec is safe. Also, if the entry is guarded by a comparison with the
4680   // start value and the backedge is guarded by a comparison with the post-inc
4681   // value, the addrec is safe.
4682   if (isKnownPositive(Step)) {
4683     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4684                                 getUnsignedRangeMax(Step));
4685     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4686         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4687       Result = setFlags(Result, SCEV::FlagNUW);
4688     }
4689   }
4690 
4691   return Result;
4692 }
4693 
4694 namespace {
4695 
4696 /// Represents an abstract binary operation.  This may exist as a
4697 /// normal instruction or constant expression, or may have been
4698 /// derived from an expression tree.
4699 struct BinaryOp {
4700   unsigned Opcode;
4701   Value *LHS;
4702   Value *RHS;
4703   bool IsNSW = false;
4704   bool IsNUW = false;
4705 
4706   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4707   /// constant expression.
4708   Operator *Op = nullptr;
4709 
4710   explicit BinaryOp(Operator *Op)
4711       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4712         Op(Op) {
4713     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4714       IsNSW = OBO->hasNoSignedWrap();
4715       IsNUW = OBO->hasNoUnsignedWrap();
4716     }
4717   }
4718 
4719   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4720                     bool IsNUW = false)
4721       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4722 };
4723 
4724 } // end anonymous namespace
4725 
4726 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4727 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4728   auto *Op = dyn_cast<Operator>(V);
4729   if (!Op)
4730     return None;
4731 
4732   // Implementation detail: all the cleverness here should happen without
4733   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4734   // SCEV expressions when possible, and we should not break that.
4735 
4736   switch (Op->getOpcode()) {
4737   case Instruction::Add:
4738   case Instruction::Sub:
4739   case Instruction::Mul:
4740   case Instruction::UDiv:
4741   case Instruction::URem:
4742   case Instruction::And:
4743   case Instruction::Or:
4744   case Instruction::AShr:
4745   case Instruction::Shl:
4746     return BinaryOp(Op);
4747 
4748   case Instruction::Xor:
4749     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4750       // If the RHS of the xor is a signmask, then this is just an add.
4751       // Instcombine turns add of signmask into xor as a strength reduction step.
4752       if (RHSC->getValue().isSignMask())
4753         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4754     return BinaryOp(Op);
4755 
4756   case Instruction::LShr:
4757     // Turn logical shift right of a constant into a unsigned divide.
4758     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4759       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4760 
4761       // If the shift count is not less than the bitwidth, the result of
4762       // the shift is undefined. Don't try to analyze it, because the
4763       // resolution chosen here may differ from the resolution chosen in
4764       // other parts of the compiler.
4765       if (SA->getValue().ult(BitWidth)) {
4766         Constant *X =
4767             ConstantInt::get(SA->getContext(),
4768                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4769         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4770       }
4771     }
4772     return BinaryOp(Op);
4773 
4774   case Instruction::ExtractValue: {
4775     auto *EVI = cast<ExtractValueInst>(Op);
4776     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4777       break;
4778 
4779     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4780     if (!WO)
4781       break;
4782 
4783     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4784     bool Signed = WO->isSigned();
4785     // TODO: Should add nuw/nsw flags for mul as well.
4786     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4787       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4788 
4789     // Now that we know that all uses of the arithmetic-result component of
4790     // CI are guarded by the overflow check, we can go ahead and pretend
4791     // that the arithmetic is non-overflowing.
4792     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4793                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4794   }
4795 
4796   default:
4797     break;
4798   }
4799 
4800   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4801   // semantics as a Sub, return a binary sub expression.
4802   if (auto *II = dyn_cast<IntrinsicInst>(V))
4803     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4804       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4805 
4806   return None;
4807 }
4808 
4809 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4810 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4811 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4812 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4813 /// follows one of the following patterns:
4814 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4815 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4816 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4817 /// we return the type of the truncation operation, and indicate whether the
4818 /// truncated type should be treated as signed/unsigned by setting
4819 /// \p Signed to true/false, respectively.
4820 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4821                                bool &Signed, ScalarEvolution &SE) {
4822   // The case where Op == SymbolicPHI (that is, with no type conversions on
4823   // the way) is handled by the regular add recurrence creating logic and
4824   // would have already been triggered in createAddRecForPHI. Reaching it here
4825   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4826   // because one of the other operands of the SCEVAddExpr updating this PHI is
4827   // not invariant).
4828   //
4829   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4830   // this case predicates that allow us to prove that Op == SymbolicPHI will
4831   // be added.
4832   if (Op == SymbolicPHI)
4833     return nullptr;
4834 
4835   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4836   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4837   if (SourceBits != NewBits)
4838     return nullptr;
4839 
4840   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4841   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4842   if (!SExt && !ZExt)
4843     return nullptr;
4844   const SCEVTruncateExpr *Trunc =
4845       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4846            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4847   if (!Trunc)
4848     return nullptr;
4849   const SCEV *X = Trunc->getOperand();
4850   if (X != SymbolicPHI)
4851     return nullptr;
4852   Signed = SExt != nullptr;
4853   return Trunc->getType();
4854 }
4855 
4856 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4857   if (!PN->getType()->isIntegerTy())
4858     return nullptr;
4859   const Loop *L = LI.getLoopFor(PN->getParent());
4860   if (!L || L->getHeader() != PN->getParent())
4861     return nullptr;
4862   return L;
4863 }
4864 
4865 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4866 // computation that updates the phi follows the following pattern:
4867 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4868 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4869 // If so, try to see if it can be rewritten as an AddRecExpr under some
4870 // Predicates. If successful, return them as a pair. Also cache the results
4871 // of the analysis.
4872 //
4873 // Example usage scenario:
4874 //    Say the Rewriter is called for the following SCEV:
4875 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4876 //    where:
4877 //         %X = phi i64 (%Start, %BEValue)
4878 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4879 //    and call this function with %SymbolicPHI = %X.
4880 //
4881 //    The analysis will find that the value coming around the backedge has
4882 //    the following SCEV:
4883 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4884 //    Upon concluding that this matches the desired pattern, the function
4885 //    will return the pair {NewAddRec, SmallPredsVec} where:
4886 //         NewAddRec = {%Start,+,%Step}
4887 //         SmallPredsVec = {P1, P2, P3} as follows:
4888 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4889 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4890 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4891 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4892 //    under the predicates {P1,P2,P3}.
4893 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4894 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4895 //
4896 // TODO's:
4897 //
4898 // 1) Extend the Induction descriptor to also support inductions that involve
4899 //    casts: When needed (namely, when we are called in the context of the
4900 //    vectorizer induction analysis), a Set of cast instructions will be
4901 //    populated by this method, and provided back to isInductionPHI. This is
4902 //    needed to allow the vectorizer to properly record them to be ignored by
4903 //    the cost model and to avoid vectorizing them (otherwise these casts,
4904 //    which are redundant under the runtime overflow checks, will be
4905 //    vectorized, which can be costly).
4906 //
4907 // 2) Support additional induction/PHISCEV patterns: We also want to support
4908 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4909 //    after the induction update operation (the induction increment):
4910 //
4911 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4912 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4913 //
4914 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4915 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4916 //
4917 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4918 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4919 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4920   SmallVector<const SCEVPredicate *, 3> Predicates;
4921 
4922   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4923   // return an AddRec expression under some predicate.
4924 
4925   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4926   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4927   assert(L && "Expecting an integer loop header phi");
4928 
4929   // The loop may have multiple entrances or multiple exits; we can analyze
4930   // this phi as an addrec if it has a unique entry value and a unique
4931   // backedge value.
4932   Value *BEValueV = nullptr, *StartValueV = nullptr;
4933   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4934     Value *V = PN->getIncomingValue(i);
4935     if (L->contains(PN->getIncomingBlock(i))) {
4936       if (!BEValueV) {
4937         BEValueV = V;
4938       } else if (BEValueV != V) {
4939         BEValueV = nullptr;
4940         break;
4941       }
4942     } else if (!StartValueV) {
4943       StartValueV = V;
4944     } else if (StartValueV != V) {
4945       StartValueV = nullptr;
4946       break;
4947     }
4948   }
4949   if (!BEValueV || !StartValueV)
4950     return None;
4951 
4952   const SCEV *BEValue = getSCEV(BEValueV);
4953 
4954   // If the value coming around the backedge is an add with the symbolic
4955   // value we just inserted, possibly with casts that we can ignore under
4956   // an appropriate runtime guard, then we found a simple induction variable!
4957   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4958   if (!Add)
4959     return None;
4960 
4961   // If there is a single occurrence of the symbolic value, possibly
4962   // casted, replace it with a recurrence.
4963   unsigned FoundIndex = Add->getNumOperands();
4964   Type *TruncTy = nullptr;
4965   bool Signed;
4966   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4967     if ((TruncTy =
4968              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4969       if (FoundIndex == e) {
4970         FoundIndex = i;
4971         break;
4972       }
4973 
4974   if (FoundIndex == Add->getNumOperands())
4975     return None;
4976 
4977   // Create an add with everything but the specified operand.
4978   SmallVector<const SCEV *, 8> Ops;
4979   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4980     if (i != FoundIndex)
4981       Ops.push_back(Add->getOperand(i));
4982   const SCEV *Accum = getAddExpr(Ops);
4983 
4984   // The runtime checks will not be valid if the step amount is
4985   // varying inside the loop.
4986   if (!isLoopInvariant(Accum, L))
4987     return None;
4988 
4989   // *** Part2: Create the predicates
4990 
4991   // Analysis was successful: we have a phi-with-cast pattern for which we
4992   // can return an AddRec expression under the following predicates:
4993   //
4994   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4995   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4996   // P2: An Equal predicate that guarantees that
4997   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4998   // P3: An Equal predicate that guarantees that
4999   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5000   //
5001   // As we next prove, the above predicates guarantee that:
5002   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5003   //
5004   //
5005   // More formally, we want to prove that:
5006   //     Expr(i+1) = Start + (i+1) * Accum
5007   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5008   //
5009   // Given that:
5010   // 1) Expr(0) = Start
5011   // 2) Expr(1) = Start + Accum
5012   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5013   // 3) Induction hypothesis (step i):
5014   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5015   //
5016   // Proof:
5017   //  Expr(i+1) =
5018   //   = Start + (i+1)*Accum
5019   //   = (Start + i*Accum) + Accum
5020   //   = Expr(i) + Accum
5021   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5022   //                                                             :: from step i
5023   //
5024   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5025   //
5026   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5027   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5028   //     + Accum                                                     :: from P3
5029   //
5030   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5031   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5032   //
5033   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5034   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5035   //
5036   // By induction, the same applies to all iterations 1<=i<n:
5037   //
5038 
5039   // Create a truncated addrec for which we will add a no overflow check (P1).
5040   const SCEV *StartVal = getSCEV(StartValueV);
5041   const SCEV *PHISCEV =
5042       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5043                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5044 
5045   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5046   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5047   // will be constant.
5048   //
5049   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5050   // add P1.
5051   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5052     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5053         Signed ? SCEVWrapPredicate::IncrementNSSW
5054                : SCEVWrapPredicate::IncrementNUSW;
5055     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5056     Predicates.push_back(AddRecPred);
5057   }
5058 
5059   // Create the Equal Predicates P2,P3:
5060 
5061   // It is possible that the predicates P2 and/or P3 are computable at
5062   // compile time due to StartVal and/or Accum being constants.
5063   // If either one is, then we can check that now and escape if either P2
5064   // or P3 is false.
5065 
5066   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5067   // for each of StartVal and Accum
5068   auto getExtendedExpr = [&](const SCEV *Expr,
5069                              bool CreateSignExtend) -> const SCEV * {
5070     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5071     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5072     const SCEV *ExtendedExpr =
5073         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5074                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5075     return ExtendedExpr;
5076   };
5077 
5078   // Given:
5079   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5080   //               = getExtendedExpr(Expr)
5081   // Determine whether the predicate P: Expr == ExtendedExpr
5082   // is known to be false at compile time
5083   auto PredIsKnownFalse = [&](const SCEV *Expr,
5084                               const SCEV *ExtendedExpr) -> bool {
5085     return Expr != ExtendedExpr &&
5086            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5087   };
5088 
5089   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5090   if (PredIsKnownFalse(StartVal, StartExtended)) {
5091     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5092     return None;
5093   }
5094 
5095   // The Step is always Signed (because the overflow checks are either
5096   // NSSW or NUSW)
5097   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5098   if (PredIsKnownFalse(Accum, AccumExtended)) {
5099     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5100     return None;
5101   }
5102 
5103   auto AppendPredicate = [&](const SCEV *Expr,
5104                              const SCEV *ExtendedExpr) -> void {
5105     if (Expr != ExtendedExpr &&
5106         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5107       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5108       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5109       Predicates.push_back(Pred);
5110     }
5111   };
5112 
5113   AppendPredicate(StartVal, StartExtended);
5114   AppendPredicate(Accum, AccumExtended);
5115 
5116   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5117   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5118   // into NewAR if it will also add the runtime overflow checks specified in
5119   // Predicates.
5120   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5121 
5122   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5123       std::make_pair(NewAR, Predicates);
5124   // Remember the result of the analysis for this SCEV at this locayyytion.
5125   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5126   return PredRewrite;
5127 }
5128 
5129 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5130 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5131   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5132   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5133   if (!L)
5134     return None;
5135 
5136   // Check to see if we already analyzed this PHI.
5137   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5138   if (I != PredicatedSCEVRewrites.end()) {
5139     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5140         I->second;
5141     // Analysis was done before and failed to create an AddRec:
5142     if (Rewrite.first == SymbolicPHI)
5143       return None;
5144     // Analysis was done before and succeeded to create an AddRec under
5145     // a predicate:
5146     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5147     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5148     return Rewrite;
5149   }
5150 
5151   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5152     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5153 
5154   // Record in the cache that the analysis failed
5155   if (!Rewrite) {
5156     SmallVector<const SCEVPredicate *, 3> Predicates;
5157     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5158     return None;
5159   }
5160 
5161   return Rewrite;
5162 }
5163 
5164 // FIXME: This utility is currently required because the Rewriter currently
5165 // does not rewrite this expression:
5166 // {0, +, (sext ix (trunc iy to ix) to iy)}
5167 // into {0, +, %step},
5168 // even when the following Equal predicate exists:
5169 // "%step == (sext ix (trunc iy to ix) to iy)".
5170 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5171     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5172   if (AR1 == AR2)
5173     return true;
5174 
5175   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5176     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5177         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5178       return false;
5179     return true;
5180   };
5181 
5182   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5183       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5184     return false;
5185   return true;
5186 }
5187 
5188 /// A helper function for createAddRecFromPHI to handle simple cases.
5189 ///
5190 /// This function tries to find an AddRec expression for the simplest (yet most
5191 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5192 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5193 /// technique for finding the AddRec expression.
5194 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5195                                                       Value *BEValueV,
5196                                                       Value *StartValueV) {
5197   const Loop *L = LI.getLoopFor(PN->getParent());
5198   assert(L && L->getHeader() == PN->getParent());
5199   assert(BEValueV && StartValueV);
5200 
5201   auto BO = MatchBinaryOp(BEValueV, DT);
5202   if (!BO)
5203     return nullptr;
5204 
5205   if (BO->Opcode != Instruction::Add)
5206     return nullptr;
5207 
5208   const SCEV *Accum = nullptr;
5209   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5210     Accum = getSCEV(BO->RHS);
5211   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5212     Accum = getSCEV(BO->LHS);
5213 
5214   if (!Accum)
5215     return nullptr;
5216 
5217   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5218   if (BO->IsNUW)
5219     Flags = setFlags(Flags, SCEV::FlagNUW);
5220   if (BO->IsNSW)
5221     Flags = setFlags(Flags, SCEV::FlagNSW);
5222 
5223   const SCEV *StartVal = getSCEV(StartValueV);
5224   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5225 
5226   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5227 
5228   // We can add Flags to the post-inc expression only if we
5229   // know that it is *undefined behavior* for BEValueV to
5230   // overflow.
5231   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5232     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5233       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5234 
5235   return PHISCEV;
5236 }
5237 
5238 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5239   const Loop *L = LI.getLoopFor(PN->getParent());
5240   if (!L || L->getHeader() != PN->getParent())
5241     return nullptr;
5242 
5243   // The loop may have multiple entrances or multiple exits; we can analyze
5244   // this phi as an addrec if it has a unique entry value and a unique
5245   // backedge value.
5246   Value *BEValueV = nullptr, *StartValueV = nullptr;
5247   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5248     Value *V = PN->getIncomingValue(i);
5249     if (L->contains(PN->getIncomingBlock(i))) {
5250       if (!BEValueV) {
5251         BEValueV = V;
5252       } else if (BEValueV != V) {
5253         BEValueV = nullptr;
5254         break;
5255       }
5256     } else if (!StartValueV) {
5257       StartValueV = V;
5258     } else if (StartValueV != V) {
5259       StartValueV = nullptr;
5260       break;
5261     }
5262   }
5263   if (!BEValueV || !StartValueV)
5264     return nullptr;
5265 
5266   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5267          "PHI node already processed?");
5268 
5269   // First, try to find AddRec expression without creating a fictituos symbolic
5270   // value for PN.
5271   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5272     return S;
5273 
5274   // Handle PHI node value symbolically.
5275   const SCEV *SymbolicName = getUnknown(PN);
5276   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5277 
5278   // Using this symbolic name for the PHI, analyze the value coming around
5279   // the back-edge.
5280   const SCEV *BEValue = getSCEV(BEValueV);
5281 
5282   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5283   // has a special value for the first iteration of the loop.
5284 
5285   // If the value coming around the backedge is an add with the symbolic
5286   // value we just inserted, then we found a simple induction variable!
5287   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5288     // If there is a single occurrence of the symbolic value, replace it
5289     // with a recurrence.
5290     unsigned FoundIndex = Add->getNumOperands();
5291     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5292       if (Add->getOperand(i) == SymbolicName)
5293         if (FoundIndex == e) {
5294           FoundIndex = i;
5295           break;
5296         }
5297 
5298     if (FoundIndex != Add->getNumOperands()) {
5299       // Create an add with everything but the specified operand.
5300       SmallVector<const SCEV *, 8> Ops;
5301       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5302         if (i != FoundIndex)
5303           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5304                                                              L, *this));
5305       const SCEV *Accum = getAddExpr(Ops);
5306 
5307       // This is not a valid addrec if the step amount is varying each
5308       // loop iteration, but is not itself an addrec in this loop.
5309       if (isLoopInvariant(Accum, L) ||
5310           (isa<SCEVAddRecExpr>(Accum) &&
5311            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5312         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5313 
5314         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5315           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5316             if (BO->IsNUW)
5317               Flags = setFlags(Flags, SCEV::FlagNUW);
5318             if (BO->IsNSW)
5319               Flags = setFlags(Flags, SCEV::FlagNSW);
5320           }
5321         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5322           // If the increment is an inbounds GEP, then we know the address
5323           // space cannot be wrapped around. We cannot make any guarantee
5324           // about signed or unsigned overflow because pointers are
5325           // unsigned but we may have a negative index from the base
5326           // pointer. We can guarantee that no unsigned wrap occurs if the
5327           // indices form a positive value.
5328           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5329             Flags = setFlags(Flags, SCEV::FlagNW);
5330 
5331             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5332             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5333               Flags = setFlags(Flags, SCEV::FlagNUW);
5334           }
5335 
5336           // We cannot transfer nuw and nsw flags from subtraction
5337           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5338           // for instance.
5339         }
5340 
5341         const SCEV *StartVal = getSCEV(StartValueV);
5342         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5343 
5344         // Okay, for the entire analysis of this edge we assumed the PHI
5345         // to be symbolic.  We now need to go back and purge all of the
5346         // entries for the scalars that use the symbolic expression.
5347         forgetSymbolicName(PN, SymbolicName);
5348         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5349 
5350         // We can add Flags to the post-inc expression only if we
5351         // know that it is *undefined behavior* for BEValueV to
5352         // overflow.
5353         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5354           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5355             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5356 
5357         return PHISCEV;
5358       }
5359     }
5360   } else {
5361     // Otherwise, this could be a loop like this:
5362     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5363     // In this case, j = {1,+,1}  and BEValue is j.
5364     // Because the other in-value of i (0) fits the evolution of BEValue
5365     // i really is an addrec evolution.
5366     //
5367     // We can generalize this saying that i is the shifted value of BEValue
5368     // by one iteration:
5369     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5370     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5371     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5372     if (Shifted != getCouldNotCompute() &&
5373         Start != getCouldNotCompute()) {
5374       const SCEV *StartVal = getSCEV(StartValueV);
5375       if (Start == StartVal) {
5376         // Okay, for the entire analysis of this edge we assumed the PHI
5377         // to be symbolic.  We now need to go back and purge all of the
5378         // entries for the scalars that use the symbolic expression.
5379         forgetSymbolicName(PN, SymbolicName);
5380         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5381         return Shifted;
5382       }
5383     }
5384   }
5385 
5386   // Remove the temporary PHI node SCEV that has been inserted while intending
5387   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5388   // as it will prevent later (possibly simpler) SCEV expressions to be added
5389   // to the ValueExprMap.
5390   eraseValueFromMap(PN);
5391 
5392   return nullptr;
5393 }
5394 
5395 // Checks if the SCEV S is available at BB.  S is considered available at BB
5396 // if S can be materialized at BB without introducing a fault.
5397 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5398                                BasicBlock *BB) {
5399   struct CheckAvailable {
5400     bool TraversalDone = false;
5401     bool Available = true;
5402 
5403     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5404     BasicBlock *BB = nullptr;
5405     DominatorTree &DT;
5406 
5407     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5408       : L(L), BB(BB), DT(DT) {}
5409 
5410     bool setUnavailable() {
5411       TraversalDone = true;
5412       Available = false;
5413       return false;
5414     }
5415 
5416     bool follow(const SCEV *S) {
5417       switch (S->getSCEVType()) {
5418       case scConstant:
5419       case scPtrToInt:
5420       case scTruncate:
5421       case scZeroExtend:
5422       case scSignExtend:
5423       case scAddExpr:
5424       case scMulExpr:
5425       case scUMaxExpr:
5426       case scSMaxExpr:
5427       case scUMinExpr:
5428       case scSMinExpr:
5429         // These expressions are available if their operand(s) is/are.
5430         return true;
5431 
5432       case scAddRecExpr: {
5433         // We allow add recurrences that are on the loop BB is in, or some
5434         // outer loop.  This guarantees availability because the value of the
5435         // add recurrence at BB is simply the "current" value of the induction
5436         // variable.  We can relax this in the future; for instance an add
5437         // recurrence on a sibling dominating loop is also available at BB.
5438         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5439         if (L && (ARLoop == L || ARLoop->contains(L)))
5440           return true;
5441 
5442         return setUnavailable();
5443       }
5444 
5445       case scUnknown: {
5446         // For SCEVUnknown, we check for simple dominance.
5447         const auto *SU = cast<SCEVUnknown>(S);
5448         Value *V = SU->getValue();
5449 
5450         if (isa<Argument>(V))
5451           return false;
5452 
5453         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5454           return false;
5455 
5456         return setUnavailable();
5457       }
5458 
5459       case scUDivExpr:
5460       case scCouldNotCompute:
5461         // We do not try to smart about these at all.
5462         return setUnavailable();
5463       }
5464       llvm_unreachable("Unknown SCEV kind!");
5465     }
5466 
5467     bool isDone() { return TraversalDone; }
5468   };
5469 
5470   CheckAvailable CA(L, BB, DT);
5471   SCEVTraversal<CheckAvailable> ST(CA);
5472 
5473   ST.visitAll(S);
5474   return CA.Available;
5475 }
5476 
5477 // Try to match a control flow sequence that branches out at BI and merges back
5478 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5479 // match.
5480 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5481                           Value *&C, Value *&LHS, Value *&RHS) {
5482   C = BI->getCondition();
5483 
5484   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5485   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5486 
5487   if (!LeftEdge.isSingleEdge())
5488     return false;
5489 
5490   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5491 
5492   Use &LeftUse = Merge->getOperandUse(0);
5493   Use &RightUse = Merge->getOperandUse(1);
5494 
5495   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5496     LHS = LeftUse;
5497     RHS = RightUse;
5498     return true;
5499   }
5500 
5501   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5502     LHS = RightUse;
5503     RHS = LeftUse;
5504     return true;
5505   }
5506 
5507   return false;
5508 }
5509 
5510 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5511   auto IsReachable =
5512       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5513   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5514     const Loop *L = LI.getLoopFor(PN->getParent());
5515 
5516     // We don't want to break LCSSA, even in a SCEV expression tree.
5517     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5518       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5519         return nullptr;
5520 
5521     // Try to match
5522     //
5523     //  br %cond, label %left, label %right
5524     // left:
5525     //  br label %merge
5526     // right:
5527     //  br label %merge
5528     // merge:
5529     //  V = phi [ %x, %left ], [ %y, %right ]
5530     //
5531     // as "select %cond, %x, %y"
5532 
5533     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5534     assert(IDom && "At least the entry block should dominate PN");
5535 
5536     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5537     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5538 
5539     if (BI && BI->isConditional() &&
5540         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5541         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5542         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5543       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5544   }
5545 
5546   return nullptr;
5547 }
5548 
5549 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5550   if (const SCEV *S = createAddRecFromPHI(PN))
5551     return S;
5552 
5553   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5554     return S;
5555 
5556   // If the PHI has a single incoming value, follow that value, unless the
5557   // PHI's incoming blocks are in a different loop, in which case doing so
5558   // risks breaking LCSSA form. Instcombine would normally zap these, but
5559   // it doesn't have DominatorTree information, so it may miss cases.
5560   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5561     if (LI.replacementPreservesLCSSAForm(PN, V))
5562       return getSCEV(V);
5563 
5564   // If it's not a loop phi, we can't handle it yet.
5565   return getUnknown(PN);
5566 }
5567 
5568 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5569                                                       Value *Cond,
5570                                                       Value *TrueVal,
5571                                                       Value *FalseVal) {
5572   // Handle "constant" branch or select. This can occur for instance when a
5573   // loop pass transforms an inner loop and moves on to process the outer loop.
5574   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5575     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5576 
5577   // Try to match some simple smax or umax patterns.
5578   auto *ICI = dyn_cast<ICmpInst>(Cond);
5579   if (!ICI)
5580     return getUnknown(I);
5581 
5582   Value *LHS = ICI->getOperand(0);
5583   Value *RHS = ICI->getOperand(1);
5584 
5585   switch (ICI->getPredicate()) {
5586   case ICmpInst::ICMP_SLT:
5587   case ICmpInst::ICMP_SLE:
5588   case ICmpInst::ICMP_ULT:
5589   case ICmpInst::ICMP_ULE:
5590     std::swap(LHS, RHS);
5591     LLVM_FALLTHROUGH;
5592   case ICmpInst::ICMP_SGT:
5593   case ICmpInst::ICMP_SGE:
5594   case ICmpInst::ICMP_UGT:
5595   case ICmpInst::ICMP_UGE:
5596     // a > b ? a+x : b+x  ->  max(a, b)+x
5597     // a > b ? b+x : a+x  ->  min(a, b)+x
5598     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5599       bool Signed = ICI->isSigned();
5600       const SCEV *LA = getSCEV(TrueVal);
5601       const SCEV *RA = getSCEV(FalseVal);
5602       const SCEV *LS = getSCEV(LHS);
5603       const SCEV *RS = getSCEV(RHS);
5604       if (LA->getType()->isPointerTy()) {
5605         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5606         // Need to make sure we can't produce weird expressions involving
5607         // negated pointers.
5608         if (LA == LS && RA == RS)
5609           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5610         if (LA == RS && RA == LS)
5611           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5612       }
5613       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5614         if (Op->getType()->isPointerTy()) {
5615           Op = getLosslessPtrToIntExpr(Op);
5616           if (isa<SCEVCouldNotCompute>(Op))
5617             return Op;
5618         }
5619         if (Signed)
5620           Op = getNoopOrSignExtend(Op, I->getType());
5621         else
5622           Op = getNoopOrZeroExtend(Op, I->getType());
5623         return Op;
5624       };
5625       LS = CoerceOperand(LS);
5626       RS = CoerceOperand(RS);
5627       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
5628         break;
5629       const SCEV *LDiff = getMinusSCEV(LA, LS);
5630       const SCEV *RDiff = getMinusSCEV(RA, RS);
5631       if (LDiff == RDiff)
5632         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
5633                           LDiff);
5634       LDiff = getMinusSCEV(LA, RS);
5635       RDiff = getMinusSCEV(RA, LS);
5636       if (LDiff == RDiff)
5637         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
5638                           LDiff);
5639     }
5640     break;
5641   case ICmpInst::ICMP_NE:
5642     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5643     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5644         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5645       const SCEV *One = getOne(I->getType());
5646       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5647       const SCEV *LA = getSCEV(TrueVal);
5648       const SCEV *RA = getSCEV(FalseVal);
5649       const SCEV *LDiff = getMinusSCEV(LA, LS);
5650       const SCEV *RDiff = getMinusSCEV(RA, One);
5651       if (LDiff == RDiff)
5652         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5653     }
5654     break;
5655   case ICmpInst::ICMP_EQ:
5656     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5657     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5658         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5659       const SCEV *One = getOne(I->getType());
5660       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5661       const SCEV *LA = getSCEV(TrueVal);
5662       const SCEV *RA = getSCEV(FalseVal);
5663       const SCEV *LDiff = getMinusSCEV(LA, One);
5664       const SCEV *RDiff = getMinusSCEV(RA, LS);
5665       if (LDiff == RDiff)
5666         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5667     }
5668     break;
5669   default:
5670     break;
5671   }
5672 
5673   return getUnknown(I);
5674 }
5675 
5676 /// Expand GEP instructions into add and multiply operations. This allows them
5677 /// to be analyzed by regular SCEV code.
5678 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5679   // Don't attempt to analyze GEPs over unsized objects.
5680   if (!GEP->getSourceElementType()->isSized())
5681     return getUnknown(GEP);
5682 
5683   SmallVector<const SCEV *, 4> IndexExprs;
5684   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5685     IndexExprs.push_back(getSCEV(*Index));
5686   return getGEPExpr(GEP, IndexExprs);
5687 }
5688 
5689 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5690   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5691     return C->getAPInt().countTrailingZeros();
5692 
5693   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5694     return GetMinTrailingZeros(I->getOperand());
5695 
5696   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5697     return std::min(GetMinTrailingZeros(T->getOperand()),
5698                     (uint32_t)getTypeSizeInBits(T->getType()));
5699 
5700   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5701     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5702     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5703                ? getTypeSizeInBits(E->getType())
5704                : OpRes;
5705   }
5706 
5707   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5708     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5709     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5710                ? getTypeSizeInBits(E->getType())
5711                : OpRes;
5712   }
5713 
5714   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5715     // The result is the min of all operands results.
5716     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5717     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5718       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5719     return MinOpRes;
5720   }
5721 
5722   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5723     // The result is the sum of all operands results.
5724     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5725     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5726     for (unsigned i = 1, e = M->getNumOperands();
5727          SumOpRes != BitWidth && i != e; ++i)
5728       SumOpRes =
5729           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5730     return SumOpRes;
5731   }
5732 
5733   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5734     // The result is the min of all operands results.
5735     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5736     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5737       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5738     return MinOpRes;
5739   }
5740 
5741   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5742     // The result is the min of all operands results.
5743     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5744     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5745       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5746     return MinOpRes;
5747   }
5748 
5749   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5750     // The result is the min of all operands results.
5751     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5752     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5753       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5754     return MinOpRes;
5755   }
5756 
5757   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5758     // For a SCEVUnknown, ask ValueTracking.
5759     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5760     return Known.countMinTrailingZeros();
5761   }
5762 
5763   // SCEVUDivExpr
5764   return 0;
5765 }
5766 
5767 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5768   auto I = MinTrailingZerosCache.find(S);
5769   if (I != MinTrailingZerosCache.end())
5770     return I->second;
5771 
5772   uint32_t Result = GetMinTrailingZerosImpl(S);
5773   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5774   assert(InsertPair.second && "Should insert a new key");
5775   return InsertPair.first->second;
5776 }
5777 
5778 /// Helper method to assign a range to V from metadata present in the IR.
5779 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5780   if (Instruction *I = dyn_cast<Instruction>(V))
5781     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5782       return getConstantRangeFromMetadata(*MD);
5783 
5784   return None;
5785 }
5786 
5787 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5788                                      SCEV::NoWrapFlags Flags) {
5789   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5790     AddRec->setNoWrapFlags(Flags);
5791     UnsignedRanges.erase(AddRec);
5792     SignedRanges.erase(AddRec);
5793   }
5794 }
5795 
5796 ConstantRange ScalarEvolution::
5797 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5798   const DataLayout &DL = getDataLayout();
5799 
5800   unsigned BitWidth = getTypeSizeInBits(U->getType());
5801   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
5802 
5803   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5804   // use information about the trip count to improve our available range.  Note
5805   // that the trip count independent cases are already handled by known bits.
5806   // WARNING: The definition of recurrence used here is subtly different than
5807   // the one used by AddRec (and thus most of this file).  Step is allowed to
5808   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5809   // and other addrecs in the same loop (for non-affine addrecs).  The code
5810   // below intentionally handles the case where step is not loop invariant.
5811   auto *P = dyn_cast<PHINode>(U->getValue());
5812   if (!P)
5813     return FullSet;
5814 
5815   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5816   // even the values that are not available in these blocks may come from them,
5817   // and this leads to false-positive recurrence test.
5818   for (auto *Pred : predecessors(P->getParent()))
5819     if (!DT.isReachableFromEntry(Pred))
5820       return FullSet;
5821 
5822   BinaryOperator *BO;
5823   Value *Start, *Step;
5824   if (!matchSimpleRecurrence(P, BO, Start, Step))
5825     return FullSet;
5826 
5827   // If we found a recurrence in reachable code, we must be in a loop. Note
5828   // that BO might be in some subloop of L, and that's completely okay.
5829   auto *L = LI.getLoopFor(P->getParent());
5830   assert(L && L->getHeader() == P->getParent());
5831   if (!L->contains(BO->getParent()))
5832     // NOTE: This bailout should be an assert instead.  However, asserting
5833     // the condition here exposes a case where LoopFusion is querying SCEV
5834     // with malformed loop information during the midst of the transform.
5835     // There doesn't appear to be an obvious fix, so for the moment bailout
5836     // until the caller issue can be fixed.  PR49566 tracks the bug.
5837     return FullSet;
5838 
5839   // TODO: Extend to other opcodes such as mul, and div
5840   switch (BO->getOpcode()) {
5841   default:
5842     return FullSet;
5843   case Instruction::AShr:
5844   case Instruction::LShr:
5845   case Instruction::Shl:
5846     break;
5847   };
5848 
5849   if (BO->getOperand(0) != P)
5850     // TODO: Handle the power function forms some day.
5851     return FullSet;
5852 
5853   unsigned TC = getSmallConstantMaxTripCount(L);
5854   if (!TC || TC >= BitWidth)
5855     return FullSet;
5856 
5857   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5858   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5859   assert(KnownStart.getBitWidth() == BitWidth &&
5860          KnownStep.getBitWidth() == BitWidth);
5861 
5862   // Compute total shift amount, being careful of overflow and bitwidths.
5863   auto MaxShiftAmt = KnownStep.getMaxValue();
5864   APInt TCAP(BitWidth, TC-1);
5865   bool Overflow = false;
5866   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5867   if (Overflow)
5868     return FullSet;
5869 
5870   switch (BO->getOpcode()) {
5871   default:
5872     llvm_unreachable("filtered out above");
5873   case Instruction::AShr: {
5874     // For each ashr, three cases:
5875     //   shift = 0 => unchanged value
5876     //   saturation => 0 or -1
5877     //   other => a value closer to zero (of the same sign)
5878     // Thus, the end value is closer to zero than the start.
5879     auto KnownEnd = KnownBits::ashr(KnownStart,
5880                                     KnownBits::makeConstant(TotalShift));
5881     if (KnownStart.isNonNegative())
5882       // Analogous to lshr (simply not yet canonicalized)
5883       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5884                                         KnownStart.getMaxValue() + 1);
5885     if (KnownStart.isNegative())
5886       // End >=u Start && End <=s Start
5887       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
5888                                         KnownEnd.getMaxValue() + 1);
5889     break;
5890   }
5891   case Instruction::LShr: {
5892     // For each lshr, three cases:
5893     //   shift = 0 => unchanged value
5894     //   saturation => 0
5895     //   other => a smaller positive number
5896     // Thus, the low end of the unsigned range is the last value produced.
5897     auto KnownEnd = KnownBits::lshr(KnownStart,
5898                                     KnownBits::makeConstant(TotalShift));
5899     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5900                                       KnownStart.getMaxValue() + 1);
5901   }
5902   case Instruction::Shl: {
5903     // Iff no bits are shifted out, value increases on every shift.
5904     auto KnownEnd = KnownBits::shl(KnownStart,
5905                                    KnownBits::makeConstant(TotalShift));
5906     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5907       return ConstantRange(KnownStart.getMinValue(),
5908                            KnownEnd.getMaxValue() + 1);
5909     break;
5910   }
5911   };
5912   return FullSet;
5913 }
5914 
5915 /// Determine the range for a particular SCEV.  If SignHint is
5916 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5917 /// with a "cleaner" unsigned (resp. signed) representation.
5918 const ConstantRange &
5919 ScalarEvolution::getRangeRef(const SCEV *S,
5920                              ScalarEvolution::RangeSignHint SignHint) {
5921   DenseMap<const SCEV *, ConstantRange> &Cache =
5922       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5923                                                        : SignedRanges;
5924   ConstantRange::PreferredRangeType RangeType =
5925       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5926           ? ConstantRange::Unsigned : ConstantRange::Signed;
5927 
5928   // See if we've computed this range already.
5929   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5930   if (I != Cache.end())
5931     return I->second;
5932 
5933   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5934     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5935 
5936   unsigned BitWidth = getTypeSizeInBits(S->getType());
5937   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5938   using OBO = OverflowingBinaryOperator;
5939 
5940   // If the value has known zeros, the maximum value will have those known zeros
5941   // as well.
5942   uint32_t TZ = GetMinTrailingZeros(S);
5943   if (TZ != 0) {
5944     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5945       ConservativeResult =
5946           ConstantRange(APInt::getMinValue(BitWidth),
5947                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5948     else
5949       ConservativeResult = ConstantRange(
5950           APInt::getSignedMinValue(BitWidth),
5951           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5952   }
5953 
5954   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5955     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5956     unsigned WrapType = OBO::AnyWrap;
5957     if (Add->hasNoSignedWrap())
5958       WrapType |= OBO::NoSignedWrap;
5959     if (Add->hasNoUnsignedWrap())
5960       WrapType |= OBO::NoUnsignedWrap;
5961     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5962       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5963                           WrapType, RangeType);
5964     return setRange(Add, SignHint,
5965                     ConservativeResult.intersectWith(X, RangeType));
5966   }
5967 
5968   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5969     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5970     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5971       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5972     return setRange(Mul, SignHint,
5973                     ConservativeResult.intersectWith(X, RangeType));
5974   }
5975 
5976   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5977     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5978     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5979       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5980     return setRange(SMax, SignHint,
5981                     ConservativeResult.intersectWith(X, RangeType));
5982   }
5983 
5984   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5985     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5986     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5987       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5988     return setRange(UMax, SignHint,
5989                     ConservativeResult.intersectWith(X, RangeType));
5990   }
5991 
5992   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5993     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5994     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5995       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5996     return setRange(SMin, SignHint,
5997                     ConservativeResult.intersectWith(X, RangeType));
5998   }
5999 
6000   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
6001     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
6002     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
6003       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
6004     return setRange(UMin, SignHint,
6005                     ConservativeResult.intersectWith(X, RangeType));
6006   }
6007 
6008   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6009     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6010     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6011     return setRange(UDiv, SignHint,
6012                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6013   }
6014 
6015   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6016     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6017     return setRange(ZExt, SignHint,
6018                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6019                                                      RangeType));
6020   }
6021 
6022   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6023     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6024     return setRange(SExt, SignHint,
6025                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6026                                                      RangeType));
6027   }
6028 
6029   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6030     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6031     return setRange(PtrToInt, SignHint, X);
6032   }
6033 
6034   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6035     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6036     return setRange(Trunc, SignHint,
6037                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6038                                                      RangeType));
6039   }
6040 
6041   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6042     // If there's no unsigned wrap, the value will never be less than its
6043     // initial value.
6044     if (AddRec->hasNoUnsignedWrap()) {
6045       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6046       if (!UnsignedMinValue.isNullValue())
6047         ConservativeResult = ConservativeResult.intersectWith(
6048             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6049     }
6050 
6051     // If there's no signed wrap, and all the operands except initial value have
6052     // the same sign or zero, the value won't ever be:
6053     // 1: smaller than initial value if operands are non negative,
6054     // 2: bigger than initial value if operands are non positive.
6055     // For both cases, value can not cross signed min/max boundary.
6056     if (AddRec->hasNoSignedWrap()) {
6057       bool AllNonNeg = true;
6058       bool AllNonPos = true;
6059       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6060         if (!isKnownNonNegative(AddRec->getOperand(i)))
6061           AllNonNeg = false;
6062         if (!isKnownNonPositive(AddRec->getOperand(i)))
6063           AllNonPos = false;
6064       }
6065       if (AllNonNeg)
6066         ConservativeResult = ConservativeResult.intersectWith(
6067             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6068                                        APInt::getSignedMinValue(BitWidth)),
6069             RangeType);
6070       else if (AllNonPos)
6071         ConservativeResult = ConservativeResult.intersectWith(
6072             ConstantRange::getNonEmpty(
6073                 APInt::getSignedMinValue(BitWidth),
6074                 getSignedRangeMax(AddRec->getStart()) + 1),
6075             RangeType);
6076     }
6077 
6078     // TODO: non-affine addrec
6079     if (AddRec->isAffine()) {
6080       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6081       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6082           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6083         auto RangeFromAffine = getRangeForAffineAR(
6084             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6085             BitWidth);
6086         ConservativeResult =
6087             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6088 
6089         auto RangeFromFactoring = getRangeViaFactoring(
6090             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6091             BitWidth);
6092         ConservativeResult =
6093             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6094       }
6095 
6096       // Now try symbolic BE count and more powerful methods.
6097       if (UseExpensiveRangeSharpening) {
6098         const SCEV *SymbolicMaxBECount =
6099             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6100         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6101             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6102             AddRec->hasNoSelfWrap()) {
6103           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6104               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6105           ConservativeResult =
6106               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6107         }
6108       }
6109     }
6110 
6111     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6112   }
6113 
6114   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6115 
6116     // Check if the IR explicitly contains !range metadata.
6117     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6118     if (MDRange.hasValue())
6119       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6120                                                             RangeType);
6121 
6122     // Use facts about recurrences in the underlying IR.  Note that add
6123     // recurrences are AddRecExprs and thus don't hit this path.  This
6124     // primarily handles shift recurrences.
6125     auto CR = getRangeForUnknownRecurrence(U);
6126     ConservativeResult = ConservativeResult.intersectWith(CR);
6127 
6128     // See if ValueTracking can give us a useful range.
6129     const DataLayout &DL = getDataLayout();
6130     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6131     if (Known.getBitWidth() != BitWidth)
6132       Known = Known.zextOrTrunc(BitWidth);
6133 
6134     // ValueTracking may be able to compute a tighter result for the number of
6135     // sign bits than for the value of those sign bits.
6136     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6137     if (U->getType()->isPointerTy()) {
6138       // If the pointer size is larger than the index size type, this can cause
6139       // NS to be larger than BitWidth. So compensate for this.
6140       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6141       int ptrIdxDiff = ptrSize - BitWidth;
6142       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6143         NS -= ptrIdxDiff;
6144     }
6145 
6146     if (NS > 1) {
6147       // If we know any of the sign bits, we know all of the sign bits.
6148       if (!Known.Zero.getHiBits(NS).isNullValue())
6149         Known.Zero.setHighBits(NS);
6150       if (!Known.One.getHiBits(NS).isNullValue())
6151         Known.One.setHighBits(NS);
6152     }
6153 
6154     if (Known.getMinValue() != Known.getMaxValue() + 1)
6155       ConservativeResult = ConservativeResult.intersectWith(
6156           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6157           RangeType);
6158     if (NS > 1)
6159       ConservativeResult = ConservativeResult.intersectWith(
6160           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6161                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6162           RangeType);
6163 
6164     // A range of Phi is a subset of union of all ranges of its input.
6165     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6166       // Make sure that we do not run over cycled Phis.
6167       if (PendingPhiRanges.insert(Phi).second) {
6168         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6169         for (auto &Op : Phi->operands()) {
6170           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6171           RangeFromOps = RangeFromOps.unionWith(OpRange);
6172           // No point to continue if we already have a full set.
6173           if (RangeFromOps.isFullSet())
6174             break;
6175         }
6176         ConservativeResult =
6177             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6178         bool Erased = PendingPhiRanges.erase(Phi);
6179         assert(Erased && "Failed to erase Phi properly?");
6180         (void) Erased;
6181       }
6182     }
6183 
6184     return setRange(U, SignHint, std::move(ConservativeResult));
6185   }
6186 
6187   return setRange(S, SignHint, std::move(ConservativeResult));
6188 }
6189 
6190 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6191 // values that the expression can take. Initially, the expression has a value
6192 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6193 // argument defines if we treat Step as signed or unsigned.
6194 static ConstantRange getRangeForAffineARHelper(APInt Step,
6195                                                const ConstantRange &StartRange,
6196                                                const APInt &MaxBECount,
6197                                                unsigned BitWidth, bool Signed) {
6198   // If either Step or MaxBECount is 0, then the expression won't change, and we
6199   // just need to return the initial range.
6200   if (Step == 0 || MaxBECount == 0)
6201     return StartRange;
6202 
6203   // If we don't know anything about the initial value (i.e. StartRange is
6204   // FullRange), then we don't know anything about the final range either.
6205   // Return FullRange.
6206   if (StartRange.isFullSet())
6207     return ConstantRange::getFull(BitWidth);
6208 
6209   // If Step is signed and negative, then we use its absolute value, but we also
6210   // note that we're moving in the opposite direction.
6211   bool Descending = Signed && Step.isNegative();
6212 
6213   if (Signed)
6214     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6215     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6216     // This equations hold true due to the well-defined wrap-around behavior of
6217     // APInt.
6218     Step = Step.abs();
6219 
6220   // Check if Offset is more than full span of BitWidth. If it is, the
6221   // expression is guaranteed to overflow.
6222   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6223     return ConstantRange::getFull(BitWidth);
6224 
6225   // Offset is by how much the expression can change. Checks above guarantee no
6226   // overflow here.
6227   APInt Offset = Step * MaxBECount;
6228 
6229   // Minimum value of the final range will match the minimal value of StartRange
6230   // if the expression is increasing and will be decreased by Offset otherwise.
6231   // Maximum value of the final range will match the maximal value of StartRange
6232   // if the expression is decreasing and will be increased by Offset otherwise.
6233   APInt StartLower = StartRange.getLower();
6234   APInt StartUpper = StartRange.getUpper() - 1;
6235   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6236                                    : (StartUpper + std::move(Offset));
6237 
6238   // It's possible that the new minimum/maximum value will fall into the initial
6239   // range (due to wrap around). This means that the expression can take any
6240   // value in this bitwidth, and we have to return full range.
6241   if (StartRange.contains(MovedBoundary))
6242     return ConstantRange::getFull(BitWidth);
6243 
6244   APInt NewLower =
6245       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6246   APInt NewUpper =
6247       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6248   NewUpper += 1;
6249 
6250   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6251   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6252 }
6253 
6254 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6255                                                    const SCEV *Step,
6256                                                    const SCEV *MaxBECount,
6257                                                    unsigned BitWidth) {
6258   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6259          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6260          "Precondition!");
6261 
6262   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6263   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6264 
6265   // First, consider step signed.
6266   ConstantRange StartSRange = getSignedRange(Start);
6267   ConstantRange StepSRange = getSignedRange(Step);
6268 
6269   // If Step can be both positive and negative, we need to find ranges for the
6270   // maximum absolute step values in both directions and union them.
6271   ConstantRange SR =
6272       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6273                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6274   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6275                                               StartSRange, MaxBECountValue,
6276                                               BitWidth, /* Signed = */ true));
6277 
6278   // Next, consider step unsigned.
6279   ConstantRange UR = getRangeForAffineARHelper(
6280       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6281       MaxBECountValue, BitWidth, /* Signed = */ false);
6282 
6283   // Finally, intersect signed and unsigned ranges.
6284   return SR.intersectWith(UR, ConstantRange::Smallest);
6285 }
6286 
6287 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6288     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6289     ScalarEvolution::RangeSignHint SignHint) {
6290   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6291   assert(AddRec->hasNoSelfWrap() &&
6292          "This only works for non-self-wrapping AddRecs!");
6293   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6294   const SCEV *Step = AddRec->getStepRecurrence(*this);
6295   // Only deal with constant step to save compile time.
6296   if (!isa<SCEVConstant>(Step))
6297     return ConstantRange::getFull(BitWidth);
6298   // Let's make sure that we can prove that we do not self-wrap during
6299   // MaxBECount iterations. We need this because MaxBECount is a maximum
6300   // iteration count estimate, and we might infer nw from some exit for which we
6301   // do not know max exit count (or any other side reasoning).
6302   // TODO: Turn into assert at some point.
6303   if (getTypeSizeInBits(MaxBECount->getType()) >
6304       getTypeSizeInBits(AddRec->getType()))
6305     return ConstantRange::getFull(BitWidth);
6306   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6307   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6308   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6309   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6310   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6311                                          MaxItersWithoutWrap))
6312     return ConstantRange::getFull(BitWidth);
6313 
6314   ICmpInst::Predicate LEPred =
6315       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6316   ICmpInst::Predicate GEPred =
6317       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6318   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6319 
6320   // We know that there is no self-wrap. Let's take Start and End values and
6321   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6322   // the iteration. They either lie inside the range [Min(Start, End),
6323   // Max(Start, End)] or outside it:
6324   //
6325   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6326   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6327   //
6328   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6329   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6330   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6331   // Start <= End and step is positive, or Start >= End and step is negative.
6332   const SCEV *Start = AddRec->getStart();
6333   ConstantRange StartRange = getRangeRef(Start, SignHint);
6334   ConstantRange EndRange = getRangeRef(End, SignHint);
6335   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6336   // If they already cover full iteration space, we will know nothing useful
6337   // even if we prove what we want to prove.
6338   if (RangeBetween.isFullSet())
6339     return RangeBetween;
6340   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6341   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6342                                : RangeBetween.isWrappedSet();
6343   if (IsWrappedSet)
6344     return ConstantRange::getFull(BitWidth);
6345 
6346   if (isKnownPositive(Step) &&
6347       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6348     return RangeBetween;
6349   else if (isKnownNegative(Step) &&
6350            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6351     return RangeBetween;
6352   return ConstantRange::getFull(BitWidth);
6353 }
6354 
6355 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6356                                                     const SCEV *Step,
6357                                                     const SCEV *MaxBECount,
6358                                                     unsigned BitWidth) {
6359   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6360   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6361 
6362   struct SelectPattern {
6363     Value *Condition = nullptr;
6364     APInt TrueValue;
6365     APInt FalseValue;
6366 
6367     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6368                            const SCEV *S) {
6369       Optional<unsigned> CastOp;
6370       APInt Offset(BitWidth, 0);
6371 
6372       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6373              "Should be!");
6374 
6375       // Peel off a constant offset:
6376       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6377         // In the future we could consider being smarter here and handle
6378         // {Start+Step,+,Step} too.
6379         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6380           return;
6381 
6382         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6383         S = SA->getOperand(1);
6384       }
6385 
6386       // Peel off a cast operation
6387       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6388         CastOp = SCast->getSCEVType();
6389         S = SCast->getOperand();
6390       }
6391 
6392       using namespace llvm::PatternMatch;
6393 
6394       auto *SU = dyn_cast<SCEVUnknown>(S);
6395       const APInt *TrueVal, *FalseVal;
6396       if (!SU ||
6397           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6398                                           m_APInt(FalseVal)))) {
6399         Condition = nullptr;
6400         return;
6401       }
6402 
6403       TrueValue = *TrueVal;
6404       FalseValue = *FalseVal;
6405 
6406       // Re-apply the cast we peeled off earlier
6407       if (CastOp.hasValue())
6408         switch (*CastOp) {
6409         default:
6410           llvm_unreachable("Unknown SCEV cast type!");
6411 
6412         case scTruncate:
6413           TrueValue = TrueValue.trunc(BitWidth);
6414           FalseValue = FalseValue.trunc(BitWidth);
6415           break;
6416         case scZeroExtend:
6417           TrueValue = TrueValue.zext(BitWidth);
6418           FalseValue = FalseValue.zext(BitWidth);
6419           break;
6420         case scSignExtend:
6421           TrueValue = TrueValue.sext(BitWidth);
6422           FalseValue = FalseValue.sext(BitWidth);
6423           break;
6424         }
6425 
6426       // Re-apply the constant offset we peeled off earlier
6427       TrueValue += Offset;
6428       FalseValue += Offset;
6429     }
6430 
6431     bool isRecognized() { return Condition != nullptr; }
6432   };
6433 
6434   SelectPattern StartPattern(*this, BitWidth, Start);
6435   if (!StartPattern.isRecognized())
6436     return ConstantRange::getFull(BitWidth);
6437 
6438   SelectPattern StepPattern(*this, BitWidth, Step);
6439   if (!StepPattern.isRecognized())
6440     return ConstantRange::getFull(BitWidth);
6441 
6442   if (StartPattern.Condition != StepPattern.Condition) {
6443     // We don't handle this case today; but we could, by considering four
6444     // possibilities below instead of two. I'm not sure if there are cases where
6445     // that will help over what getRange already does, though.
6446     return ConstantRange::getFull(BitWidth);
6447   }
6448 
6449   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6450   // construct arbitrary general SCEV expressions here.  This function is called
6451   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6452   // say) can end up caching a suboptimal value.
6453 
6454   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6455   // C2352 and C2512 (otherwise it isn't needed).
6456 
6457   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6458   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6459   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6460   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6461 
6462   ConstantRange TrueRange =
6463       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6464   ConstantRange FalseRange =
6465       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6466 
6467   return TrueRange.unionWith(FalseRange);
6468 }
6469 
6470 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6471   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6472   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6473 
6474   // Return early if there are no flags to propagate to the SCEV.
6475   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6476   if (BinOp->hasNoUnsignedWrap())
6477     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6478   if (BinOp->hasNoSignedWrap())
6479     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6480   if (Flags == SCEV::FlagAnyWrap)
6481     return SCEV::FlagAnyWrap;
6482 
6483   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6484 }
6485 
6486 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6487   // Here we check that I is in the header of the innermost loop containing I,
6488   // since we only deal with instructions in the loop header. The actual loop we
6489   // need to check later will come from an add recurrence, but getting that
6490   // requires computing the SCEV of the operands, which can be expensive. This
6491   // check we can do cheaply to rule out some cases early.
6492   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6493   if (InnermostContainingLoop == nullptr ||
6494       InnermostContainingLoop->getHeader() != I->getParent())
6495     return false;
6496 
6497   // Only proceed if we can prove that I does not yield poison.
6498   if (!programUndefinedIfPoison(I))
6499     return false;
6500 
6501   // At this point we know that if I is executed, then it does not wrap
6502   // according to at least one of NSW or NUW. If I is not executed, then we do
6503   // not know if the calculation that I represents would wrap. Multiple
6504   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6505   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6506   // derived from other instructions that map to the same SCEV. We cannot make
6507   // that guarantee for cases where I is not executed. So we need to find the
6508   // loop that I is considered in relation to and prove that I is executed for
6509   // every iteration of that loop. That implies that the value that I
6510   // calculates does not wrap anywhere in the loop, so then we can apply the
6511   // flags to the SCEV.
6512   //
6513   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6514   // from different loops, so that we know which loop to prove that I is
6515   // executed in.
6516   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6517     // I could be an extractvalue from a call to an overflow intrinsic.
6518     // TODO: We can do better here in some cases.
6519     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6520       return false;
6521     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6522     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6523       bool AllOtherOpsLoopInvariant = true;
6524       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6525            ++OtherOpIndex) {
6526         if (OtherOpIndex != OpIndex) {
6527           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6528           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6529             AllOtherOpsLoopInvariant = false;
6530             break;
6531           }
6532         }
6533       }
6534       if (AllOtherOpsLoopInvariant &&
6535           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6536         return true;
6537     }
6538   }
6539   return false;
6540 }
6541 
6542 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6543   // If we know that \c I can never be poison period, then that's enough.
6544   if (isSCEVExprNeverPoison(I))
6545     return true;
6546 
6547   // For an add recurrence specifically, we assume that infinite loops without
6548   // side effects are undefined behavior, and then reason as follows:
6549   //
6550   // If the add recurrence is poison in any iteration, it is poison on all
6551   // future iterations (since incrementing poison yields poison). If the result
6552   // of the add recurrence is fed into the loop latch condition and the loop
6553   // does not contain any throws or exiting blocks other than the latch, we now
6554   // have the ability to "choose" whether the backedge is taken or not (by
6555   // choosing a sufficiently evil value for the poison feeding into the branch)
6556   // for every iteration including and after the one in which \p I first became
6557   // poison.  There are two possibilities (let's call the iteration in which \p
6558   // I first became poison as K):
6559   //
6560   //  1. In the set of iterations including and after K, the loop body executes
6561   //     no side effects.  In this case executing the backege an infinte number
6562   //     of times will yield undefined behavior.
6563   //
6564   //  2. In the set of iterations including and after K, the loop body executes
6565   //     at least one side effect.  In this case, that specific instance of side
6566   //     effect is control dependent on poison, which also yields undefined
6567   //     behavior.
6568 
6569   auto *ExitingBB = L->getExitingBlock();
6570   auto *LatchBB = L->getLoopLatch();
6571   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6572     return false;
6573 
6574   SmallPtrSet<const Instruction *, 16> Pushed;
6575   SmallVector<const Instruction *, 8> PoisonStack;
6576 
6577   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6578   // things that are known to be poison under that assumption go on the
6579   // PoisonStack.
6580   Pushed.insert(I);
6581   PoisonStack.push_back(I);
6582 
6583   bool LatchControlDependentOnPoison = false;
6584   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6585     const Instruction *Poison = PoisonStack.pop_back_val();
6586 
6587     for (auto *PoisonUser : Poison->users()) {
6588       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6589         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6590           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6591       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6592         assert(BI->isConditional() && "Only possibility!");
6593         if (BI->getParent() == LatchBB) {
6594           LatchControlDependentOnPoison = true;
6595           break;
6596         }
6597       }
6598     }
6599   }
6600 
6601   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6602 }
6603 
6604 ScalarEvolution::LoopProperties
6605 ScalarEvolution::getLoopProperties(const Loop *L) {
6606   using LoopProperties = ScalarEvolution::LoopProperties;
6607 
6608   auto Itr = LoopPropertiesCache.find(L);
6609   if (Itr == LoopPropertiesCache.end()) {
6610     auto HasSideEffects = [](Instruction *I) {
6611       if (auto *SI = dyn_cast<StoreInst>(I))
6612         return !SI->isSimple();
6613 
6614       return I->mayHaveSideEffects();
6615     };
6616 
6617     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6618                          /*HasNoSideEffects*/ true};
6619 
6620     for (auto *BB : L->getBlocks())
6621       for (auto &I : *BB) {
6622         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6623           LP.HasNoAbnormalExits = false;
6624         if (HasSideEffects(&I))
6625           LP.HasNoSideEffects = false;
6626         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6627           break; // We're already as pessimistic as we can get.
6628       }
6629 
6630     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6631     assert(InsertPair.second && "We just checked!");
6632     Itr = InsertPair.first;
6633   }
6634 
6635   return Itr->second;
6636 }
6637 
6638 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
6639   // A mustprogress loop without side effects must be finite.
6640   // TODO: The check used here is very conservative.  It's only *specific*
6641   // side effects which are well defined in infinite loops.
6642   return isMustProgress(L) && loopHasNoSideEffects(L);
6643 }
6644 
6645 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6646   if (!isSCEVable(V->getType()))
6647     return getUnknown(V);
6648 
6649   if (Instruction *I = dyn_cast<Instruction>(V)) {
6650     // Don't attempt to analyze instructions in blocks that aren't
6651     // reachable. Such instructions don't matter, and they aren't required
6652     // to obey basic rules for definitions dominating uses which this
6653     // analysis depends on.
6654     if (!DT.isReachableFromEntry(I->getParent()))
6655       return getUnknown(UndefValue::get(V->getType()));
6656   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6657     return getConstant(CI);
6658   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6659     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6660   else if (!isa<ConstantExpr>(V))
6661     return getUnknown(V);
6662 
6663   Operator *U = cast<Operator>(V);
6664   if (auto BO = MatchBinaryOp(U, DT)) {
6665     switch (BO->Opcode) {
6666     case Instruction::Add: {
6667       // The simple thing to do would be to just call getSCEV on both operands
6668       // and call getAddExpr with the result. However if we're looking at a
6669       // bunch of things all added together, this can be quite inefficient,
6670       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6671       // Instead, gather up all the operands and make a single getAddExpr call.
6672       // LLVM IR canonical form means we need only traverse the left operands.
6673       SmallVector<const SCEV *, 4> AddOps;
6674       do {
6675         if (BO->Op) {
6676           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6677             AddOps.push_back(OpSCEV);
6678             break;
6679           }
6680 
6681           // If a NUW or NSW flag can be applied to the SCEV for this
6682           // addition, then compute the SCEV for this addition by itself
6683           // with a separate call to getAddExpr. We need to do that
6684           // instead of pushing the operands of the addition onto AddOps,
6685           // since the flags are only known to apply to this particular
6686           // addition - they may not apply to other additions that can be
6687           // formed with operands from AddOps.
6688           const SCEV *RHS = getSCEV(BO->RHS);
6689           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6690           if (Flags != SCEV::FlagAnyWrap) {
6691             const SCEV *LHS = getSCEV(BO->LHS);
6692             if (BO->Opcode == Instruction::Sub)
6693               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6694             else
6695               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6696             break;
6697           }
6698         }
6699 
6700         if (BO->Opcode == Instruction::Sub)
6701           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6702         else
6703           AddOps.push_back(getSCEV(BO->RHS));
6704 
6705         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6706         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6707                        NewBO->Opcode != Instruction::Sub)) {
6708           AddOps.push_back(getSCEV(BO->LHS));
6709           break;
6710         }
6711         BO = NewBO;
6712       } while (true);
6713 
6714       return getAddExpr(AddOps);
6715     }
6716 
6717     case Instruction::Mul: {
6718       SmallVector<const SCEV *, 4> MulOps;
6719       do {
6720         if (BO->Op) {
6721           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6722             MulOps.push_back(OpSCEV);
6723             break;
6724           }
6725 
6726           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6727           if (Flags != SCEV::FlagAnyWrap) {
6728             MulOps.push_back(
6729                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6730             break;
6731           }
6732         }
6733 
6734         MulOps.push_back(getSCEV(BO->RHS));
6735         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6736         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6737           MulOps.push_back(getSCEV(BO->LHS));
6738           break;
6739         }
6740         BO = NewBO;
6741       } while (true);
6742 
6743       return getMulExpr(MulOps);
6744     }
6745     case Instruction::UDiv:
6746       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6747     case Instruction::URem:
6748       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6749     case Instruction::Sub: {
6750       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6751       if (BO->Op)
6752         Flags = getNoWrapFlagsFromUB(BO->Op);
6753       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6754     }
6755     case Instruction::And:
6756       // For an expression like x&255 that merely masks off the high bits,
6757       // use zext(trunc(x)) as the SCEV expression.
6758       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6759         if (CI->isZero())
6760           return getSCEV(BO->RHS);
6761         if (CI->isMinusOne())
6762           return getSCEV(BO->LHS);
6763         const APInt &A = CI->getValue();
6764 
6765         // Instcombine's ShrinkDemandedConstant may strip bits out of
6766         // constants, obscuring what would otherwise be a low-bits mask.
6767         // Use computeKnownBits to compute what ShrinkDemandedConstant
6768         // knew about to reconstruct a low-bits mask value.
6769         unsigned LZ = A.countLeadingZeros();
6770         unsigned TZ = A.countTrailingZeros();
6771         unsigned BitWidth = A.getBitWidth();
6772         KnownBits Known(BitWidth);
6773         computeKnownBits(BO->LHS, Known, getDataLayout(),
6774                          0, &AC, nullptr, &DT);
6775 
6776         APInt EffectiveMask =
6777             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6778         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6779           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6780           const SCEV *LHS = getSCEV(BO->LHS);
6781           const SCEV *ShiftedLHS = nullptr;
6782           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6783             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6784               // For an expression like (x * 8) & 8, simplify the multiply.
6785               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6786               unsigned GCD = std::min(MulZeros, TZ);
6787               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6788               SmallVector<const SCEV*, 4> MulOps;
6789               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6790               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6791               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6792               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6793             }
6794           }
6795           if (!ShiftedLHS)
6796             ShiftedLHS = getUDivExpr(LHS, MulCount);
6797           return getMulExpr(
6798               getZeroExtendExpr(
6799                   getTruncateExpr(ShiftedLHS,
6800                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6801                   BO->LHS->getType()),
6802               MulCount);
6803         }
6804       }
6805       break;
6806 
6807     case Instruction::Or:
6808       // If the RHS of the Or is a constant, we may have something like:
6809       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6810       // optimizations will transparently handle this case.
6811       //
6812       // In order for this transformation to be safe, the LHS must be of the
6813       // form X*(2^n) and the Or constant must be less than 2^n.
6814       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6815         const SCEV *LHS = getSCEV(BO->LHS);
6816         const APInt &CIVal = CI->getValue();
6817         if (GetMinTrailingZeros(LHS) >=
6818             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6819           // Build a plain add SCEV.
6820           return getAddExpr(LHS, getSCEV(CI),
6821                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6822         }
6823       }
6824       break;
6825 
6826     case Instruction::Xor:
6827       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6828         // If the RHS of xor is -1, then this is a not operation.
6829         if (CI->isMinusOne())
6830           return getNotSCEV(getSCEV(BO->LHS));
6831 
6832         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6833         // This is a variant of the check for xor with -1, and it handles
6834         // the case where instcombine has trimmed non-demanded bits out
6835         // of an xor with -1.
6836         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6837           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6838             if (LBO->getOpcode() == Instruction::And &&
6839                 LCI->getValue() == CI->getValue())
6840               if (const SCEVZeroExtendExpr *Z =
6841                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6842                 Type *UTy = BO->LHS->getType();
6843                 const SCEV *Z0 = Z->getOperand();
6844                 Type *Z0Ty = Z0->getType();
6845                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6846 
6847                 // If C is a low-bits mask, the zero extend is serving to
6848                 // mask off the high bits. Complement the operand and
6849                 // re-apply the zext.
6850                 if (CI->getValue().isMask(Z0TySize))
6851                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6852 
6853                 // If C is a single bit, it may be in the sign-bit position
6854                 // before the zero-extend. In this case, represent the xor
6855                 // using an add, which is equivalent, and re-apply the zext.
6856                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6857                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6858                     Trunc.isSignMask())
6859                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6860                                            UTy);
6861               }
6862       }
6863       break;
6864 
6865     case Instruction::Shl:
6866       // Turn shift left of a constant amount into a multiply.
6867       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6868         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6869 
6870         // If the shift count is not less than the bitwidth, the result of
6871         // the shift is undefined. Don't try to analyze it, because the
6872         // resolution chosen here may differ from the resolution chosen in
6873         // other parts of the compiler.
6874         if (SA->getValue().uge(BitWidth))
6875           break;
6876 
6877         // We can safely preserve the nuw flag in all cases. It's also safe to
6878         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6879         // requires special handling. It can be preserved as long as we're not
6880         // left shifting by bitwidth - 1.
6881         auto Flags = SCEV::FlagAnyWrap;
6882         if (BO->Op) {
6883           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6884           if ((MulFlags & SCEV::FlagNSW) &&
6885               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6886             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6887           if (MulFlags & SCEV::FlagNUW)
6888             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6889         }
6890 
6891         Constant *X = ConstantInt::get(
6892             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6893         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6894       }
6895       break;
6896 
6897     case Instruction::AShr: {
6898       // AShr X, C, where C is a constant.
6899       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6900       if (!CI)
6901         break;
6902 
6903       Type *OuterTy = BO->LHS->getType();
6904       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6905       // If the shift count is not less than the bitwidth, the result of
6906       // the shift is undefined. Don't try to analyze it, because the
6907       // resolution chosen here may differ from the resolution chosen in
6908       // other parts of the compiler.
6909       if (CI->getValue().uge(BitWidth))
6910         break;
6911 
6912       if (CI->isZero())
6913         return getSCEV(BO->LHS); // shift by zero --> noop
6914 
6915       uint64_t AShrAmt = CI->getZExtValue();
6916       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6917 
6918       Operator *L = dyn_cast<Operator>(BO->LHS);
6919       if (L && L->getOpcode() == Instruction::Shl) {
6920         // X = Shl A, n
6921         // Y = AShr X, m
6922         // Both n and m are constant.
6923 
6924         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6925         if (L->getOperand(1) == BO->RHS)
6926           // For a two-shift sext-inreg, i.e. n = m,
6927           // use sext(trunc(x)) as the SCEV expression.
6928           return getSignExtendExpr(
6929               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6930 
6931         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6932         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6933           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6934           if (ShlAmt > AShrAmt) {
6935             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6936             // expression. We already checked that ShlAmt < BitWidth, so
6937             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6938             // ShlAmt - AShrAmt < Amt.
6939             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6940                                             ShlAmt - AShrAmt);
6941             return getSignExtendExpr(
6942                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6943                 getConstant(Mul)), OuterTy);
6944           }
6945         }
6946       }
6947       break;
6948     }
6949     }
6950   }
6951 
6952   switch (U->getOpcode()) {
6953   case Instruction::Trunc:
6954     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6955 
6956   case Instruction::ZExt:
6957     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6958 
6959   case Instruction::SExt:
6960     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6961       // The NSW flag of a subtract does not always survive the conversion to
6962       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6963       // more likely to preserve NSW and allow later AddRec optimisations.
6964       //
6965       // NOTE: This is effectively duplicating this logic from getSignExtend:
6966       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6967       // but by that point the NSW information has potentially been lost.
6968       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6969         Type *Ty = U->getType();
6970         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6971         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6972         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6973       }
6974     }
6975     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6976 
6977   case Instruction::BitCast:
6978     // BitCasts are no-op casts so we just eliminate the cast.
6979     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6980       return getSCEV(U->getOperand(0));
6981     break;
6982 
6983   case Instruction::PtrToInt: {
6984     // Pointer to integer cast is straight-forward, so do model it.
6985     const SCEV *Op = getSCEV(U->getOperand(0));
6986     Type *DstIntTy = U->getType();
6987     // But only if effective SCEV (integer) type is wide enough to represent
6988     // all possible pointer values.
6989     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
6990     if (isa<SCEVCouldNotCompute>(IntOp))
6991       return getUnknown(V);
6992     return IntOp;
6993   }
6994   case Instruction::IntToPtr:
6995     // Just don't deal with inttoptr casts.
6996     return getUnknown(V);
6997 
6998   case Instruction::SDiv:
6999     // If both operands are non-negative, this is just an udiv.
7000     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7001         isKnownNonNegative(getSCEV(U->getOperand(1))))
7002       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7003     break;
7004 
7005   case Instruction::SRem:
7006     // If both operands are non-negative, this is just an urem.
7007     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7008         isKnownNonNegative(getSCEV(U->getOperand(1))))
7009       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7010     break;
7011 
7012   case Instruction::GetElementPtr:
7013     return createNodeForGEP(cast<GEPOperator>(U));
7014 
7015   case Instruction::PHI:
7016     return createNodeForPHI(cast<PHINode>(U));
7017 
7018   case Instruction::Select:
7019     // U can also be a select constant expr, which let fall through.  Since
7020     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
7021     // constant expressions cannot have instructions as operands, we'd have
7022     // returned getUnknown for a select constant expressions anyway.
7023     if (isa<Instruction>(U))
7024       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
7025                                       U->getOperand(1), U->getOperand(2));
7026     break;
7027 
7028   case Instruction::Call:
7029   case Instruction::Invoke:
7030     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7031       return getSCEV(RV);
7032 
7033     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7034       switch (II->getIntrinsicID()) {
7035       case Intrinsic::abs:
7036         return getAbsExpr(
7037             getSCEV(II->getArgOperand(0)),
7038             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7039       case Intrinsic::umax:
7040         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7041                            getSCEV(II->getArgOperand(1)));
7042       case Intrinsic::umin:
7043         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7044                            getSCEV(II->getArgOperand(1)));
7045       case Intrinsic::smax:
7046         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7047                            getSCEV(II->getArgOperand(1)));
7048       case Intrinsic::smin:
7049         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7050                            getSCEV(II->getArgOperand(1)));
7051       case Intrinsic::usub_sat: {
7052         const SCEV *X = getSCEV(II->getArgOperand(0));
7053         const SCEV *Y = getSCEV(II->getArgOperand(1));
7054         const SCEV *ClampedY = getUMinExpr(X, Y);
7055         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7056       }
7057       case Intrinsic::uadd_sat: {
7058         const SCEV *X = getSCEV(II->getArgOperand(0));
7059         const SCEV *Y = getSCEV(II->getArgOperand(1));
7060         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7061         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7062       }
7063       case Intrinsic::start_loop_iterations:
7064         // A start_loop_iterations is just equivalent to the first operand for
7065         // SCEV purposes.
7066         return getSCEV(II->getArgOperand(0));
7067       default:
7068         break;
7069       }
7070     }
7071     break;
7072   }
7073 
7074   return getUnknown(V);
7075 }
7076 
7077 //===----------------------------------------------------------------------===//
7078 //                   Iteration Count Computation Code
7079 //
7080 
7081 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
7082   // Get the trip count from the BE count by adding 1.  Overflow, results
7083   // in zero which means "unknown".
7084   return getAddExpr(ExitCount, getOne(ExitCount->getType()));
7085 }
7086 
7087 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7088   if (!ExitCount)
7089     return 0;
7090 
7091   ConstantInt *ExitConst = ExitCount->getValue();
7092 
7093   // Guard against huge trip counts.
7094   if (ExitConst->getValue().getActiveBits() > 32)
7095     return 0;
7096 
7097   // In case of integer overflow, this returns 0, which is correct.
7098   return ((unsigned)ExitConst->getZExtValue()) + 1;
7099 }
7100 
7101 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7102   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7103   return getConstantTripCount(ExitCount);
7104 }
7105 
7106 unsigned
7107 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7108                                            const BasicBlock *ExitingBlock) {
7109   assert(ExitingBlock && "Must pass a non-null exiting block!");
7110   assert(L->isLoopExiting(ExitingBlock) &&
7111          "Exiting block must actually branch out of the loop!");
7112   const SCEVConstant *ExitCount =
7113       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7114   return getConstantTripCount(ExitCount);
7115 }
7116 
7117 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7118   const auto *MaxExitCount =
7119       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7120   return getConstantTripCount(MaxExitCount);
7121 }
7122 
7123 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7124   SmallVector<BasicBlock *, 8> ExitingBlocks;
7125   L->getExitingBlocks(ExitingBlocks);
7126 
7127   Optional<unsigned> Res = None;
7128   for (auto *ExitingBB : ExitingBlocks) {
7129     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7130     if (!Res)
7131       Res = Multiple;
7132     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7133   }
7134   return Res.getValueOr(1);
7135 }
7136 
7137 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7138                                                        const SCEV *ExitCount) {
7139   if (ExitCount == getCouldNotCompute())
7140     return 1;
7141 
7142   // Get the trip count
7143   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7144 
7145   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7146   if (!TC)
7147     // Attempt to factor more general cases. Returns the greatest power of
7148     // two divisor. If overflow happens, the trip count expression is still
7149     // divisible by the greatest power of 2 divisor returned.
7150     return 1U << std::min((uint32_t)31,
7151                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7152 
7153   ConstantInt *Result = TC->getValue();
7154 
7155   // Guard against huge trip counts (this requires checking
7156   // for zero to handle the case where the trip count == -1 and the
7157   // addition wraps).
7158   if (!Result || Result->getValue().getActiveBits() > 32 ||
7159       Result->getValue().getActiveBits() == 0)
7160     return 1;
7161 
7162   return (unsigned)Result->getZExtValue();
7163 }
7164 
7165 /// Returns the largest constant divisor of the trip count of this loop as a
7166 /// normal unsigned value, if possible. This means that the actual trip count is
7167 /// always a multiple of the returned value (don't forget the trip count could
7168 /// very well be zero as well!).
7169 ///
7170 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7171 /// multiple of a constant (which is also the case if the trip count is simply
7172 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7173 /// if the trip count is very large (>= 2^32).
7174 ///
7175 /// As explained in the comments for getSmallConstantTripCount, this assumes
7176 /// that control exits the loop via ExitingBlock.
7177 unsigned
7178 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7179                                               const BasicBlock *ExitingBlock) {
7180   assert(ExitingBlock && "Must pass a non-null exiting block!");
7181   assert(L->isLoopExiting(ExitingBlock) &&
7182          "Exiting block must actually branch out of the loop!");
7183   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7184   return getSmallConstantTripMultiple(L, ExitCount);
7185 }
7186 
7187 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7188                                           const BasicBlock *ExitingBlock,
7189                                           ExitCountKind Kind) {
7190   switch (Kind) {
7191   case Exact:
7192   case SymbolicMaximum:
7193     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7194   case ConstantMaximum:
7195     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7196   };
7197   llvm_unreachable("Invalid ExitCountKind!");
7198 }
7199 
7200 const SCEV *
7201 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7202                                                  SCEVUnionPredicate &Preds) {
7203   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7204 }
7205 
7206 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7207                                                    ExitCountKind Kind) {
7208   switch (Kind) {
7209   case Exact:
7210     return getBackedgeTakenInfo(L).getExact(L, this);
7211   case ConstantMaximum:
7212     return getBackedgeTakenInfo(L).getConstantMax(this);
7213   case SymbolicMaximum:
7214     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7215   };
7216   llvm_unreachable("Invalid ExitCountKind!");
7217 }
7218 
7219 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7220   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7221 }
7222 
7223 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7224 static void
7225 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
7226   BasicBlock *Header = L->getHeader();
7227 
7228   // Push all Loop-header PHIs onto the Worklist stack.
7229   for (PHINode &PN : Header->phis())
7230     Worklist.push_back(&PN);
7231 }
7232 
7233 const ScalarEvolution::BackedgeTakenInfo &
7234 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7235   auto &BTI = getBackedgeTakenInfo(L);
7236   if (BTI.hasFullInfo())
7237     return BTI;
7238 
7239   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7240 
7241   if (!Pair.second)
7242     return Pair.first->second;
7243 
7244   BackedgeTakenInfo Result =
7245       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7246 
7247   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7248 }
7249 
7250 ScalarEvolution::BackedgeTakenInfo &
7251 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7252   // Initially insert an invalid entry for this loop. If the insertion
7253   // succeeds, proceed to actually compute a backedge-taken count and
7254   // update the value. The temporary CouldNotCompute value tells SCEV
7255   // code elsewhere that it shouldn't attempt to request a new
7256   // backedge-taken count, which could result in infinite recursion.
7257   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7258       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7259   if (!Pair.second)
7260     return Pair.first->second;
7261 
7262   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7263   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7264   // must be cleared in this scope.
7265   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7266 
7267   // In product build, there are no usage of statistic.
7268   (void)NumTripCountsComputed;
7269   (void)NumTripCountsNotComputed;
7270 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7271   const SCEV *BEExact = Result.getExact(L, this);
7272   if (BEExact != getCouldNotCompute()) {
7273     assert(isLoopInvariant(BEExact, L) &&
7274            isLoopInvariant(Result.getConstantMax(this), L) &&
7275            "Computed backedge-taken count isn't loop invariant for loop!");
7276     ++NumTripCountsComputed;
7277   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7278              isa<PHINode>(L->getHeader()->begin())) {
7279     // Only count loops that have phi nodes as not being computable.
7280     ++NumTripCountsNotComputed;
7281   }
7282 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7283 
7284   // Now that we know more about the trip count for this loop, forget any
7285   // existing SCEV values for PHI nodes in this loop since they are only
7286   // conservative estimates made without the benefit of trip count
7287   // information. This is similar to the code in forgetLoop, except that
7288   // it handles SCEVUnknown PHI nodes specially.
7289   if (Result.hasAnyInfo()) {
7290     SmallVector<Instruction *, 16> Worklist;
7291     PushLoopPHIs(L, Worklist);
7292 
7293     SmallPtrSet<Instruction *, 8> Discovered;
7294     while (!Worklist.empty()) {
7295       Instruction *I = Worklist.pop_back_val();
7296 
7297       ValueExprMapType::iterator It =
7298         ValueExprMap.find_as(static_cast<Value *>(I));
7299       if (It != ValueExprMap.end()) {
7300         const SCEV *Old = It->second;
7301 
7302         // SCEVUnknown for a PHI either means that it has an unrecognized
7303         // structure, or it's a PHI that's in the progress of being computed
7304         // by createNodeForPHI.  In the former case, additional loop trip
7305         // count information isn't going to change anything. In the later
7306         // case, createNodeForPHI will perform the necessary updates on its
7307         // own when it gets to that point.
7308         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7309           eraseValueFromMap(It->first);
7310           forgetMemoizedResults(Old);
7311         }
7312         if (PHINode *PN = dyn_cast<PHINode>(I))
7313           ConstantEvolutionLoopExitValue.erase(PN);
7314       }
7315 
7316       // Since we don't need to invalidate anything for correctness and we're
7317       // only invalidating to make SCEV's results more precise, we get to stop
7318       // early to avoid invalidating too much.  This is especially important in
7319       // cases like:
7320       //
7321       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7322       // loop0:
7323       //   %pn0 = phi
7324       //   ...
7325       // loop1:
7326       //   %pn1 = phi
7327       //   ...
7328       //
7329       // where both loop0 and loop1's backedge taken count uses the SCEV
7330       // expression for %v.  If we don't have the early stop below then in cases
7331       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7332       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7333       // count for loop1, effectively nullifying SCEV's trip count cache.
7334       for (auto *U : I->users())
7335         if (auto *I = dyn_cast<Instruction>(U)) {
7336           auto *LoopForUser = LI.getLoopFor(I->getParent());
7337           if (LoopForUser && L->contains(LoopForUser) &&
7338               Discovered.insert(I).second)
7339             Worklist.push_back(I);
7340         }
7341     }
7342   }
7343 
7344   // Re-lookup the insert position, since the call to
7345   // computeBackedgeTakenCount above could result in a
7346   // recusive call to getBackedgeTakenInfo (on a different
7347   // loop), which would invalidate the iterator computed
7348   // earlier.
7349   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7350 }
7351 
7352 void ScalarEvolution::forgetAllLoops() {
7353   // This method is intended to forget all info about loops. It should
7354   // invalidate caches as if the following happened:
7355   // - The trip counts of all loops have changed arbitrarily
7356   // - Every llvm::Value has been updated in place to produce a different
7357   // result.
7358   BackedgeTakenCounts.clear();
7359   PredicatedBackedgeTakenCounts.clear();
7360   LoopPropertiesCache.clear();
7361   ConstantEvolutionLoopExitValue.clear();
7362   ValueExprMap.clear();
7363   ValuesAtScopes.clear();
7364   LoopDispositions.clear();
7365   BlockDispositions.clear();
7366   UnsignedRanges.clear();
7367   SignedRanges.clear();
7368   ExprValueMap.clear();
7369   HasRecMap.clear();
7370   MinTrailingZerosCache.clear();
7371   PredicatedSCEVRewrites.clear();
7372 }
7373 
7374 void ScalarEvolution::forgetLoop(const Loop *L) {
7375   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7376   SmallVector<Instruction *, 32> Worklist;
7377   SmallPtrSet<Instruction *, 16> Visited;
7378 
7379   // Iterate over all the loops and sub-loops to drop SCEV information.
7380   while (!LoopWorklist.empty()) {
7381     auto *CurrL = LoopWorklist.pop_back_val();
7382 
7383     // Drop any stored trip count value.
7384     BackedgeTakenCounts.erase(CurrL);
7385     PredicatedBackedgeTakenCounts.erase(CurrL);
7386 
7387     // Drop information about predicated SCEV rewrites for this loop.
7388     for (auto I = PredicatedSCEVRewrites.begin();
7389          I != PredicatedSCEVRewrites.end();) {
7390       std::pair<const SCEV *, const Loop *> Entry = I->first;
7391       if (Entry.second == CurrL)
7392         PredicatedSCEVRewrites.erase(I++);
7393       else
7394         ++I;
7395     }
7396 
7397     auto LoopUsersItr = LoopUsers.find(CurrL);
7398     if (LoopUsersItr != LoopUsers.end()) {
7399       for (auto *S : LoopUsersItr->second)
7400         forgetMemoizedResults(S);
7401       LoopUsers.erase(LoopUsersItr);
7402     }
7403 
7404     // Drop information about expressions based on loop-header PHIs.
7405     PushLoopPHIs(CurrL, Worklist);
7406 
7407     while (!Worklist.empty()) {
7408       Instruction *I = Worklist.pop_back_val();
7409       if (!Visited.insert(I).second)
7410         continue;
7411 
7412       ValueExprMapType::iterator It =
7413           ValueExprMap.find_as(static_cast<Value *>(I));
7414       if (It != ValueExprMap.end()) {
7415         eraseValueFromMap(It->first);
7416         forgetMemoizedResults(It->second);
7417         if (PHINode *PN = dyn_cast<PHINode>(I))
7418           ConstantEvolutionLoopExitValue.erase(PN);
7419       }
7420 
7421       PushDefUseChildren(I, Worklist);
7422     }
7423 
7424     LoopPropertiesCache.erase(CurrL);
7425     // Forget all contained loops too, to avoid dangling entries in the
7426     // ValuesAtScopes map.
7427     LoopWorklist.append(CurrL->begin(), CurrL->end());
7428   }
7429 }
7430 
7431 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7432   while (Loop *Parent = L->getParentLoop())
7433     L = Parent;
7434   forgetLoop(L);
7435 }
7436 
7437 void ScalarEvolution::forgetValue(Value *V) {
7438   Instruction *I = dyn_cast<Instruction>(V);
7439   if (!I) return;
7440 
7441   // Drop information about expressions based on loop-header PHIs.
7442   SmallVector<Instruction *, 16> Worklist;
7443   Worklist.push_back(I);
7444 
7445   SmallPtrSet<Instruction *, 8> Visited;
7446   while (!Worklist.empty()) {
7447     I = Worklist.pop_back_val();
7448     if (!Visited.insert(I).second)
7449       continue;
7450 
7451     ValueExprMapType::iterator It =
7452       ValueExprMap.find_as(static_cast<Value *>(I));
7453     if (It != ValueExprMap.end()) {
7454       eraseValueFromMap(It->first);
7455       forgetMemoizedResults(It->second);
7456       if (PHINode *PN = dyn_cast<PHINode>(I))
7457         ConstantEvolutionLoopExitValue.erase(PN);
7458     }
7459 
7460     PushDefUseChildren(I, Worklist);
7461   }
7462 }
7463 
7464 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7465   LoopDispositions.clear();
7466 }
7467 
7468 /// Get the exact loop backedge taken count considering all loop exits. A
7469 /// computable result can only be returned for loops with all exiting blocks
7470 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7471 /// is never skipped. This is a valid assumption as long as the loop exits via
7472 /// that test. For precise results, it is the caller's responsibility to specify
7473 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7474 const SCEV *
7475 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7476                                              SCEVUnionPredicate *Preds) const {
7477   // If any exits were not computable, the loop is not computable.
7478   if (!isComplete() || ExitNotTaken.empty())
7479     return SE->getCouldNotCompute();
7480 
7481   const BasicBlock *Latch = L->getLoopLatch();
7482   // All exiting blocks we have collected must dominate the only backedge.
7483   if (!Latch)
7484     return SE->getCouldNotCompute();
7485 
7486   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7487   // count is simply a minimum out of all these calculated exit counts.
7488   SmallVector<const SCEV *, 2> Ops;
7489   for (auto &ENT : ExitNotTaken) {
7490     const SCEV *BECount = ENT.ExactNotTaken;
7491     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7492     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7493            "We should only have known counts for exiting blocks that dominate "
7494            "latch!");
7495 
7496     Ops.push_back(BECount);
7497 
7498     if (Preds && !ENT.hasAlwaysTruePredicate())
7499       Preds->add(ENT.Predicate.get());
7500 
7501     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7502            "Predicate should be always true!");
7503   }
7504 
7505   return SE->getUMinFromMismatchedTypes(Ops);
7506 }
7507 
7508 /// Get the exact not taken count for this loop exit.
7509 const SCEV *
7510 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7511                                              ScalarEvolution *SE) const {
7512   for (auto &ENT : ExitNotTaken)
7513     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7514       return ENT.ExactNotTaken;
7515 
7516   return SE->getCouldNotCompute();
7517 }
7518 
7519 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7520     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7521   for (auto &ENT : ExitNotTaken)
7522     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7523       return ENT.MaxNotTaken;
7524 
7525   return SE->getCouldNotCompute();
7526 }
7527 
7528 /// getConstantMax - Get the constant max backedge taken count for the loop.
7529 const SCEV *
7530 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7531   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7532     return !ENT.hasAlwaysTruePredicate();
7533   };
7534 
7535   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7536     return SE->getCouldNotCompute();
7537 
7538   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7539           isa<SCEVConstant>(getConstantMax())) &&
7540          "No point in having a non-constant max backedge taken count!");
7541   return getConstantMax();
7542 }
7543 
7544 const SCEV *
7545 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7546                                                    ScalarEvolution *SE) {
7547   if (!SymbolicMax)
7548     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7549   return SymbolicMax;
7550 }
7551 
7552 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7553     ScalarEvolution *SE) const {
7554   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7555     return !ENT.hasAlwaysTruePredicate();
7556   };
7557   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7558 }
7559 
7560 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const {
7561   return Operands.contains(S);
7562 }
7563 
7564 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7565     : ExitLimit(E, E, false, None) {
7566 }
7567 
7568 ScalarEvolution::ExitLimit::ExitLimit(
7569     const SCEV *E, const SCEV *M, bool MaxOrZero,
7570     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7571     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7572   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7573           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7574          "Exact is not allowed to be less precise than Max");
7575   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7576           isa<SCEVConstant>(MaxNotTaken)) &&
7577          "No point in having a non-constant max backedge taken count!");
7578   for (auto *PredSet : PredSetList)
7579     for (auto *P : *PredSet)
7580       addPredicate(P);
7581   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
7582          "Backedge count should be int");
7583   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
7584          "Max backedge count should be int");
7585 }
7586 
7587 ScalarEvolution::ExitLimit::ExitLimit(
7588     const SCEV *E, const SCEV *M, bool MaxOrZero,
7589     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7590     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7591 }
7592 
7593 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7594                                       bool MaxOrZero)
7595     : ExitLimit(E, M, MaxOrZero, None) {
7596 }
7597 
7598 class SCEVRecordOperands {
7599   SmallPtrSetImpl<const SCEV *> &Operands;
7600 
7601 public:
7602   SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands)
7603     : Operands(Operands) {}
7604   bool follow(const SCEV *S) {
7605     Operands.insert(S);
7606     return true;
7607   }
7608   bool isDone() { return false; }
7609 };
7610 
7611 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7612 /// computable exit into a persistent ExitNotTakenInfo array.
7613 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7614     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7615     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7616     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7617   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7618 
7619   ExitNotTaken.reserve(ExitCounts.size());
7620   std::transform(
7621       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7622       [&](const EdgeExitInfo &EEI) {
7623         BasicBlock *ExitBB = EEI.first;
7624         const ExitLimit &EL = EEI.second;
7625         if (EL.Predicates.empty())
7626           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7627                                   nullptr);
7628 
7629         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7630         for (auto *Pred : EL.Predicates)
7631           Predicate->add(Pred);
7632 
7633         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7634                                 std::move(Predicate));
7635       });
7636   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7637           isa<SCEVConstant>(ConstantMax)) &&
7638          "No point in having a non-constant max backedge taken count!");
7639 
7640   SCEVRecordOperands RecordOperands(Operands);
7641   SCEVTraversal<SCEVRecordOperands> ST(RecordOperands);
7642   if (!isa<SCEVCouldNotCompute>(ConstantMax))
7643     ST.visitAll(ConstantMax);
7644   for (auto &ENT : ExitNotTaken)
7645     if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken))
7646       ST.visitAll(ENT.ExactNotTaken);
7647 }
7648 
7649 /// Compute the number of times the backedge of the specified loop will execute.
7650 ScalarEvolution::BackedgeTakenInfo
7651 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7652                                            bool AllowPredicates) {
7653   SmallVector<BasicBlock *, 8> ExitingBlocks;
7654   L->getExitingBlocks(ExitingBlocks);
7655 
7656   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7657 
7658   SmallVector<EdgeExitInfo, 4> ExitCounts;
7659   bool CouldComputeBECount = true;
7660   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7661   const SCEV *MustExitMaxBECount = nullptr;
7662   const SCEV *MayExitMaxBECount = nullptr;
7663   bool MustExitMaxOrZero = false;
7664 
7665   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7666   // and compute maxBECount.
7667   // Do a union of all the predicates here.
7668   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7669     BasicBlock *ExitBB = ExitingBlocks[i];
7670 
7671     // We canonicalize untaken exits to br (constant), ignore them so that
7672     // proving an exit untaken doesn't negatively impact our ability to reason
7673     // about the loop as whole.
7674     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7675       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7676         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7677         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7678           continue;
7679       }
7680 
7681     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7682 
7683     assert((AllowPredicates || EL.Predicates.empty()) &&
7684            "Predicated exit limit when predicates are not allowed!");
7685 
7686     // 1. For each exit that can be computed, add an entry to ExitCounts.
7687     // CouldComputeBECount is true only if all exits can be computed.
7688     if (EL.ExactNotTaken == getCouldNotCompute())
7689       // We couldn't compute an exact value for this exit, so
7690       // we won't be able to compute an exact value for the loop.
7691       CouldComputeBECount = false;
7692     else
7693       ExitCounts.emplace_back(ExitBB, EL);
7694 
7695     // 2. Derive the loop's MaxBECount from each exit's max number of
7696     // non-exiting iterations. Partition the loop exits into two kinds:
7697     // LoopMustExits and LoopMayExits.
7698     //
7699     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7700     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7701     // MaxBECount is the minimum EL.MaxNotTaken of computable
7702     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7703     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7704     // computable EL.MaxNotTaken.
7705     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7706         DT.dominates(ExitBB, Latch)) {
7707       if (!MustExitMaxBECount) {
7708         MustExitMaxBECount = EL.MaxNotTaken;
7709         MustExitMaxOrZero = EL.MaxOrZero;
7710       } else {
7711         MustExitMaxBECount =
7712             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7713       }
7714     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7715       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7716         MayExitMaxBECount = EL.MaxNotTaken;
7717       else {
7718         MayExitMaxBECount =
7719             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7720       }
7721     }
7722   }
7723   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7724     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7725   // The loop backedge will be taken the maximum or zero times if there's
7726   // a single exit that must be taken the maximum or zero times.
7727   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7728   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7729                            MaxBECount, MaxOrZero);
7730 }
7731 
7732 ScalarEvolution::ExitLimit
7733 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7734                                       bool AllowPredicates) {
7735   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7736   // If our exiting block does not dominate the latch, then its connection with
7737   // loop's exit limit may be far from trivial.
7738   const BasicBlock *Latch = L->getLoopLatch();
7739   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7740     return getCouldNotCompute();
7741 
7742   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7743   Instruction *Term = ExitingBlock->getTerminator();
7744   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7745     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7746     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7747     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7748            "It should have one successor in loop and one exit block!");
7749     // Proceed to the next level to examine the exit condition expression.
7750     return computeExitLimitFromCond(
7751         L, BI->getCondition(), ExitIfTrue,
7752         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7753   }
7754 
7755   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7756     // For switch, make sure that there is a single exit from the loop.
7757     BasicBlock *Exit = nullptr;
7758     for (auto *SBB : successors(ExitingBlock))
7759       if (!L->contains(SBB)) {
7760         if (Exit) // Multiple exit successors.
7761           return getCouldNotCompute();
7762         Exit = SBB;
7763       }
7764     assert(Exit && "Exiting block must have at least one exit");
7765     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7766                                                 /*ControlsExit=*/IsOnlyExit);
7767   }
7768 
7769   return getCouldNotCompute();
7770 }
7771 
7772 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7773     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7774     bool ControlsExit, bool AllowPredicates) {
7775   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7776   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7777                                         ControlsExit, AllowPredicates);
7778 }
7779 
7780 Optional<ScalarEvolution::ExitLimit>
7781 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7782                                       bool ExitIfTrue, bool ControlsExit,
7783                                       bool AllowPredicates) {
7784   (void)this->L;
7785   (void)this->ExitIfTrue;
7786   (void)this->AllowPredicates;
7787 
7788   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7789          this->AllowPredicates == AllowPredicates &&
7790          "Variance in assumed invariant key components!");
7791   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7792   if (Itr == TripCountMap.end())
7793     return None;
7794   return Itr->second;
7795 }
7796 
7797 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7798                                              bool ExitIfTrue,
7799                                              bool ControlsExit,
7800                                              bool AllowPredicates,
7801                                              const ExitLimit &EL) {
7802   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7803          this->AllowPredicates == AllowPredicates &&
7804          "Variance in assumed invariant key components!");
7805 
7806   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7807   assert(InsertResult.second && "Expected successful insertion!");
7808   (void)InsertResult;
7809   (void)ExitIfTrue;
7810 }
7811 
7812 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7813     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7814     bool ControlsExit, bool AllowPredicates) {
7815 
7816   if (auto MaybeEL =
7817           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7818     return *MaybeEL;
7819 
7820   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7821                                               ControlsExit, AllowPredicates);
7822   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7823   return EL;
7824 }
7825 
7826 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7827     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7828     bool ControlsExit, bool AllowPredicates) {
7829   // Handle BinOp conditions (And, Or).
7830   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7831           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7832     return *LimitFromBinOp;
7833 
7834   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7835   // Proceed to the next level to examine the icmp.
7836   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7837     ExitLimit EL =
7838         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7839     if (EL.hasFullInfo() || !AllowPredicates)
7840       return EL;
7841 
7842     // Try again, but use SCEV predicates this time.
7843     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7844                                     /*AllowPredicates=*/true);
7845   }
7846 
7847   // Check for a constant condition. These are normally stripped out by
7848   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7849   // preserve the CFG and is temporarily leaving constant conditions
7850   // in place.
7851   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7852     if (ExitIfTrue == !CI->getZExtValue())
7853       // The backedge is always taken.
7854       return getCouldNotCompute();
7855     else
7856       // The backedge is never taken.
7857       return getZero(CI->getType());
7858   }
7859 
7860   // If it's not an integer or pointer comparison then compute it the hard way.
7861   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7862 }
7863 
7864 Optional<ScalarEvolution::ExitLimit>
7865 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7866     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7867     bool ControlsExit, bool AllowPredicates) {
7868   // Check if the controlling expression for this loop is an And or Or.
7869   Value *Op0, *Op1;
7870   bool IsAnd = false;
7871   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7872     IsAnd = true;
7873   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7874     IsAnd = false;
7875   else
7876     return None;
7877 
7878   // EitherMayExit is true in these two cases:
7879   //   br (and Op0 Op1), loop, exit
7880   //   br (or  Op0 Op1), exit, loop
7881   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7882   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7883                                                  ControlsExit && !EitherMayExit,
7884                                                  AllowPredicates);
7885   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7886                                                  ControlsExit && !EitherMayExit,
7887                                                  AllowPredicates);
7888 
7889   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7890   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7891   if (isa<ConstantInt>(Op1))
7892     return Op1 == NeutralElement ? EL0 : EL1;
7893   if (isa<ConstantInt>(Op0))
7894     return Op0 == NeutralElement ? EL1 : EL0;
7895 
7896   const SCEV *BECount = getCouldNotCompute();
7897   const SCEV *MaxBECount = getCouldNotCompute();
7898   if (EitherMayExit) {
7899     // Both conditions must be same for the loop to continue executing.
7900     // Choose the less conservative count.
7901     // If ExitCond is a short-circuit form (select), using
7902     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7903     // To see the detailed examples, please see
7904     // test/Analysis/ScalarEvolution/exit-count-select.ll
7905     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7906     if (!PoisonSafe)
7907       // Even if ExitCond is select, we can safely derive BECount using both
7908       // EL0 and EL1 in these cases:
7909       // (1) EL0.ExactNotTaken is non-zero
7910       // (2) EL1.ExactNotTaken is non-poison
7911       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7912       //     it cannot be umin(0, ..))
7913       // The PoisonSafe assignment below is simplified and the assertion after
7914       // BECount calculation fully guarantees the condition (3).
7915       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7916                    isa<SCEVConstant>(EL1.ExactNotTaken);
7917     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7918         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7919       BECount =
7920           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7921 
7922       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7923       // it should have been simplified to zero (see the condition (3) above)
7924       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7925              BECount->isZero());
7926     }
7927     if (EL0.MaxNotTaken == getCouldNotCompute())
7928       MaxBECount = EL1.MaxNotTaken;
7929     else if (EL1.MaxNotTaken == getCouldNotCompute())
7930       MaxBECount = EL0.MaxNotTaken;
7931     else
7932       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7933   } else {
7934     // Both conditions must be same at the same time for the loop to exit.
7935     // For now, be conservative.
7936     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7937       BECount = EL0.ExactNotTaken;
7938   }
7939 
7940   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7941   // to be more aggressive when computing BECount than when computing
7942   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7943   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7944   // to not.
7945   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7946       !isa<SCEVCouldNotCompute>(BECount))
7947     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7948 
7949   return ExitLimit(BECount, MaxBECount, false,
7950                    { &EL0.Predicates, &EL1.Predicates });
7951 }
7952 
7953 ScalarEvolution::ExitLimit
7954 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7955                                           ICmpInst *ExitCond,
7956                                           bool ExitIfTrue,
7957                                           bool ControlsExit,
7958                                           bool AllowPredicates) {
7959   // If the condition was exit on true, convert the condition to exit on false
7960   ICmpInst::Predicate Pred;
7961   if (!ExitIfTrue)
7962     Pred = ExitCond->getPredicate();
7963   else
7964     Pred = ExitCond->getInversePredicate();
7965   const ICmpInst::Predicate OriginalPred = Pred;
7966 
7967   // Handle common loops like: for (X = "string"; *X; ++X)
7968   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7969     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7970       ExitLimit ItCnt =
7971         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7972       if (ItCnt.hasAnyInfo())
7973         return ItCnt;
7974     }
7975 
7976   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7977   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7978 
7979   // Try to evaluate any dependencies out of the loop.
7980   LHS = getSCEVAtScope(LHS, L);
7981   RHS = getSCEVAtScope(RHS, L);
7982 
7983   // At this point, we would like to compute how many iterations of the
7984   // loop the predicate will return true for these inputs.
7985   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7986     // If there is a loop-invariant, force it into the RHS.
7987     std::swap(LHS, RHS);
7988     Pred = ICmpInst::getSwappedPredicate(Pred);
7989   }
7990 
7991   // Simplify the operands before analyzing them.
7992   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7993 
7994   // If we have a comparison of a chrec against a constant, try to use value
7995   // ranges to answer this query.
7996   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7997     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7998       if (AddRec->getLoop() == L) {
7999         // Form the constant range.
8000         ConstantRange CompRange =
8001             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8002 
8003         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8004         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8005       }
8006 
8007   switch (Pred) {
8008   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8009     // Convert to: while (X-Y != 0)
8010     if (LHS->getType()->isPointerTy()) {
8011       LHS = getLosslessPtrToIntExpr(LHS);
8012       if (isa<SCEVCouldNotCompute>(LHS))
8013         return LHS;
8014     }
8015     if (RHS->getType()->isPointerTy()) {
8016       RHS = getLosslessPtrToIntExpr(RHS);
8017       if (isa<SCEVCouldNotCompute>(RHS))
8018         return RHS;
8019     }
8020     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8021                                 AllowPredicates);
8022     if (EL.hasAnyInfo()) return EL;
8023     break;
8024   }
8025   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8026     // Convert to: while (X-Y == 0)
8027     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8028     if (EL.hasAnyInfo()) return EL;
8029     break;
8030   }
8031   case ICmpInst::ICMP_SLT:
8032   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8033     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8034     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8035                                     AllowPredicates);
8036     if (EL.hasAnyInfo()) return EL;
8037     break;
8038   }
8039   case ICmpInst::ICMP_SGT:
8040   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8041     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8042     ExitLimit EL =
8043         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8044                             AllowPredicates);
8045     if (EL.hasAnyInfo()) return EL;
8046     break;
8047   }
8048   default:
8049     break;
8050   }
8051 
8052   auto *ExhaustiveCount =
8053       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8054 
8055   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8056     return ExhaustiveCount;
8057 
8058   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8059                                       ExitCond->getOperand(1), L, OriginalPred);
8060 }
8061 
8062 ScalarEvolution::ExitLimit
8063 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8064                                                       SwitchInst *Switch,
8065                                                       BasicBlock *ExitingBlock,
8066                                                       bool ControlsExit) {
8067   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8068 
8069   // Give up if the exit is the default dest of a switch.
8070   if (Switch->getDefaultDest() == ExitingBlock)
8071     return getCouldNotCompute();
8072 
8073   assert(L->contains(Switch->getDefaultDest()) &&
8074          "Default case must not exit the loop!");
8075   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8076   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8077 
8078   // while (X != Y) --> while (X-Y != 0)
8079   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8080   if (EL.hasAnyInfo())
8081     return EL;
8082 
8083   return getCouldNotCompute();
8084 }
8085 
8086 static ConstantInt *
8087 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8088                                 ScalarEvolution &SE) {
8089   const SCEV *InVal = SE.getConstant(C);
8090   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8091   assert(isa<SCEVConstant>(Val) &&
8092          "Evaluation of SCEV at constant didn't fold correctly?");
8093   return cast<SCEVConstant>(Val)->getValue();
8094 }
8095 
8096 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
8097 /// compute the backedge execution count.
8098 ScalarEvolution::ExitLimit
8099 ScalarEvolution::computeLoadConstantCompareExitLimit(
8100   LoadInst *LI,
8101   Constant *RHS,
8102   const Loop *L,
8103   ICmpInst::Predicate predicate) {
8104   if (LI->isVolatile()) return getCouldNotCompute();
8105 
8106   // Check to see if the loaded pointer is a getelementptr of a global.
8107   // TODO: Use SCEV instead of manually grubbing with GEPs.
8108   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
8109   if (!GEP) return getCouldNotCompute();
8110 
8111   // Make sure that it is really a constant global we are gepping, with an
8112   // initializer, and make sure the first IDX is really 0.
8113   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
8114   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
8115       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
8116       !cast<Constant>(GEP->getOperand(1))->isNullValue())
8117     return getCouldNotCompute();
8118 
8119   // Okay, we allow one non-constant index into the GEP instruction.
8120   Value *VarIdx = nullptr;
8121   std::vector<Constant*> Indexes;
8122   unsigned VarIdxNum = 0;
8123   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
8124     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
8125       Indexes.push_back(CI);
8126     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
8127       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
8128       VarIdx = GEP->getOperand(i);
8129       VarIdxNum = i-2;
8130       Indexes.push_back(nullptr);
8131     }
8132 
8133   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
8134   if (!VarIdx)
8135     return getCouldNotCompute();
8136 
8137   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
8138   // Check to see if X is a loop variant variable value now.
8139   const SCEV *Idx = getSCEV(VarIdx);
8140   Idx = getSCEVAtScope(Idx, L);
8141 
8142   // We can only recognize very limited forms of loop index expressions, in
8143   // particular, only affine AddRec's like {C1,+,C2}<L>.
8144   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
8145   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
8146       isLoopInvariant(IdxExpr, L) ||
8147       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
8148       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
8149     return getCouldNotCompute();
8150 
8151   unsigned MaxSteps = MaxBruteForceIterations;
8152   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
8153     ConstantInt *ItCst = ConstantInt::get(
8154                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
8155     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
8156 
8157     // Form the GEP offset.
8158     Indexes[VarIdxNum] = Val;
8159 
8160     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
8161                                                          Indexes);
8162     if (!Result) break;  // Cannot compute!
8163 
8164     // Evaluate the condition for this iteration.
8165     Result = ConstantExpr::getICmp(predicate, Result, RHS);
8166     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
8167     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
8168       ++NumArrayLenItCounts;
8169       return getConstant(ItCst);   // Found terminating iteration!
8170     }
8171   }
8172   return getCouldNotCompute();
8173 }
8174 
8175 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8176     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8177   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8178   if (!RHS)
8179     return getCouldNotCompute();
8180 
8181   const BasicBlock *Latch = L->getLoopLatch();
8182   if (!Latch)
8183     return getCouldNotCompute();
8184 
8185   const BasicBlock *Predecessor = L->getLoopPredecessor();
8186   if (!Predecessor)
8187     return getCouldNotCompute();
8188 
8189   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8190   // Return LHS in OutLHS and shift_opt in OutOpCode.
8191   auto MatchPositiveShift =
8192       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8193 
8194     using namespace PatternMatch;
8195 
8196     ConstantInt *ShiftAmt;
8197     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8198       OutOpCode = Instruction::LShr;
8199     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8200       OutOpCode = Instruction::AShr;
8201     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8202       OutOpCode = Instruction::Shl;
8203     else
8204       return false;
8205 
8206     return ShiftAmt->getValue().isStrictlyPositive();
8207   };
8208 
8209   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8210   //
8211   // loop:
8212   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8213   //   %iv.shifted = lshr i32 %iv, <positive constant>
8214   //
8215   // Return true on a successful match.  Return the corresponding PHI node (%iv
8216   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8217   auto MatchShiftRecurrence =
8218       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8219     Optional<Instruction::BinaryOps> PostShiftOpCode;
8220 
8221     {
8222       Instruction::BinaryOps OpC;
8223       Value *V;
8224 
8225       // If we encounter a shift instruction, "peel off" the shift operation,
8226       // and remember that we did so.  Later when we inspect %iv's backedge
8227       // value, we will make sure that the backedge value uses the same
8228       // operation.
8229       //
8230       // Note: the peeled shift operation does not have to be the same
8231       // instruction as the one feeding into the PHI's backedge value.  We only
8232       // really care about it being the same *kind* of shift instruction --
8233       // that's all that is required for our later inferences to hold.
8234       if (MatchPositiveShift(LHS, V, OpC)) {
8235         PostShiftOpCode = OpC;
8236         LHS = V;
8237       }
8238     }
8239 
8240     PNOut = dyn_cast<PHINode>(LHS);
8241     if (!PNOut || PNOut->getParent() != L->getHeader())
8242       return false;
8243 
8244     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8245     Value *OpLHS;
8246 
8247     return
8248         // The backedge value for the PHI node must be a shift by a positive
8249         // amount
8250         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8251 
8252         // of the PHI node itself
8253         OpLHS == PNOut &&
8254 
8255         // and the kind of shift should be match the kind of shift we peeled
8256         // off, if any.
8257         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8258   };
8259 
8260   PHINode *PN;
8261   Instruction::BinaryOps OpCode;
8262   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8263     return getCouldNotCompute();
8264 
8265   const DataLayout &DL = getDataLayout();
8266 
8267   // The key rationale for this optimization is that for some kinds of shift
8268   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8269   // within a finite number of iterations.  If the condition guarding the
8270   // backedge (in the sense that the backedge is taken if the condition is true)
8271   // is false for the value the shift recurrence stabilizes to, then we know
8272   // that the backedge is taken only a finite number of times.
8273 
8274   ConstantInt *StableValue = nullptr;
8275   switch (OpCode) {
8276   default:
8277     llvm_unreachable("Impossible case!");
8278 
8279   case Instruction::AShr: {
8280     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8281     // bitwidth(K) iterations.
8282     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8283     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8284                                        Predecessor->getTerminator(), &DT);
8285     auto *Ty = cast<IntegerType>(RHS->getType());
8286     if (Known.isNonNegative())
8287       StableValue = ConstantInt::get(Ty, 0);
8288     else if (Known.isNegative())
8289       StableValue = ConstantInt::get(Ty, -1, true);
8290     else
8291       return getCouldNotCompute();
8292 
8293     break;
8294   }
8295   case Instruction::LShr:
8296   case Instruction::Shl:
8297     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8298     // stabilize to 0 in at most bitwidth(K) iterations.
8299     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8300     break;
8301   }
8302 
8303   auto *Result =
8304       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8305   assert(Result->getType()->isIntegerTy(1) &&
8306          "Otherwise cannot be an operand to a branch instruction");
8307 
8308   if (Result->isZeroValue()) {
8309     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8310     const SCEV *UpperBound =
8311         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8312     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8313   }
8314 
8315   return getCouldNotCompute();
8316 }
8317 
8318 /// Return true if we can constant fold an instruction of the specified type,
8319 /// assuming that all operands were constants.
8320 static bool CanConstantFold(const Instruction *I) {
8321   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8322       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8323       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8324     return true;
8325 
8326   if (const CallInst *CI = dyn_cast<CallInst>(I))
8327     if (const Function *F = CI->getCalledFunction())
8328       return canConstantFoldCallTo(CI, F);
8329   return false;
8330 }
8331 
8332 /// Determine whether this instruction can constant evolve within this loop
8333 /// assuming its operands can all constant evolve.
8334 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8335   // An instruction outside of the loop can't be derived from a loop PHI.
8336   if (!L->contains(I)) return false;
8337 
8338   if (isa<PHINode>(I)) {
8339     // We don't currently keep track of the control flow needed to evaluate
8340     // PHIs, so we cannot handle PHIs inside of loops.
8341     return L->getHeader() == I->getParent();
8342   }
8343 
8344   // If we won't be able to constant fold this expression even if the operands
8345   // are constants, bail early.
8346   return CanConstantFold(I);
8347 }
8348 
8349 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8350 /// recursing through each instruction operand until reaching a loop header phi.
8351 static PHINode *
8352 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8353                                DenseMap<Instruction *, PHINode *> &PHIMap,
8354                                unsigned Depth) {
8355   if (Depth > MaxConstantEvolvingDepth)
8356     return nullptr;
8357 
8358   // Otherwise, we can evaluate this instruction if all of its operands are
8359   // constant or derived from a PHI node themselves.
8360   PHINode *PHI = nullptr;
8361   for (Value *Op : UseInst->operands()) {
8362     if (isa<Constant>(Op)) continue;
8363 
8364     Instruction *OpInst = dyn_cast<Instruction>(Op);
8365     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8366 
8367     PHINode *P = dyn_cast<PHINode>(OpInst);
8368     if (!P)
8369       // If this operand is already visited, reuse the prior result.
8370       // We may have P != PHI if this is the deepest point at which the
8371       // inconsistent paths meet.
8372       P = PHIMap.lookup(OpInst);
8373     if (!P) {
8374       // Recurse and memoize the results, whether a phi is found or not.
8375       // This recursive call invalidates pointers into PHIMap.
8376       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8377       PHIMap[OpInst] = P;
8378     }
8379     if (!P)
8380       return nullptr;  // Not evolving from PHI
8381     if (PHI && PHI != P)
8382       return nullptr;  // Evolving from multiple different PHIs.
8383     PHI = P;
8384   }
8385   // This is a expression evolving from a constant PHI!
8386   return PHI;
8387 }
8388 
8389 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8390 /// in the loop that V is derived from.  We allow arbitrary operations along the
8391 /// way, but the operands of an operation must either be constants or a value
8392 /// derived from a constant PHI.  If this expression does not fit with these
8393 /// constraints, return null.
8394 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8395   Instruction *I = dyn_cast<Instruction>(V);
8396   if (!I || !canConstantEvolve(I, L)) return nullptr;
8397 
8398   if (PHINode *PN = dyn_cast<PHINode>(I))
8399     return PN;
8400 
8401   // Record non-constant instructions contained by the loop.
8402   DenseMap<Instruction *, PHINode *> PHIMap;
8403   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8404 }
8405 
8406 /// EvaluateExpression - Given an expression that passes the
8407 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8408 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8409 /// reason, return null.
8410 static Constant *EvaluateExpression(Value *V, const Loop *L,
8411                                     DenseMap<Instruction *, Constant *> &Vals,
8412                                     const DataLayout &DL,
8413                                     const TargetLibraryInfo *TLI) {
8414   // Convenient constant check, but redundant for recursive calls.
8415   if (Constant *C = dyn_cast<Constant>(V)) return C;
8416   Instruction *I = dyn_cast<Instruction>(V);
8417   if (!I) return nullptr;
8418 
8419   if (Constant *C = Vals.lookup(I)) return C;
8420 
8421   // An instruction inside the loop depends on a value outside the loop that we
8422   // weren't given a mapping for, or a value such as a call inside the loop.
8423   if (!canConstantEvolve(I, L)) return nullptr;
8424 
8425   // An unmapped PHI can be due to a branch or another loop inside this loop,
8426   // or due to this not being the initial iteration through a loop where we
8427   // couldn't compute the evolution of this particular PHI last time.
8428   if (isa<PHINode>(I)) return nullptr;
8429 
8430   std::vector<Constant*> Operands(I->getNumOperands());
8431 
8432   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8433     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8434     if (!Operand) {
8435       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8436       if (!Operands[i]) return nullptr;
8437       continue;
8438     }
8439     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8440     Vals[Operand] = C;
8441     if (!C) return nullptr;
8442     Operands[i] = C;
8443   }
8444 
8445   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8446     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8447                                            Operands[1], DL, TLI);
8448   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8449     if (!LI->isVolatile())
8450       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8451   }
8452   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8453 }
8454 
8455 
8456 // If every incoming value to PN except the one for BB is a specific Constant,
8457 // return that, else return nullptr.
8458 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8459   Constant *IncomingVal = nullptr;
8460 
8461   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8462     if (PN->getIncomingBlock(i) == BB)
8463       continue;
8464 
8465     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8466     if (!CurrentVal)
8467       return nullptr;
8468 
8469     if (IncomingVal != CurrentVal) {
8470       if (IncomingVal)
8471         return nullptr;
8472       IncomingVal = CurrentVal;
8473     }
8474   }
8475 
8476   return IncomingVal;
8477 }
8478 
8479 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8480 /// in the header of its containing loop, we know the loop executes a
8481 /// constant number of times, and the PHI node is just a recurrence
8482 /// involving constants, fold it.
8483 Constant *
8484 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8485                                                    const APInt &BEs,
8486                                                    const Loop *L) {
8487   auto I = ConstantEvolutionLoopExitValue.find(PN);
8488   if (I != ConstantEvolutionLoopExitValue.end())
8489     return I->second;
8490 
8491   if (BEs.ugt(MaxBruteForceIterations))
8492     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8493 
8494   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8495 
8496   DenseMap<Instruction *, Constant *> CurrentIterVals;
8497   BasicBlock *Header = L->getHeader();
8498   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8499 
8500   BasicBlock *Latch = L->getLoopLatch();
8501   if (!Latch)
8502     return nullptr;
8503 
8504   for (PHINode &PHI : Header->phis()) {
8505     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8506       CurrentIterVals[&PHI] = StartCST;
8507   }
8508   if (!CurrentIterVals.count(PN))
8509     return RetVal = nullptr;
8510 
8511   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8512 
8513   // Execute the loop symbolically to determine the exit value.
8514   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8515          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8516 
8517   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8518   unsigned IterationNum = 0;
8519   const DataLayout &DL = getDataLayout();
8520   for (; ; ++IterationNum) {
8521     if (IterationNum == NumIterations)
8522       return RetVal = CurrentIterVals[PN];  // Got exit value!
8523 
8524     // Compute the value of the PHIs for the next iteration.
8525     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8526     DenseMap<Instruction *, Constant *> NextIterVals;
8527     Constant *NextPHI =
8528         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8529     if (!NextPHI)
8530       return nullptr;        // Couldn't evaluate!
8531     NextIterVals[PN] = NextPHI;
8532 
8533     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8534 
8535     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8536     // cease to be able to evaluate one of them or if they stop evolving,
8537     // because that doesn't necessarily prevent us from computing PN.
8538     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8539     for (const auto &I : CurrentIterVals) {
8540       PHINode *PHI = dyn_cast<PHINode>(I.first);
8541       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8542       PHIsToCompute.emplace_back(PHI, I.second);
8543     }
8544     // We use two distinct loops because EvaluateExpression may invalidate any
8545     // iterators into CurrentIterVals.
8546     for (const auto &I : PHIsToCompute) {
8547       PHINode *PHI = I.first;
8548       Constant *&NextPHI = NextIterVals[PHI];
8549       if (!NextPHI) {   // Not already computed.
8550         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8551         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8552       }
8553       if (NextPHI != I.second)
8554         StoppedEvolving = false;
8555     }
8556 
8557     // If all entries in CurrentIterVals == NextIterVals then we can stop
8558     // iterating, the loop can't continue to change.
8559     if (StoppedEvolving)
8560       return RetVal = CurrentIterVals[PN];
8561 
8562     CurrentIterVals.swap(NextIterVals);
8563   }
8564 }
8565 
8566 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8567                                                           Value *Cond,
8568                                                           bool ExitWhen) {
8569   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8570   if (!PN) return getCouldNotCompute();
8571 
8572   // If the loop is canonicalized, the PHI will have exactly two entries.
8573   // That's the only form we support here.
8574   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8575 
8576   DenseMap<Instruction *, Constant *> CurrentIterVals;
8577   BasicBlock *Header = L->getHeader();
8578   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8579 
8580   BasicBlock *Latch = L->getLoopLatch();
8581   assert(Latch && "Should follow from NumIncomingValues == 2!");
8582 
8583   for (PHINode &PHI : Header->phis()) {
8584     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8585       CurrentIterVals[&PHI] = StartCST;
8586   }
8587   if (!CurrentIterVals.count(PN))
8588     return getCouldNotCompute();
8589 
8590   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8591   // the loop symbolically to determine when the condition gets a value of
8592   // "ExitWhen".
8593   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8594   const DataLayout &DL = getDataLayout();
8595   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8596     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8597         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8598 
8599     // Couldn't symbolically evaluate.
8600     if (!CondVal) return getCouldNotCompute();
8601 
8602     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8603       ++NumBruteForceTripCountsComputed;
8604       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8605     }
8606 
8607     // Update all the PHI nodes for the next iteration.
8608     DenseMap<Instruction *, Constant *> NextIterVals;
8609 
8610     // Create a list of which PHIs we need to compute. We want to do this before
8611     // calling EvaluateExpression on them because that may invalidate iterators
8612     // into CurrentIterVals.
8613     SmallVector<PHINode *, 8> PHIsToCompute;
8614     for (const auto &I : CurrentIterVals) {
8615       PHINode *PHI = dyn_cast<PHINode>(I.first);
8616       if (!PHI || PHI->getParent() != Header) continue;
8617       PHIsToCompute.push_back(PHI);
8618     }
8619     for (PHINode *PHI : PHIsToCompute) {
8620       Constant *&NextPHI = NextIterVals[PHI];
8621       if (NextPHI) continue;    // Already computed!
8622 
8623       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8624       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8625     }
8626     CurrentIterVals.swap(NextIterVals);
8627   }
8628 
8629   // Too many iterations were needed to evaluate.
8630   return getCouldNotCompute();
8631 }
8632 
8633 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8634   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8635       ValuesAtScopes[V];
8636   // Check to see if we've folded this expression at this loop before.
8637   for (auto &LS : Values)
8638     if (LS.first == L)
8639       return LS.second ? LS.second : V;
8640 
8641   Values.emplace_back(L, nullptr);
8642 
8643   // Otherwise compute it.
8644   const SCEV *C = computeSCEVAtScope(V, L);
8645   for (auto &LS : reverse(ValuesAtScopes[V]))
8646     if (LS.first == L) {
8647       LS.second = C;
8648       break;
8649     }
8650   return C;
8651 }
8652 
8653 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8654 /// will return Constants for objects which aren't represented by a
8655 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8656 /// Returns NULL if the SCEV isn't representable as a Constant.
8657 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8658   switch (V->getSCEVType()) {
8659   case scCouldNotCompute:
8660   case scAddRecExpr:
8661     return nullptr;
8662   case scConstant:
8663     return cast<SCEVConstant>(V)->getValue();
8664   case scUnknown:
8665     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8666   case scSignExtend: {
8667     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8668     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8669       return ConstantExpr::getSExt(CastOp, SS->getType());
8670     return nullptr;
8671   }
8672   case scZeroExtend: {
8673     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8674     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8675       return ConstantExpr::getZExt(CastOp, SZ->getType());
8676     return nullptr;
8677   }
8678   case scPtrToInt: {
8679     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8680     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8681       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8682 
8683     return nullptr;
8684   }
8685   case scTruncate: {
8686     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8687     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8688       return ConstantExpr::getTrunc(CastOp, ST->getType());
8689     return nullptr;
8690   }
8691   case scAddExpr: {
8692     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8693     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8694       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8695         unsigned AS = PTy->getAddressSpace();
8696         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8697         C = ConstantExpr::getBitCast(C, DestPtrTy);
8698       }
8699       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8700         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8701         if (!C2)
8702           return nullptr;
8703 
8704         // First pointer!
8705         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8706           unsigned AS = C2->getType()->getPointerAddressSpace();
8707           std::swap(C, C2);
8708           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8709           // The offsets have been converted to bytes.  We can add bytes to an
8710           // i8* by GEP with the byte count in the first index.
8711           C = ConstantExpr::getBitCast(C, DestPtrTy);
8712         }
8713 
8714         // Don't bother trying to sum two pointers. We probably can't
8715         // statically compute a load that results from it anyway.
8716         if (C2->getType()->isPointerTy())
8717           return nullptr;
8718 
8719         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8720           if (PTy->getElementType()->isStructTy())
8721             C2 = ConstantExpr::getIntegerCast(
8722                 C2, Type::getInt32Ty(C->getContext()), true);
8723           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8724         } else
8725           C = ConstantExpr::getAdd(C, C2);
8726       }
8727       return C;
8728     }
8729     return nullptr;
8730   }
8731   case scMulExpr: {
8732     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8733     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8734       // Don't bother with pointers at all.
8735       if (C->getType()->isPointerTy())
8736         return nullptr;
8737       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8738         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8739         if (!C2 || C2->getType()->isPointerTy())
8740           return nullptr;
8741         C = ConstantExpr::getMul(C, C2);
8742       }
8743       return C;
8744     }
8745     return nullptr;
8746   }
8747   case scUDivExpr: {
8748     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8749     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8750       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8751         if (LHS->getType() == RHS->getType())
8752           return ConstantExpr::getUDiv(LHS, RHS);
8753     return nullptr;
8754   }
8755   case scSMaxExpr:
8756   case scUMaxExpr:
8757   case scSMinExpr:
8758   case scUMinExpr:
8759     return nullptr; // TODO: smax, umax, smin, umax.
8760   }
8761   llvm_unreachable("Unknown SCEV kind!");
8762 }
8763 
8764 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8765   if (isa<SCEVConstant>(V)) return V;
8766 
8767   // If this instruction is evolved from a constant-evolving PHI, compute the
8768   // exit value from the loop without using SCEVs.
8769   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8770     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8771       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8772         const Loop *CurrLoop = this->LI[I->getParent()];
8773         // Looking for loop exit value.
8774         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8775             PN->getParent() == CurrLoop->getHeader()) {
8776           // Okay, there is no closed form solution for the PHI node.  Check
8777           // to see if the loop that contains it has a known backedge-taken
8778           // count.  If so, we may be able to force computation of the exit
8779           // value.
8780           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8781           // This trivial case can show up in some degenerate cases where
8782           // the incoming IR has not yet been fully simplified.
8783           if (BackedgeTakenCount->isZero()) {
8784             Value *InitValue = nullptr;
8785             bool MultipleInitValues = false;
8786             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8787               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8788                 if (!InitValue)
8789                   InitValue = PN->getIncomingValue(i);
8790                 else if (InitValue != PN->getIncomingValue(i)) {
8791                   MultipleInitValues = true;
8792                   break;
8793                 }
8794               }
8795             }
8796             if (!MultipleInitValues && InitValue)
8797               return getSCEV(InitValue);
8798           }
8799           // Do we have a loop invariant value flowing around the backedge
8800           // for a loop which must execute the backedge?
8801           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8802               isKnownPositive(BackedgeTakenCount) &&
8803               PN->getNumIncomingValues() == 2) {
8804 
8805             unsigned InLoopPred =
8806                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8807             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8808             if (CurrLoop->isLoopInvariant(BackedgeVal))
8809               return getSCEV(BackedgeVal);
8810           }
8811           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8812             // Okay, we know how many times the containing loop executes.  If
8813             // this is a constant evolving PHI node, get the final value at
8814             // the specified iteration number.
8815             Constant *RV = getConstantEvolutionLoopExitValue(
8816                 PN, BTCC->getAPInt(), CurrLoop);
8817             if (RV) return getSCEV(RV);
8818           }
8819         }
8820 
8821         // If there is a single-input Phi, evaluate it at our scope. If we can
8822         // prove that this replacement does not break LCSSA form, use new value.
8823         if (PN->getNumOperands() == 1) {
8824           const SCEV *Input = getSCEV(PN->getOperand(0));
8825           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8826           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8827           // for the simplest case just support constants.
8828           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8829         }
8830       }
8831 
8832       // Okay, this is an expression that we cannot symbolically evaluate
8833       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8834       // the arguments into constants, and if so, try to constant propagate the
8835       // result.  This is particularly useful for computing loop exit values.
8836       if (CanConstantFold(I)) {
8837         SmallVector<Constant *, 4> Operands;
8838         bool MadeImprovement = false;
8839         for (Value *Op : I->operands()) {
8840           if (Constant *C = dyn_cast<Constant>(Op)) {
8841             Operands.push_back(C);
8842             continue;
8843           }
8844 
8845           // If any of the operands is non-constant and if they are
8846           // non-integer and non-pointer, don't even try to analyze them
8847           // with scev techniques.
8848           if (!isSCEVable(Op->getType()))
8849             return V;
8850 
8851           const SCEV *OrigV = getSCEV(Op);
8852           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8853           MadeImprovement |= OrigV != OpV;
8854 
8855           Constant *C = BuildConstantFromSCEV(OpV);
8856           if (!C) return V;
8857           if (C->getType() != Op->getType())
8858             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8859                                                               Op->getType(),
8860                                                               false),
8861                                       C, Op->getType());
8862           Operands.push_back(C);
8863         }
8864 
8865         // Check to see if getSCEVAtScope actually made an improvement.
8866         if (MadeImprovement) {
8867           Constant *C = nullptr;
8868           const DataLayout &DL = getDataLayout();
8869           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8870             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8871                                                 Operands[1], DL, &TLI);
8872           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8873             if (!Load->isVolatile())
8874               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8875                                                DL);
8876           } else
8877             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8878           if (!C) return V;
8879           return getSCEV(C);
8880         }
8881       }
8882     }
8883 
8884     // This is some other type of SCEVUnknown, just return it.
8885     return V;
8886   }
8887 
8888   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8889     // Avoid performing the look-up in the common case where the specified
8890     // expression has no loop-variant portions.
8891     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8892       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8893       if (OpAtScope != Comm->getOperand(i)) {
8894         // Okay, at least one of these operands is loop variant but might be
8895         // foldable.  Build a new instance of the folded commutative expression.
8896         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8897                                             Comm->op_begin()+i);
8898         NewOps.push_back(OpAtScope);
8899 
8900         for (++i; i != e; ++i) {
8901           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8902           NewOps.push_back(OpAtScope);
8903         }
8904         if (isa<SCEVAddExpr>(Comm))
8905           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8906         if (isa<SCEVMulExpr>(Comm))
8907           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8908         if (isa<SCEVMinMaxExpr>(Comm))
8909           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8910         llvm_unreachable("Unknown commutative SCEV type!");
8911       }
8912     }
8913     // If we got here, all operands are loop invariant.
8914     return Comm;
8915   }
8916 
8917   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8918     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8919     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8920     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8921       return Div;   // must be loop invariant
8922     return getUDivExpr(LHS, RHS);
8923   }
8924 
8925   // If this is a loop recurrence for a loop that does not contain L, then we
8926   // are dealing with the final value computed by the loop.
8927   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8928     // First, attempt to evaluate each operand.
8929     // Avoid performing the look-up in the common case where the specified
8930     // expression has no loop-variant portions.
8931     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8932       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8933       if (OpAtScope == AddRec->getOperand(i))
8934         continue;
8935 
8936       // Okay, at least one of these operands is loop variant but might be
8937       // foldable.  Build a new instance of the folded commutative expression.
8938       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8939                                           AddRec->op_begin()+i);
8940       NewOps.push_back(OpAtScope);
8941       for (++i; i != e; ++i)
8942         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8943 
8944       const SCEV *FoldedRec =
8945         getAddRecExpr(NewOps, AddRec->getLoop(),
8946                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8947       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8948       // The addrec may be folded to a nonrecurrence, for example, if the
8949       // induction variable is multiplied by zero after constant folding. Go
8950       // ahead and return the folded value.
8951       if (!AddRec)
8952         return FoldedRec;
8953       break;
8954     }
8955 
8956     // If the scope is outside the addrec's loop, evaluate it by using the
8957     // loop exit value of the addrec.
8958     if (!AddRec->getLoop()->contains(L)) {
8959       // To evaluate this recurrence, we need to know how many times the AddRec
8960       // loop iterates.  Compute this now.
8961       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8962       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8963 
8964       // Then, evaluate the AddRec.
8965       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8966     }
8967 
8968     return AddRec;
8969   }
8970 
8971   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8972     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8973     if (Op == Cast->getOperand())
8974       return Cast;  // must be loop invariant
8975     return getZeroExtendExpr(Op, Cast->getType());
8976   }
8977 
8978   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8979     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8980     if (Op == Cast->getOperand())
8981       return Cast;  // must be loop invariant
8982     return getSignExtendExpr(Op, Cast->getType());
8983   }
8984 
8985   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8986     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8987     if (Op == Cast->getOperand())
8988       return Cast;  // must be loop invariant
8989     return getTruncateExpr(Op, Cast->getType());
8990   }
8991 
8992   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8993     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8994     if (Op == Cast->getOperand())
8995       return Cast; // must be loop invariant
8996     return getPtrToIntExpr(Op, Cast->getType());
8997   }
8998 
8999   llvm_unreachable("Unknown SCEV type!");
9000 }
9001 
9002 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9003   return getSCEVAtScope(getSCEV(V), L);
9004 }
9005 
9006 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9007   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9008     return stripInjectiveFunctions(ZExt->getOperand());
9009   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9010     return stripInjectiveFunctions(SExt->getOperand());
9011   return S;
9012 }
9013 
9014 /// Finds the minimum unsigned root of the following equation:
9015 ///
9016 ///     A * X = B (mod N)
9017 ///
9018 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9019 /// A and B isn't important.
9020 ///
9021 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9022 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9023                                                ScalarEvolution &SE) {
9024   uint32_t BW = A.getBitWidth();
9025   assert(BW == SE.getTypeSizeInBits(B->getType()));
9026   assert(A != 0 && "A must be non-zero.");
9027 
9028   // 1. D = gcd(A, N)
9029   //
9030   // The gcd of A and N may have only one prime factor: 2. The number of
9031   // trailing zeros in A is its multiplicity
9032   uint32_t Mult2 = A.countTrailingZeros();
9033   // D = 2^Mult2
9034 
9035   // 2. Check if B is divisible by D.
9036   //
9037   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9038   // is not less than multiplicity of this prime factor for D.
9039   if (SE.GetMinTrailingZeros(B) < Mult2)
9040     return SE.getCouldNotCompute();
9041 
9042   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9043   // modulo (N / D).
9044   //
9045   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9046   // (N / D) in general. The inverse itself always fits into BW bits, though,
9047   // so we immediately truncate it.
9048   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9049   APInt Mod(BW + 1, 0);
9050   Mod.setBit(BW - Mult2);  // Mod = N / D
9051   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9052 
9053   // 4. Compute the minimum unsigned root of the equation:
9054   // I * (B / D) mod (N / D)
9055   // To simplify the computation, we factor out the divide by D:
9056   // (I * B mod N) / D
9057   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9058   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9059 }
9060 
9061 /// For a given quadratic addrec, generate coefficients of the corresponding
9062 /// quadratic equation, multiplied by a common value to ensure that they are
9063 /// integers.
9064 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9065 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9066 /// were multiplied by, and BitWidth is the bit width of the original addrec
9067 /// coefficients.
9068 /// This function returns None if the addrec coefficients are not compile-
9069 /// time constants.
9070 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9071 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9072   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9073   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9074   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9075   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9076   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9077                     << *AddRec << '\n');
9078 
9079   // We currently can only solve this if the coefficients are constants.
9080   if (!LC || !MC || !NC) {
9081     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9082     return None;
9083   }
9084 
9085   APInt L = LC->getAPInt();
9086   APInt M = MC->getAPInt();
9087   APInt N = NC->getAPInt();
9088   assert(!N.isNullValue() && "This is not a quadratic addrec");
9089 
9090   unsigned BitWidth = LC->getAPInt().getBitWidth();
9091   unsigned NewWidth = BitWidth + 1;
9092   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9093                     << BitWidth << '\n');
9094   // The sign-extension (as opposed to a zero-extension) here matches the
9095   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9096   N = N.sext(NewWidth);
9097   M = M.sext(NewWidth);
9098   L = L.sext(NewWidth);
9099 
9100   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9101   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9102   //   L+M, L+2M+N, L+3M+3N, ...
9103   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9104   //
9105   // The equation Acc = 0 is then
9106   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9107   // In a quadratic form it becomes:
9108   //   N n^2 + (2M-N) n + 2L = 0.
9109 
9110   APInt A = N;
9111   APInt B = 2 * M - A;
9112   APInt C = 2 * L;
9113   APInt T = APInt(NewWidth, 2);
9114   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9115                     << "x + " << C << ", coeff bw: " << NewWidth
9116                     << ", multiplied by " << T << '\n');
9117   return std::make_tuple(A, B, C, T, BitWidth);
9118 }
9119 
9120 /// Helper function to compare optional APInts:
9121 /// (a) if X and Y both exist, return min(X, Y),
9122 /// (b) if neither X nor Y exist, return None,
9123 /// (c) if exactly one of X and Y exists, return that value.
9124 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9125   if (X.hasValue() && Y.hasValue()) {
9126     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9127     APInt XW = X->sextOrSelf(W);
9128     APInt YW = Y->sextOrSelf(W);
9129     return XW.slt(YW) ? *X : *Y;
9130   }
9131   if (!X.hasValue() && !Y.hasValue())
9132     return None;
9133   return X.hasValue() ? *X : *Y;
9134 }
9135 
9136 /// Helper function to truncate an optional APInt to a given BitWidth.
9137 /// When solving addrec-related equations, it is preferable to return a value
9138 /// that has the same bit width as the original addrec's coefficients. If the
9139 /// solution fits in the original bit width, truncate it (except for i1).
9140 /// Returning a value of a different bit width may inhibit some optimizations.
9141 ///
9142 /// In general, a solution to a quadratic equation generated from an addrec
9143 /// may require BW+1 bits, where BW is the bit width of the addrec's
9144 /// coefficients. The reason is that the coefficients of the quadratic
9145 /// equation are BW+1 bits wide (to avoid truncation when converting from
9146 /// the addrec to the equation).
9147 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9148   if (!X.hasValue())
9149     return None;
9150   unsigned W = X->getBitWidth();
9151   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9152     return X->trunc(BitWidth);
9153   return X;
9154 }
9155 
9156 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9157 /// iterations. The values L, M, N are assumed to be signed, and they
9158 /// should all have the same bit widths.
9159 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9160 /// where BW is the bit width of the addrec's coefficients.
9161 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9162 /// returned as such, otherwise the bit width of the returned value may
9163 /// be greater than BW.
9164 ///
9165 /// This function returns None if
9166 /// (a) the addrec coefficients are not constant, or
9167 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9168 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9169 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9170 static Optional<APInt>
9171 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9172   APInt A, B, C, M;
9173   unsigned BitWidth;
9174   auto T = GetQuadraticEquation(AddRec);
9175   if (!T.hasValue())
9176     return None;
9177 
9178   std::tie(A, B, C, M, BitWidth) = *T;
9179   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9180   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9181   if (!X.hasValue())
9182     return None;
9183 
9184   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9185   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9186   if (!V->isZero())
9187     return None;
9188 
9189   return TruncIfPossible(X, BitWidth);
9190 }
9191 
9192 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9193 /// iterations. The values M, N are assumed to be signed, and they
9194 /// should all have the same bit widths.
9195 /// Find the least n such that c(n) does not belong to the given range,
9196 /// while c(n-1) does.
9197 ///
9198 /// This function returns None if
9199 /// (a) the addrec coefficients are not constant, or
9200 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9201 ///     bounds of the range.
9202 static Optional<APInt>
9203 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9204                           const ConstantRange &Range, ScalarEvolution &SE) {
9205   assert(AddRec->getOperand(0)->isZero() &&
9206          "Starting value of addrec should be 0");
9207   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9208                     << Range << ", addrec " << *AddRec << '\n');
9209   // This case is handled in getNumIterationsInRange. Here we can assume that
9210   // we start in the range.
9211   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9212          "Addrec's initial value should be in range");
9213 
9214   APInt A, B, C, M;
9215   unsigned BitWidth;
9216   auto T = GetQuadraticEquation(AddRec);
9217   if (!T.hasValue())
9218     return None;
9219 
9220   // Be careful about the return value: there can be two reasons for not
9221   // returning an actual number. First, if no solutions to the equations
9222   // were found, and second, if the solutions don't leave the given range.
9223   // The first case means that the actual solution is "unknown", the second
9224   // means that it's known, but not valid. If the solution is unknown, we
9225   // cannot make any conclusions.
9226   // Return a pair: the optional solution and a flag indicating if the
9227   // solution was found.
9228   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9229     // Solve for signed overflow and unsigned overflow, pick the lower
9230     // solution.
9231     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9232                       << Bound << " (before multiplying by " << M << ")\n");
9233     Bound *= M; // The quadratic equation multiplier.
9234 
9235     Optional<APInt> SO = None;
9236     if (BitWidth > 1) {
9237       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9238                            "signed overflow\n");
9239       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9240     }
9241     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9242                          "unsigned overflow\n");
9243     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9244                                                               BitWidth+1);
9245 
9246     auto LeavesRange = [&] (const APInt &X) {
9247       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9248       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9249       if (Range.contains(V0->getValue()))
9250         return false;
9251       // X should be at least 1, so X-1 is non-negative.
9252       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9253       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9254       if (Range.contains(V1->getValue()))
9255         return true;
9256       return false;
9257     };
9258 
9259     // If SolveQuadraticEquationWrap returns None, it means that there can
9260     // be a solution, but the function failed to find it. We cannot treat it
9261     // as "no solution".
9262     if (!SO.hasValue() || !UO.hasValue())
9263       return { None, false };
9264 
9265     // Check the smaller value first to see if it leaves the range.
9266     // At this point, both SO and UO must have values.
9267     Optional<APInt> Min = MinOptional(SO, UO);
9268     if (LeavesRange(*Min))
9269       return { Min, true };
9270     Optional<APInt> Max = Min == SO ? UO : SO;
9271     if (LeavesRange(*Max))
9272       return { Max, true };
9273 
9274     // Solutions were found, but were eliminated, hence the "true".
9275     return { None, true };
9276   };
9277 
9278   std::tie(A, B, C, M, BitWidth) = *T;
9279   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9280   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9281   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9282   auto SL = SolveForBoundary(Lower);
9283   auto SU = SolveForBoundary(Upper);
9284   // If any of the solutions was unknown, no meaninigful conclusions can
9285   // be made.
9286   if (!SL.second || !SU.second)
9287     return None;
9288 
9289   // Claim: The correct solution is not some value between Min and Max.
9290   //
9291   // Justification: Assuming that Min and Max are different values, one of
9292   // them is when the first signed overflow happens, the other is when the
9293   // first unsigned overflow happens. Crossing the range boundary is only
9294   // possible via an overflow (treating 0 as a special case of it, modeling
9295   // an overflow as crossing k*2^W for some k).
9296   //
9297   // The interesting case here is when Min was eliminated as an invalid
9298   // solution, but Max was not. The argument is that if there was another
9299   // overflow between Min and Max, it would also have been eliminated if
9300   // it was considered.
9301   //
9302   // For a given boundary, it is possible to have two overflows of the same
9303   // type (signed/unsigned) without having the other type in between: this
9304   // can happen when the vertex of the parabola is between the iterations
9305   // corresponding to the overflows. This is only possible when the two
9306   // overflows cross k*2^W for the same k. In such case, if the second one
9307   // left the range (and was the first one to do so), the first overflow
9308   // would have to enter the range, which would mean that either we had left
9309   // the range before or that we started outside of it. Both of these cases
9310   // are contradictions.
9311   //
9312   // Claim: In the case where SolveForBoundary returns None, the correct
9313   // solution is not some value between the Max for this boundary and the
9314   // Min of the other boundary.
9315   //
9316   // Justification: Assume that we had such Max_A and Min_B corresponding
9317   // to range boundaries A and B and such that Max_A < Min_B. If there was
9318   // a solution between Max_A and Min_B, it would have to be caused by an
9319   // overflow corresponding to either A or B. It cannot correspond to B,
9320   // since Min_B is the first occurrence of such an overflow. If it
9321   // corresponded to A, it would have to be either a signed or an unsigned
9322   // overflow that is larger than both eliminated overflows for A. But
9323   // between the eliminated overflows and this overflow, the values would
9324   // cover the entire value space, thus crossing the other boundary, which
9325   // is a contradiction.
9326 
9327   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9328 }
9329 
9330 ScalarEvolution::ExitLimit
9331 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9332                               bool AllowPredicates) {
9333 
9334   // This is only used for loops with a "x != y" exit test. The exit condition
9335   // is now expressed as a single expression, V = x-y. So the exit test is
9336   // effectively V != 0.  We know and take advantage of the fact that this
9337   // expression only being used in a comparison by zero context.
9338 
9339   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9340   // If the value is a constant
9341   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9342     // If the value is already zero, the branch will execute zero times.
9343     if (C->getValue()->isZero()) return C;
9344     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9345   }
9346 
9347   const SCEVAddRecExpr *AddRec =
9348       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9349 
9350   if (!AddRec && AllowPredicates)
9351     // Try to make this an AddRec using runtime tests, in the first X
9352     // iterations of this loop, where X is the SCEV expression found by the
9353     // algorithm below.
9354     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9355 
9356   if (!AddRec || AddRec->getLoop() != L)
9357     return getCouldNotCompute();
9358 
9359   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9360   // the quadratic equation to solve it.
9361   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9362     // We can only use this value if the chrec ends up with an exact zero
9363     // value at this index.  When solving for "X*X != 5", for example, we
9364     // should not accept a root of 2.
9365     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9366       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9367       return ExitLimit(R, R, false, Predicates);
9368     }
9369     return getCouldNotCompute();
9370   }
9371 
9372   // Otherwise we can only handle this if it is affine.
9373   if (!AddRec->isAffine())
9374     return getCouldNotCompute();
9375 
9376   // If this is an affine expression, the execution count of this branch is
9377   // the minimum unsigned root of the following equation:
9378   //
9379   //     Start + Step*N = 0 (mod 2^BW)
9380   //
9381   // equivalent to:
9382   //
9383   //             Step*N = -Start (mod 2^BW)
9384   //
9385   // where BW is the common bit width of Start and Step.
9386 
9387   // Get the initial value for the loop.
9388   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9389   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9390 
9391   // For now we handle only constant steps.
9392   //
9393   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9394   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9395   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9396   // We have not yet seen any such cases.
9397   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9398   if (!StepC || StepC->getValue()->isZero())
9399     return getCouldNotCompute();
9400 
9401   // For positive steps (counting up until unsigned overflow):
9402   //   N = -Start/Step (as unsigned)
9403   // For negative steps (counting down to zero):
9404   //   N = Start/-Step
9405   // First compute the unsigned distance from zero in the direction of Step.
9406   bool CountDown = StepC->getAPInt().isNegative();
9407   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9408 
9409   // Handle unitary steps, which cannot wraparound.
9410   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9411   //   N = Distance (as unsigned)
9412   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9413     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9414     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9415     if (MaxBECountBase.ult(MaxBECount))
9416       MaxBECount = MaxBECountBase;
9417 
9418     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9419     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9420     // case, and see if we can improve the bound.
9421     //
9422     // Explicitly handling this here is necessary because getUnsignedRange
9423     // isn't context-sensitive; it doesn't know that we only care about the
9424     // range inside the loop.
9425     const SCEV *Zero = getZero(Distance->getType());
9426     const SCEV *One = getOne(Distance->getType());
9427     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9428     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9429       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9430       // as "unsigned_max(Distance + 1) - 1".
9431       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9432       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9433     }
9434     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9435   }
9436 
9437   // If the condition controls loop exit (the loop exits only if the expression
9438   // is true) and the addition is no-wrap we can use unsigned divide to
9439   // compute the backedge count.  In this case, the step may not divide the
9440   // distance, but we don't care because if the condition is "missed" the loop
9441   // will have undefined behavior due to wrapping.
9442   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9443       loopHasNoAbnormalExits(AddRec->getLoop())) {
9444     const SCEV *Exact =
9445         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9446     const SCEV *Max = getCouldNotCompute();
9447     if (Exact != getCouldNotCompute()) {
9448       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
9449       APInt BaseMaxInt = getUnsignedRangeMax(Exact);
9450       if (BaseMaxInt.ult(MaxInt))
9451         Max = getConstant(BaseMaxInt);
9452       else
9453         Max = getConstant(MaxInt);
9454     }
9455     return ExitLimit(Exact, Max, false, Predicates);
9456   }
9457 
9458   // Solve the general equation.
9459   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9460                                                getNegativeSCEV(Start), *this);
9461   const SCEV *M = E == getCouldNotCompute()
9462                       ? E
9463                       : getConstant(getUnsignedRangeMax(E));
9464   return ExitLimit(E, M, false, Predicates);
9465 }
9466 
9467 ScalarEvolution::ExitLimit
9468 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9469   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9470   // handle them yet except for the trivial case.  This could be expanded in the
9471   // future as needed.
9472 
9473   // If the value is a constant, check to see if it is known to be non-zero
9474   // already.  If so, the backedge will execute zero times.
9475   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9476     if (!C->getValue()->isZero())
9477       return getZero(C->getType());
9478     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9479   }
9480 
9481   // We could implement others, but I really doubt anyone writes loops like
9482   // this, and if they did, they would already be constant folded.
9483   return getCouldNotCompute();
9484 }
9485 
9486 std::pair<const BasicBlock *, const BasicBlock *>
9487 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9488     const {
9489   // If the block has a unique predecessor, then there is no path from the
9490   // predecessor to the block that does not go through the direct edge
9491   // from the predecessor to the block.
9492   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9493     return {Pred, BB};
9494 
9495   // A loop's header is defined to be a block that dominates the loop.
9496   // If the header has a unique predecessor outside the loop, it must be
9497   // a block that has exactly one successor that can reach the loop.
9498   if (const Loop *L = LI.getLoopFor(BB))
9499     return {L->getLoopPredecessor(), L->getHeader()};
9500 
9501   return {nullptr, nullptr};
9502 }
9503 
9504 /// SCEV structural equivalence is usually sufficient for testing whether two
9505 /// expressions are equal, however for the purposes of looking for a condition
9506 /// guarding a loop, it can be useful to be a little more general, since a
9507 /// front-end may have replicated the controlling expression.
9508 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9509   // Quick check to see if they are the same SCEV.
9510   if (A == B) return true;
9511 
9512   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9513     // Not all instructions that are "identical" compute the same value.  For
9514     // instance, two distinct alloca instructions allocating the same type are
9515     // identical and do not read memory; but compute distinct values.
9516     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9517   };
9518 
9519   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9520   // two different instructions with the same value. Check for this case.
9521   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9522     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9523       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9524         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9525           if (ComputesEqualValues(AI, BI))
9526             return true;
9527 
9528   // Otherwise assume they may have a different value.
9529   return false;
9530 }
9531 
9532 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9533                                            const SCEV *&LHS, const SCEV *&RHS,
9534                                            unsigned Depth) {
9535   bool Changed = false;
9536   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9537   // '0 != 0'.
9538   auto TrivialCase = [&](bool TriviallyTrue) {
9539     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9540     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9541     return true;
9542   };
9543   // If we hit the max recursion limit bail out.
9544   if (Depth >= 3)
9545     return false;
9546 
9547   // Canonicalize a constant to the right side.
9548   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9549     // Check for both operands constant.
9550     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9551       if (ConstantExpr::getICmp(Pred,
9552                                 LHSC->getValue(),
9553                                 RHSC->getValue())->isNullValue())
9554         return TrivialCase(false);
9555       else
9556         return TrivialCase(true);
9557     }
9558     // Otherwise swap the operands to put the constant on the right.
9559     std::swap(LHS, RHS);
9560     Pred = ICmpInst::getSwappedPredicate(Pred);
9561     Changed = true;
9562   }
9563 
9564   // If we're comparing an addrec with a value which is loop-invariant in the
9565   // addrec's loop, put the addrec on the left. Also make a dominance check,
9566   // as both operands could be addrecs loop-invariant in each other's loop.
9567   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9568     const Loop *L = AR->getLoop();
9569     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9570       std::swap(LHS, RHS);
9571       Pred = ICmpInst::getSwappedPredicate(Pred);
9572       Changed = true;
9573     }
9574   }
9575 
9576   // If there's a constant operand, canonicalize comparisons with boundary
9577   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9578   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9579     const APInt &RA = RC->getAPInt();
9580 
9581     bool SimplifiedByConstantRange = false;
9582 
9583     if (!ICmpInst::isEquality(Pred)) {
9584       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9585       if (ExactCR.isFullSet())
9586         return TrivialCase(true);
9587       else if (ExactCR.isEmptySet())
9588         return TrivialCase(false);
9589 
9590       APInt NewRHS;
9591       CmpInst::Predicate NewPred;
9592       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9593           ICmpInst::isEquality(NewPred)) {
9594         // We were able to convert an inequality to an equality.
9595         Pred = NewPred;
9596         RHS = getConstant(NewRHS);
9597         Changed = SimplifiedByConstantRange = true;
9598       }
9599     }
9600 
9601     if (!SimplifiedByConstantRange) {
9602       switch (Pred) {
9603       default:
9604         break;
9605       case ICmpInst::ICMP_EQ:
9606       case ICmpInst::ICMP_NE:
9607         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9608         if (!RA)
9609           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9610             if (const SCEVMulExpr *ME =
9611                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9612               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9613                   ME->getOperand(0)->isAllOnesValue()) {
9614                 RHS = AE->getOperand(1);
9615                 LHS = ME->getOperand(1);
9616                 Changed = true;
9617               }
9618         break;
9619 
9620 
9621         // The "Should have been caught earlier!" messages refer to the fact
9622         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9623         // should have fired on the corresponding cases, and canonicalized the
9624         // check to trivial case.
9625 
9626       case ICmpInst::ICMP_UGE:
9627         assert(!RA.isMinValue() && "Should have been caught earlier!");
9628         Pred = ICmpInst::ICMP_UGT;
9629         RHS = getConstant(RA - 1);
9630         Changed = true;
9631         break;
9632       case ICmpInst::ICMP_ULE:
9633         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9634         Pred = ICmpInst::ICMP_ULT;
9635         RHS = getConstant(RA + 1);
9636         Changed = true;
9637         break;
9638       case ICmpInst::ICMP_SGE:
9639         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9640         Pred = ICmpInst::ICMP_SGT;
9641         RHS = getConstant(RA - 1);
9642         Changed = true;
9643         break;
9644       case ICmpInst::ICMP_SLE:
9645         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9646         Pred = ICmpInst::ICMP_SLT;
9647         RHS = getConstant(RA + 1);
9648         Changed = true;
9649         break;
9650       }
9651     }
9652   }
9653 
9654   // Check for obvious equality.
9655   if (HasSameValue(LHS, RHS)) {
9656     if (ICmpInst::isTrueWhenEqual(Pred))
9657       return TrivialCase(true);
9658     if (ICmpInst::isFalseWhenEqual(Pred))
9659       return TrivialCase(false);
9660   }
9661 
9662   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9663   // adding or subtracting 1 from one of the operands.
9664   switch (Pred) {
9665   case ICmpInst::ICMP_SLE:
9666     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9667       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9668                        SCEV::FlagNSW);
9669       Pred = ICmpInst::ICMP_SLT;
9670       Changed = true;
9671     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9672       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9673                        SCEV::FlagNSW);
9674       Pred = ICmpInst::ICMP_SLT;
9675       Changed = true;
9676     }
9677     break;
9678   case ICmpInst::ICMP_SGE:
9679     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9680       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9681                        SCEV::FlagNSW);
9682       Pred = ICmpInst::ICMP_SGT;
9683       Changed = true;
9684     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9685       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9686                        SCEV::FlagNSW);
9687       Pred = ICmpInst::ICMP_SGT;
9688       Changed = true;
9689     }
9690     break;
9691   case ICmpInst::ICMP_ULE:
9692     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9693       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9694                        SCEV::FlagNUW);
9695       Pred = ICmpInst::ICMP_ULT;
9696       Changed = true;
9697     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9698       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9699       Pred = ICmpInst::ICMP_ULT;
9700       Changed = true;
9701     }
9702     break;
9703   case ICmpInst::ICMP_UGE:
9704     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9705       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9706       Pred = ICmpInst::ICMP_UGT;
9707       Changed = true;
9708     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9709       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9710                        SCEV::FlagNUW);
9711       Pred = ICmpInst::ICMP_UGT;
9712       Changed = true;
9713     }
9714     break;
9715   default:
9716     break;
9717   }
9718 
9719   // TODO: More simplifications are possible here.
9720 
9721   // Recursively simplify until we either hit a recursion limit or nothing
9722   // changes.
9723   if (Changed)
9724     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9725 
9726   return Changed;
9727 }
9728 
9729 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9730   return getSignedRangeMax(S).isNegative();
9731 }
9732 
9733 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9734   return getSignedRangeMin(S).isStrictlyPositive();
9735 }
9736 
9737 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9738   return !getSignedRangeMin(S).isNegative();
9739 }
9740 
9741 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9742   return !getSignedRangeMax(S).isStrictlyPositive();
9743 }
9744 
9745 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9746   return isKnownNegative(S) || isKnownPositive(S);
9747 }
9748 
9749 std::pair<const SCEV *, const SCEV *>
9750 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9751   // Compute SCEV on entry of loop L.
9752   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9753   if (Start == getCouldNotCompute())
9754     return { Start, Start };
9755   // Compute post increment SCEV for loop L.
9756   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9757   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9758   return { Start, PostInc };
9759 }
9760 
9761 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9762                                           const SCEV *LHS, const SCEV *RHS) {
9763   // First collect all loops.
9764   SmallPtrSet<const Loop *, 8> LoopsUsed;
9765   getUsedLoops(LHS, LoopsUsed);
9766   getUsedLoops(RHS, LoopsUsed);
9767 
9768   if (LoopsUsed.empty())
9769     return false;
9770 
9771   // Domination relationship must be a linear order on collected loops.
9772 #ifndef NDEBUG
9773   for (auto *L1 : LoopsUsed)
9774     for (auto *L2 : LoopsUsed)
9775       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9776               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9777              "Domination relationship is not a linear order");
9778 #endif
9779 
9780   const Loop *MDL =
9781       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9782                         [&](const Loop *L1, const Loop *L2) {
9783          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9784        });
9785 
9786   // Get init and post increment value for LHS.
9787   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9788   // if LHS contains unknown non-invariant SCEV then bail out.
9789   if (SplitLHS.first == getCouldNotCompute())
9790     return false;
9791   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9792   // Get init and post increment value for RHS.
9793   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9794   // if RHS contains unknown non-invariant SCEV then bail out.
9795   if (SplitRHS.first == getCouldNotCompute())
9796     return false;
9797   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9798   // It is possible that init SCEV contains an invariant load but it does
9799   // not dominate MDL and is not available at MDL loop entry, so we should
9800   // check it here.
9801   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9802       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9803     return false;
9804 
9805   // It seems backedge guard check is faster than entry one so in some cases
9806   // it can speed up whole estimation by short circuit
9807   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9808                                      SplitRHS.second) &&
9809          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9810 }
9811 
9812 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9813                                        const SCEV *LHS, const SCEV *RHS) {
9814   // Canonicalize the inputs first.
9815   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9816 
9817   if (isKnownViaInduction(Pred, LHS, RHS))
9818     return true;
9819 
9820   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9821     return true;
9822 
9823   // Otherwise see what can be done with some simple reasoning.
9824   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9825 }
9826 
9827 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
9828                                                   const SCEV *LHS,
9829                                                   const SCEV *RHS) {
9830   if (isKnownPredicate(Pred, LHS, RHS))
9831     return true;
9832   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
9833     return false;
9834   return None;
9835 }
9836 
9837 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9838                                          const SCEV *LHS, const SCEV *RHS,
9839                                          const Instruction *Context) {
9840   // TODO: Analyze guards and assumes from Context's block.
9841   return isKnownPredicate(Pred, LHS, RHS) ||
9842          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9843 }
9844 
9845 Optional<bool>
9846 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
9847                                      const SCEV *RHS,
9848                                      const Instruction *Context) {
9849   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
9850   if (KnownWithoutContext)
9851     return KnownWithoutContext;
9852 
9853   if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS))
9854     return true;
9855   else if (isBasicBlockEntryGuardedByCond(Context->getParent(),
9856                                           ICmpInst::getInversePredicate(Pred),
9857                                           LHS, RHS))
9858     return false;
9859   return None;
9860 }
9861 
9862 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9863                                               const SCEVAddRecExpr *LHS,
9864                                               const SCEV *RHS) {
9865   const Loop *L = LHS->getLoop();
9866   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9867          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9868 }
9869 
9870 Optional<ScalarEvolution::MonotonicPredicateType>
9871 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9872                                            ICmpInst::Predicate Pred) {
9873   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9874 
9875 #ifndef NDEBUG
9876   // Verify an invariant: inverting the predicate should turn a monotonically
9877   // increasing change to a monotonically decreasing one, and vice versa.
9878   if (Result) {
9879     auto ResultSwapped =
9880         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9881 
9882     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9883     assert(ResultSwapped.getValue() != Result.getValue() &&
9884            "monotonicity should flip as we flip the predicate");
9885   }
9886 #endif
9887 
9888   return Result;
9889 }
9890 
9891 Optional<ScalarEvolution::MonotonicPredicateType>
9892 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9893                                                ICmpInst::Predicate Pred) {
9894   // A zero step value for LHS means the induction variable is essentially a
9895   // loop invariant value. We don't really depend on the predicate actually
9896   // flipping from false to true (for increasing predicates, and the other way
9897   // around for decreasing predicates), all we care about is that *if* the
9898   // predicate changes then it only changes from false to true.
9899   //
9900   // A zero step value in itself is not very useful, but there may be places
9901   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9902   // as general as possible.
9903 
9904   // Only handle LE/LT/GE/GT predicates.
9905   if (!ICmpInst::isRelational(Pred))
9906     return None;
9907 
9908   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9909   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9910          "Should be greater or less!");
9911 
9912   // Check that AR does not wrap.
9913   if (ICmpInst::isUnsigned(Pred)) {
9914     if (!LHS->hasNoUnsignedWrap())
9915       return None;
9916     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9917   } else {
9918     assert(ICmpInst::isSigned(Pred) &&
9919            "Relational predicate is either signed or unsigned!");
9920     if (!LHS->hasNoSignedWrap())
9921       return None;
9922 
9923     const SCEV *Step = LHS->getStepRecurrence(*this);
9924 
9925     if (isKnownNonNegative(Step))
9926       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9927 
9928     if (isKnownNonPositive(Step))
9929       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9930 
9931     return None;
9932   }
9933 }
9934 
9935 Optional<ScalarEvolution::LoopInvariantPredicate>
9936 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9937                                            const SCEV *LHS, const SCEV *RHS,
9938                                            const Loop *L) {
9939 
9940   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9941   if (!isLoopInvariant(RHS, L)) {
9942     if (!isLoopInvariant(LHS, L))
9943       return None;
9944 
9945     std::swap(LHS, RHS);
9946     Pred = ICmpInst::getSwappedPredicate(Pred);
9947   }
9948 
9949   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9950   if (!ArLHS || ArLHS->getLoop() != L)
9951     return None;
9952 
9953   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9954   if (!MonotonicType)
9955     return None;
9956   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9957   // true as the loop iterates, and the backedge is control dependent on
9958   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9959   //
9960   //   * if the predicate was false in the first iteration then the predicate
9961   //     is never evaluated again, since the loop exits without taking the
9962   //     backedge.
9963   //   * if the predicate was true in the first iteration then it will
9964   //     continue to be true for all future iterations since it is
9965   //     monotonically increasing.
9966   //
9967   // For both the above possibilities, we can replace the loop varying
9968   // predicate with its value on the first iteration of the loop (which is
9969   // loop invariant).
9970   //
9971   // A similar reasoning applies for a monotonically decreasing predicate, by
9972   // replacing true with false and false with true in the above two bullets.
9973   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9974   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9975 
9976   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9977     return None;
9978 
9979   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9980 }
9981 
9982 Optional<ScalarEvolution::LoopInvariantPredicate>
9983 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9984     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9985     const Instruction *Context, const SCEV *MaxIter) {
9986   // Try to prove the following set of facts:
9987   // - The predicate is monotonic in the iteration space.
9988   // - If the check does not fail on the 1st iteration:
9989   //   - No overflow will happen during first MaxIter iterations;
9990   //   - It will not fail on the MaxIter'th iteration.
9991   // If the check does fail on the 1st iteration, we leave the loop and no
9992   // other checks matter.
9993 
9994   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9995   if (!isLoopInvariant(RHS, L)) {
9996     if (!isLoopInvariant(LHS, L))
9997       return None;
9998 
9999     std::swap(LHS, RHS);
10000     Pred = ICmpInst::getSwappedPredicate(Pred);
10001   }
10002 
10003   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10004   if (!AR || AR->getLoop() != L)
10005     return None;
10006 
10007   // The predicate must be relational (i.e. <, <=, >=, >).
10008   if (!ICmpInst::isRelational(Pred))
10009     return None;
10010 
10011   // TODO: Support steps other than +/- 1.
10012   const SCEV *Step = AR->getStepRecurrence(*this);
10013   auto *One = getOne(Step->getType());
10014   auto *MinusOne = getNegativeSCEV(One);
10015   if (Step != One && Step != MinusOne)
10016     return None;
10017 
10018   // Type mismatch here means that MaxIter is potentially larger than max
10019   // unsigned value in start type, which mean we cannot prove no wrap for the
10020   // indvar.
10021   if (AR->getType() != MaxIter->getType())
10022     return None;
10023 
10024   // Value of IV on suggested last iteration.
10025   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10026   // Does it still meet the requirement?
10027   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10028     return None;
10029   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10030   // not exceed max unsigned value of this type), this effectively proves
10031   // that there is no wrap during the iteration. To prove that there is no
10032   // signed/unsigned wrap, we need to check that
10033   // Start <= Last for step = 1 or Start >= Last for step = -1.
10034   ICmpInst::Predicate NoOverflowPred =
10035       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10036   if (Step == MinusOne)
10037     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10038   const SCEV *Start = AR->getStart();
10039   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
10040     return None;
10041 
10042   // Everything is fine.
10043   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10044 }
10045 
10046 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10047     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10048   if (HasSameValue(LHS, RHS))
10049     return ICmpInst::isTrueWhenEqual(Pred);
10050 
10051   // This code is split out from isKnownPredicate because it is called from
10052   // within isLoopEntryGuardedByCond.
10053 
10054   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10055                          const ConstantRange &RangeRHS) {
10056     return RangeLHS.icmp(Pred, RangeRHS);
10057   };
10058 
10059   // The check at the top of the function catches the case where the values are
10060   // known to be equal.
10061   if (Pred == CmpInst::ICMP_EQ)
10062     return false;
10063 
10064   if (Pred == CmpInst::ICMP_NE)
10065     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10066            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
10067            isKnownNonZero(getMinusSCEV(LHS, RHS));
10068 
10069   if (CmpInst::isSigned(Pred))
10070     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10071 
10072   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10073 }
10074 
10075 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10076                                                     const SCEV *LHS,
10077                                                     const SCEV *RHS) {
10078   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10079   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10080   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10081   // OutC1 and OutC2.
10082   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10083                                       APInt &OutC1, APInt &OutC2,
10084                                       SCEV::NoWrapFlags ExpectedFlags) {
10085     const SCEV *XNonConstOp, *XConstOp;
10086     const SCEV *YNonConstOp, *YConstOp;
10087     SCEV::NoWrapFlags XFlagsPresent;
10088     SCEV::NoWrapFlags YFlagsPresent;
10089 
10090     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10091       XConstOp = getZero(X->getType());
10092       XNonConstOp = X;
10093       XFlagsPresent = ExpectedFlags;
10094     }
10095     if (!isa<SCEVConstant>(XConstOp) ||
10096         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10097       return false;
10098 
10099     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10100       YConstOp = getZero(Y->getType());
10101       YNonConstOp = Y;
10102       YFlagsPresent = ExpectedFlags;
10103     }
10104 
10105     if (!isa<SCEVConstant>(YConstOp) ||
10106         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10107       return false;
10108 
10109     if (YNonConstOp != XNonConstOp)
10110       return false;
10111 
10112     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10113     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10114 
10115     return true;
10116   };
10117 
10118   APInt C1;
10119   APInt C2;
10120 
10121   switch (Pred) {
10122   default:
10123     break;
10124 
10125   case ICmpInst::ICMP_SGE:
10126     std::swap(LHS, RHS);
10127     LLVM_FALLTHROUGH;
10128   case ICmpInst::ICMP_SLE:
10129     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10130     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10131       return true;
10132 
10133     break;
10134 
10135   case ICmpInst::ICMP_SGT:
10136     std::swap(LHS, RHS);
10137     LLVM_FALLTHROUGH;
10138   case ICmpInst::ICMP_SLT:
10139     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10140     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10141       return true;
10142 
10143     break;
10144 
10145   case ICmpInst::ICMP_UGE:
10146     std::swap(LHS, RHS);
10147     LLVM_FALLTHROUGH;
10148   case ICmpInst::ICMP_ULE:
10149     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10150     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10151       return true;
10152 
10153     break;
10154 
10155   case ICmpInst::ICMP_UGT:
10156     std::swap(LHS, RHS);
10157     LLVM_FALLTHROUGH;
10158   case ICmpInst::ICMP_ULT:
10159     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10160     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10161       return true;
10162     break;
10163   }
10164 
10165   return false;
10166 }
10167 
10168 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10169                                                    const SCEV *LHS,
10170                                                    const SCEV *RHS) {
10171   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10172     return false;
10173 
10174   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10175   // the stack can result in exponential time complexity.
10176   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10177 
10178   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10179   //
10180   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10181   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10182   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10183   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10184   // use isKnownPredicate later if needed.
10185   return isKnownNonNegative(RHS) &&
10186          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10187          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10188 }
10189 
10190 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10191                                         ICmpInst::Predicate Pred,
10192                                         const SCEV *LHS, const SCEV *RHS) {
10193   // No need to even try if we know the module has no guards.
10194   if (!HasGuards)
10195     return false;
10196 
10197   return any_of(*BB, [&](const Instruction &I) {
10198     using namespace llvm::PatternMatch;
10199 
10200     Value *Condition;
10201     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10202                          m_Value(Condition))) &&
10203            isImpliedCond(Pred, LHS, RHS, Condition, false);
10204   });
10205 }
10206 
10207 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10208 /// protected by a conditional between LHS and RHS.  This is used to
10209 /// to eliminate casts.
10210 bool
10211 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10212                                              ICmpInst::Predicate Pred,
10213                                              const SCEV *LHS, const SCEV *RHS) {
10214   // Interpret a null as meaning no loop, where there is obviously no guard
10215   // (interprocedural conditions notwithstanding).
10216   if (!L) return true;
10217 
10218   if (VerifyIR)
10219     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10220            "This cannot be done on broken IR!");
10221 
10222 
10223   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10224     return true;
10225 
10226   BasicBlock *Latch = L->getLoopLatch();
10227   if (!Latch)
10228     return false;
10229 
10230   BranchInst *LoopContinuePredicate =
10231     dyn_cast<BranchInst>(Latch->getTerminator());
10232   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10233       isImpliedCond(Pred, LHS, RHS,
10234                     LoopContinuePredicate->getCondition(),
10235                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10236     return true;
10237 
10238   // We don't want more than one activation of the following loops on the stack
10239   // -- that can lead to O(n!) time complexity.
10240   if (WalkingBEDominatingConds)
10241     return false;
10242 
10243   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10244 
10245   // See if we can exploit a trip count to prove the predicate.
10246   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10247   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10248   if (LatchBECount != getCouldNotCompute()) {
10249     // We know that Latch branches back to the loop header exactly
10250     // LatchBECount times.  This means the backdege condition at Latch is
10251     // equivalent to  "{0,+,1} u< LatchBECount".
10252     Type *Ty = LatchBECount->getType();
10253     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10254     const SCEV *LoopCounter =
10255       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10256     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10257                       LatchBECount))
10258       return true;
10259   }
10260 
10261   // Check conditions due to any @llvm.assume intrinsics.
10262   for (auto &AssumeVH : AC.assumptions()) {
10263     if (!AssumeVH)
10264       continue;
10265     auto *CI = cast<CallInst>(AssumeVH);
10266     if (!DT.dominates(CI, Latch->getTerminator()))
10267       continue;
10268 
10269     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10270       return true;
10271   }
10272 
10273   // If the loop is not reachable from the entry block, we risk running into an
10274   // infinite loop as we walk up into the dom tree.  These loops do not matter
10275   // anyway, so we just return a conservative answer when we see them.
10276   if (!DT.isReachableFromEntry(L->getHeader()))
10277     return false;
10278 
10279   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10280     return true;
10281 
10282   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10283        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10284     assert(DTN && "should reach the loop header before reaching the root!");
10285 
10286     BasicBlock *BB = DTN->getBlock();
10287     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10288       return true;
10289 
10290     BasicBlock *PBB = BB->getSinglePredecessor();
10291     if (!PBB)
10292       continue;
10293 
10294     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10295     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10296       continue;
10297 
10298     Value *Condition = ContinuePredicate->getCondition();
10299 
10300     // If we have an edge `E` within the loop body that dominates the only
10301     // latch, the condition guarding `E` also guards the backedge.  This
10302     // reasoning works only for loops with a single latch.
10303 
10304     BasicBlockEdge DominatingEdge(PBB, BB);
10305     if (DominatingEdge.isSingleEdge()) {
10306       // We're constructively (and conservatively) enumerating edges within the
10307       // loop body that dominate the latch.  The dominator tree better agree
10308       // with us on this:
10309       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10310 
10311       if (isImpliedCond(Pred, LHS, RHS, Condition,
10312                         BB != ContinuePredicate->getSuccessor(0)))
10313         return true;
10314     }
10315   }
10316 
10317   return false;
10318 }
10319 
10320 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10321                                                      ICmpInst::Predicate Pred,
10322                                                      const SCEV *LHS,
10323                                                      const SCEV *RHS) {
10324   if (VerifyIR)
10325     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10326            "This cannot be done on broken IR!");
10327 
10328   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10329   // the facts (a >= b && a != b) separately. A typical situation is when the
10330   // non-strict comparison is known from ranges and non-equality is known from
10331   // dominating predicates. If we are proving strict comparison, we always try
10332   // to prove non-equality and non-strict comparison separately.
10333   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10334   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10335   bool ProvedNonStrictComparison = false;
10336   bool ProvedNonEquality = false;
10337 
10338   auto SplitAndProve =
10339     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10340     if (!ProvedNonStrictComparison)
10341       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10342     if (!ProvedNonEquality)
10343       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10344     if (ProvedNonStrictComparison && ProvedNonEquality)
10345       return true;
10346     return false;
10347   };
10348 
10349   if (ProvingStrictComparison) {
10350     auto ProofFn = [&](ICmpInst::Predicate P) {
10351       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10352     };
10353     if (SplitAndProve(ProofFn))
10354       return true;
10355   }
10356 
10357   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10358   auto ProveViaGuard = [&](const BasicBlock *Block) {
10359     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10360       return true;
10361     if (ProvingStrictComparison) {
10362       auto ProofFn = [&](ICmpInst::Predicate P) {
10363         return isImpliedViaGuard(Block, P, LHS, RHS);
10364       };
10365       if (SplitAndProve(ProofFn))
10366         return true;
10367     }
10368     return false;
10369   };
10370 
10371   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10372   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10373     const Instruction *Context = &BB->front();
10374     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10375       return true;
10376     if (ProvingStrictComparison) {
10377       auto ProofFn = [&](ICmpInst::Predicate P) {
10378         return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context);
10379       };
10380       if (SplitAndProve(ProofFn))
10381         return true;
10382     }
10383     return false;
10384   };
10385 
10386   // Starting at the block's predecessor, climb up the predecessor chain, as long
10387   // as there are predecessors that can be found that have unique successors
10388   // leading to the original block.
10389   const Loop *ContainingLoop = LI.getLoopFor(BB);
10390   const BasicBlock *PredBB;
10391   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10392     PredBB = ContainingLoop->getLoopPredecessor();
10393   else
10394     PredBB = BB->getSinglePredecessor();
10395   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10396        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10397     if (ProveViaGuard(Pair.first))
10398       return true;
10399 
10400     const BranchInst *LoopEntryPredicate =
10401         dyn_cast<BranchInst>(Pair.first->getTerminator());
10402     if (!LoopEntryPredicate ||
10403         LoopEntryPredicate->isUnconditional())
10404       continue;
10405 
10406     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10407                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10408       return true;
10409   }
10410 
10411   // Check conditions due to any @llvm.assume intrinsics.
10412   for (auto &AssumeVH : AC.assumptions()) {
10413     if (!AssumeVH)
10414       continue;
10415     auto *CI = cast<CallInst>(AssumeVH);
10416     if (!DT.dominates(CI, BB))
10417       continue;
10418 
10419     if (ProveViaCond(CI->getArgOperand(0), false))
10420       return true;
10421   }
10422 
10423   return false;
10424 }
10425 
10426 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10427                                                ICmpInst::Predicate Pred,
10428                                                const SCEV *LHS,
10429                                                const SCEV *RHS) {
10430   // Interpret a null as meaning no loop, where there is obviously no guard
10431   // (interprocedural conditions notwithstanding).
10432   if (!L)
10433     return false;
10434 
10435   // Both LHS and RHS must be available at loop entry.
10436   assert(isAvailableAtLoopEntry(LHS, L) &&
10437          "LHS is not available at Loop Entry");
10438   assert(isAvailableAtLoopEntry(RHS, L) &&
10439          "RHS is not available at Loop Entry");
10440 
10441   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10442     return true;
10443 
10444   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10445 }
10446 
10447 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10448                                     const SCEV *RHS,
10449                                     const Value *FoundCondValue, bool Inverse,
10450                                     const Instruction *Context) {
10451   // False conditions implies anything. Do not bother analyzing it further.
10452   if (FoundCondValue ==
10453       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10454     return true;
10455 
10456   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10457     return false;
10458 
10459   auto ClearOnExit =
10460       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10461 
10462   // Recursively handle And and Or conditions.
10463   const Value *Op0, *Op1;
10464   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10465     if (!Inverse)
10466       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10467               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10468   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10469     if (Inverse)
10470       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10471               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10472   }
10473 
10474   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10475   if (!ICI) return false;
10476 
10477   // Now that we found a conditional branch that dominates the loop or controls
10478   // the loop latch. Check to see if it is the comparison we are looking for.
10479   ICmpInst::Predicate FoundPred;
10480   if (Inverse)
10481     FoundPred = ICI->getInversePredicate();
10482   else
10483     FoundPred = ICI->getPredicate();
10484 
10485   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10486   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10487 
10488   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10489 }
10490 
10491 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10492                                     const SCEV *RHS,
10493                                     ICmpInst::Predicate FoundPred,
10494                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10495                                     const Instruction *Context) {
10496   // Balance the types.
10497   if (getTypeSizeInBits(LHS->getType()) <
10498       getTypeSizeInBits(FoundLHS->getType())) {
10499     // For unsigned and equality predicates, try to prove that both found
10500     // operands fit into narrow unsigned range. If so, try to prove facts in
10501     // narrow types.
10502     if (!CmpInst::isSigned(FoundPred)) {
10503       auto *NarrowType = LHS->getType();
10504       auto *WideType = FoundLHS->getType();
10505       auto BitWidth = getTypeSizeInBits(NarrowType);
10506       const SCEV *MaxValue = getZeroExtendExpr(
10507           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10508       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10509           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10510         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10511         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10512         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10513                                        TruncFoundRHS, Context))
10514           return true;
10515       }
10516     }
10517 
10518     if (CmpInst::isSigned(Pred)) {
10519       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10520       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10521     } else {
10522       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10523       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10524     }
10525   } else if (getTypeSizeInBits(LHS->getType()) >
10526       getTypeSizeInBits(FoundLHS->getType())) {
10527     if (CmpInst::isSigned(FoundPred)) {
10528       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10529       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10530     } else {
10531       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10532       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10533     }
10534   }
10535   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10536                                     FoundRHS, Context);
10537 }
10538 
10539 bool ScalarEvolution::isImpliedCondBalancedTypes(
10540     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10541     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10542     const Instruction *Context) {
10543   assert(getTypeSizeInBits(LHS->getType()) ==
10544              getTypeSizeInBits(FoundLHS->getType()) &&
10545          "Types should be balanced!");
10546   // Canonicalize the query to match the way instcombine will have
10547   // canonicalized the comparison.
10548   if (SimplifyICmpOperands(Pred, LHS, RHS))
10549     if (LHS == RHS)
10550       return CmpInst::isTrueWhenEqual(Pred);
10551   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10552     if (FoundLHS == FoundRHS)
10553       return CmpInst::isFalseWhenEqual(FoundPred);
10554 
10555   // Check to see if we can make the LHS or RHS match.
10556   if (LHS == FoundRHS || RHS == FoundLHS) {
10557     if (isa<SCEVConstant>(RHS)) {
10558       std::swap(FoundLHS, FoundRHS);
10559       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10560     } else {
10561       std::swap(LHS, RHS);
10562       Pred = ICmpInst::getSwappedPredicate(Pred);
10563     }
10564   }
10565 
10566   // Check whether the found predicate is the same as the desired predicate.
10567   if (FoundPred == Pred)
10568     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10569 
10570   // Check whether swapping the found predicate makes it the same as the
10571   // desired predicate.
10572   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10573     // We can write the implication
10574     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10575     // using one of the following ways:
10576     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10577     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10578     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10579     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10580     // Forms 1. and 2. require swapping the operands of one condition. Don't
10581     // do this if it would break canonical constant/addrec ordering.
10582     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10583       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10584                                    Context);
10585     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10586       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10587 
10588     // There's no clear preference between forms 3. and 4., try both.
10589     return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10590                                  FoundLHS, FoundRHS, Context) ||
10591            isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10592                                  getNotSCEV(FoundRHS), Context);
10593   }
10594 
10595   // Unsigned comparison is the same as signed comparison when both the operands
10596   // are non-negative.
10597   if (CmpInst::isUnsigned(FoundPred) &&
10598       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10599       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10600     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10601 
10602   // Check if we can make progress by sharpening ranges.
10603   if (FoundPred == ICmpInst::ICMP_NE &&
10604       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10605 
10606     const SCEVConstant *C = nullptr;
10607     const SCEV *V = nullptr;
10608 
10609     if (isa<SCEVConstant>(FoundLHS)) {
10610       C = cast<SCEVConstant>(FoundLHS);
10611       V = FoundRHS;
10612     } else {
10613       C = cast<SCEVConstant>(FoundRHS);
10614       V = FoundLHS;
10615     }
10616 
10617     // The guarding predicate tells us that C != V. If the known range
10618     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10619     // range we consider has to correspond to same signedness as the
10620     // predicate we're interested in folding.
10621 
10622     APInt Min = ICmpInst::isSigned(Pred) ?
10623         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10624 
10625     if (Min == C->getAPInt()) {
10626       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10627       // This is true even if (Min + 1) wraps around -- in case of
10628       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10629 
10630       APInt SharperMin = Min + 1;
10631 
10632       switch (Pred) {
10633         case ICmpInst::ICMP_SGE:
10634         case ICmpInst::ICMP_UGE:
10635           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10636           // RHS, we're done.
10637           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10638                                     Context))
10639             return true;
10640           LLVM_FALLTHROUGH;
10641 
10642         case ICmpInst::ICMP_SGT:
10643         case ICmpInst::ICMP_UGT:
10644           // We know from the range information that (V `Pred` Min ||
10645           // V == Min).  We know from the guarding condition that !(V
10646           // == Min).  This gives us
10647           //
10648           //       V `Pred` Min || V == Min && !(V == Min)
10649           //   =>  V `Pred` Min
10650           //
10651           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10652 
10653           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10654                                     Context))
10655             return true;
10656           break;
10657 
10658         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10659         case ICmpInst::ICMP_SLE:
10660         case ICmpInst::ICMP_ULE:
10661           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10662                                     LHS, V, getConstant(SharperMin), Context))
10663             return true;
10664           LLVM_FALLTHROUGH;
10665 
10666         case ICmpInst::ICMP_SLT:
10667         case ICmpInst::ICMP_ULT:
10668           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10669                                     LHS, V, getConstant(Min), Context))
10670             return true;
10671           break;
10672 
10673         default:
10674           // No change
10675           break;
10676       }
10677     }
10678   }
10679 
10680   // Check whether the actual condition is beyond sufficient.
10681   if (FoundPred == ICmpInst::ICMP_EQ)
10682     if (ICmpInst::isTrueWhenEqual(Pred))
10683       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10684         return true;
10685   if (Pred == ICmpInst::ICMP_NE)
10686     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10687       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10688                                 Context))
10689         return true;
10690 
10691   // Otherwise assume the worst.
10692   return false;
10693 }
10694 
10695 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10696                                      const SCEV *&L, const SCEV *&R,
10697                                      SCEV::NoWrapFlags &Flags) {
10698   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10699   if (!AE || AE->getNumOperands() != 2)
10700     return false;
10701 
10702   L = AE->getOperand(0);
10703   R = AE->getOperand(1);
10704   Flags = AE->getNoWrapFlags();
10705   return true;
10706 }
10707 
10708 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10709                                                            const SCEV *Less) {
10710   // We avoid subtracting expressions here because this function is usually
10711   // fairly deep in the call stack (i.e. is called many times).
10712 
10713   // X - X = 0.
10714   if (More == Less)
10715     return APInt(getTypeSizeInBits(More->getType()), 0);
10716 
10717   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10718     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10719     const auto *MAR = cast<SCEVAddRecExpr>(More);
10720 
10721     if (LAR->getLoop() != MAR->getLoop())
10722       return None;
10723 
10724     // We look at affine expressions only; not for correctness but to keep
10725     // getStepRecurrence cheap.
10726     if (!LAR->isAffine() || !MAR->isAffine())
10727       return None;
10728 
10729     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10730       return None;
10731 
10732     Less = LAR->getStart();
10733     More = MAR->getStart();
10734 
10735     // fall through
10736   }
10737 
10738   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10739     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10740     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10741     return M - L;
10742   }
10743 
10744   SCEV::NoWrapFlags Flags;
10745   const SCEV *LLess = nullptr, *RLess = nullptr;
10746   const SCEV *LMore = nullptr, *RMore = nullptr;
10747   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10748   // Compare (X + C1) vs X.
10749   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10750     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10751       if (RLess == More)
10752         return -(C1->getAPInt());
10753 
10754   // Compare X vs (X + C2).
10755   if (splitBinaryAdd(More, LMore, RMore, Flags))
10756     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10757       if (RMore == Less)
10758         return C2->getAPInt();
10759 
10760   // Compare (X + C1) vs (X + C2).
10761   if (C1 && C2 && RLess == RMore)
10762     return C2->getAPInt() - C1->getAPInt();
10763 
10764   return None;
10765 }
10766 
10767 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10768     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10769     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10770   // Try to recognize the following pattern:
10771   //
10772   //   FoundRHS = ...
10773   // ...
10774   // loop:
10775   //   FoundLHS = {Start,+,W}
10776   // context_bb: // Basic block from the same loop
10777   //   known(Pred, FoundLHS, FoundRHS)
10778   //
10779   // If some predicate is known in the context of a loop, it is also known on
10780   // each iteration of this loop, including the first iteration. Therefore, in
10781   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10782   // prove the original pred using this fact.
10783   if (!Context)
10784     return false;
10785   const BasicBlock *ContextBB = Context->getParent();
10786   // Make sure AR varies in the context block.
10787   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10788     const Loop *L = AR->getLoop();
10789     // Make sure that context belongs to the loop and executes on 1st iteration
10790     // (if it ever executes at all).
10791     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10792       return false;
10793     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10794       return false;
10795     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10796   }
10797 
10798   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10799     const Loop *L = AR->getLoop();
10800     // Make sure that context belongs to the loop and executes on 1st iteration
10801     // (if it ever executes at all).
10802     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10803       return false;
10804     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10805       return false;
10806     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10807   }
10808 
10809   return false;
10810 }
10811 
10812 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10813     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10814     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10815   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10816     return false;
10817 
10818   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10819   if (!AddRecLHS)
10820     return false;
10821 
10822   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10823   if (!AddRecFoundLHS)
10824     return false;
10825 
10826   // We'd like to let SCEV reason about control dependencies, so we constrain
10827   // both the inequalities to be about add recurrences on the same loop.  This
10828   // way we can use isLoopEntryGuardedByCond later.
10829 
10830   const Loop *L = AddRecFoundLHS->getLoop();
10831   if (L != AddRecLHS->getLoop())
10832     return false;
10833 
10834   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10835   //
10836   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10837   //                                                                  ... (2)
10838   //
10839   // Informal proof for (2), assuming (1) [*]:
10840   //
10841   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10842   //
10843   // Then
10844   //
10845   //       FoundLHS s< FoundRHS s< INT_MIN - C
10846   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10847   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10848   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10849   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10850   // <=>  FoundLHS + C s< FoundRHS + C
10851   //
10852   // [*]: (1) can be proved by ruling out overflow.
10853   //
10854   // [**]: This can be proved by analyzing all the four possibilities:
10855   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10856   //    (A s>= 0, B s>= 0).
10857   //
10858   // Note:
10859   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10860   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10861   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10862   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10863   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10864   // C)".
10865 
10866   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10867   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10868   if (!LDiff || !RDiff || *LDiff != *RDiff)
10869     return false;
10870 
10871   if (LDiff->isMinValue())
10872     return true;
10873 
10874   APInt FoundRHSLimit;
10875 
10876   if (Pred == CmpInst::ICMP_ULT) {
10877     FoundRHSLimit = -(*RDiff);
10878   } else {
10879     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10880     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10881   }
10882 
10883   // Try to prove (1) or (2), as needed.
10884   return isAvailableAtLoopEntry(FoundRHS, L) &&
10885          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10886                                   getConstant(FoundRHSLimit));
10887 }
10888 
10889 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10890                                         const SCEV *LHS, const SCEV *RHS,
10891                                         const SCEV *FoundLHS,
10892                                         const SCEV *FoundRHS, unsigned Depth) {
10893   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10894 
10895   auto ClearOnExit = make_scope_exit([&]() {
10896     if (LPhi) {
10897       bool Erased = PendingMerges.erase(LPhi);
10898       assert(Erased && "Failed to erase LPhi!");
10899       (void)Erased;
10900     }
10901     if (RPhi) {
10902       bool Erased = PendingMerges.erase(RPhi);
10903       assert(Erased && "Failed to erase RPhi!");
10904       (void)Erased;
10905     }
10906   });
10907 
10908   // Find respective Phis and check that they are not being pending.
10909   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10910     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10911       if (!PendingMerges.insert(Phi).second)
10912         return false;
10913       LPhi = Phi;
10914     }
10915   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10916     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10917       // If we detect a loop of Phi nodes being processed by this method, for
10918       // example:
10919       //
10920       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10921       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10922       //
10923       // we don't want to deal with a case that complex, so return conservative
10924       // answer false.
10925       if (!PendingMerges.insert(Phi).second)
10926         return false;
10927       RPhi = Phi;
10928     }
10929 
10930   // If none of LHS, RHS is a Phi, nothing to do here.
10931   if (!LPhi && !RPhi)
10932     return false;
10933 
10934   // If there is a SCEVUnknown Phi we are interested in, make it left.
10935   if (!LPhi) {
10936     std::swap(LHS, RHS);
10937     std::swap(FoundLHS, FoundRHS);
10938     std::swap(LPhi, RPhi);
10939     Pred = ICmpInst::getSwappedPredicate(Pred);
10940   }
10941 
10942   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10943   const BasicBlock *LBB = LPhi->getParent();
10944   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10945 
10946   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10947     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10948            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10949            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10950   };
10951 
10952   if (RPhi && RPhi->getParent() == LBB) {
10953     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10954     // If we compare two Phis from the same block, and for each entry block
10955     // the predicate is true for incoming values from this block, then the
10956     // predicate is also true for the Phis.
10957     for (const BasicBlock *IncBB : predecessors(LBB)) {
10958       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10959       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10960       if (!ProvedEasily(L, R))
10961         return false;
10962     }
10963   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10964     // Case two: RHS is also a Phi from the same basic block, and it is an
10965     // AddRec. It means that there is a loop which has both AddRec and Unknown
10966     // PHIs, for it we can compare incoming values of AddRec from above the loop
10967     // and latch with their respective incoming values of LPhi.
10968     // TODO: Generalize to handle loops with many inputs in a header.
10969     if (LPhi->getNumIncomingValues() != 2) return false;
10970 
10971     auto *RLoop = RAR->getLoop();
10972     auto *Predecessor = RLoop->getLoopPredecessor();
10973     assert(Predecessor && "Loop with AddRec with no predecessor?");
10974     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10975     if (!ProvedEasily(L1, RAR->getStart()))
10976       return false;
10977     auto *Latch = RLoop->getLoopLatch();
10978     assert(Latch && "Loop with AddRec with no latch?");
10979     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10980     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10981       return false;
10982   } else {
10983     // In all other cases go over inputs of LHS and compare each of them to RHS,
10984     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10985     // At this point RHS is either a non-Phi, or it is a Phi from some block
10986     // different from LBB.
10987     for (const BasicBlock *IncBB : predecessors(LBB)) {
10988       // Check that RHS is available in this block.
10989       if (!dominates(RHS, IncBB))
10990         return false;
10991       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10992       // Make sure L does not refer to a value from a potentially previous
10993       // iteration of a loop.
10994       if (!properlyDominates(L, IncBB))
10995         return false;
10996       if (!ProvedEasily(L, RHS))
10997         return false;
10998     }
10999   }
11000   return true;
11001 }
11002 
11003 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11004                                             const SCEV *LHS, const SCEV *RHS,
11005                                             const SCEV *FoundLHS,
11006                                             const SCEV *FoundRHS,
11007                                             const Instruction *Context) {
11008   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11009     return true;
11010 
11011   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11012     return true;
11013 
11014   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11015                                           Context))
11016     return true;
11017 
11018   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11019                                      FoundLHS, FoundRHS);
11020 }
11021 
11022 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11023 template <typename MinMaxExprType>
11024 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11025                                  const SCEV *Candidate) {
11026   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11027   if (!MinMaxExpr)
11028     return false;
11029 
11030   return is_contained(MinMaxExpr->operands(), Candidate);
11031 }
11032 
11033 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11034                                            ICmpInst::Predicate Pred,
11035                                            const SCEV *LHS, const SCEV *RHS) {
11036   // If both sides are affine addrecs for the same loop, with equal
11037   // steps, and we know the recurrences don't wrap, then we only
11038   // need to check the predicate on the starting values.
11039 
11040   if (!ICmpInst::isRelational(Pred))
11041     return false;
11042 
11043   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11044   if (!LAR)
11045     return false;
11046   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11047   if (!RAR)
11048     return false;
11049   if (LAR->getLoop() != RAR->getLoop())
11050     return false;
11051   if (!LAR->isAffine() || !RAR->isAffine())
11052     return false;
11053 
11054   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11055     return false;
11056 
11057   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11058                          SCEV::FlagNSW : SCEV::FlagNUW;
11059   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11060     return false;
11061 
11062   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11063 }
11064 
11065 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11066 /// expression?
11067 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11068                                         ICmpInst::Predicate Pred,
11069                                         const SCEV *LHS, const SCEV *RHS) {
11070   switch (Pred) {
11071   default:
11072     return false;
11073 
11074   case ICmpInst::ICMP_SGE:
11075     std::swap(LHS, RHS);
11076     LLVM_FALLTHROUGH;
11077   case ICmpInst::ICMP_SLE:
11078     return
11079         // min(A, ...) <= A
11080         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11081         // A <= max(A, ...)
11082         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11083 
11084   case ICmpInst::ICMP_UGE:
11085     std::swap(LHS, RHS);
11086     LLVM_FALLTHROUGH;
11087   case ICmpInst::ICMP_ULE:
11088     return
11089         // min(A, ...) <= A
11090         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11091         // A <= max(A, ...)
11092         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11093   }
11094 
11095   llvm_unreachable("covered switch fell through?!");
11096 }
11097 
11098 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11099                                              const SCEV *LHS, const SCEV *RHS,
11100                                              const SCEV *FoundLHS,
11101                                              const SCEV *FoundRHS,
11102                                              unsigned Depth) {
11103   assert(getTypeSizeInBits(LHS->getType()) ==
11104              getTypeSizeInBits(RHS->getType()) &&
11105          "LHS and RHS have different sizes?");
11106   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11107              getTypeSizeInBits(FoundRHS->getType()) &&
11108          "FoundLHS and FoundRHS have different sizes?");
11109   // We want to avoid hurting the compile time with analysis of too big trees.
11110   if (Depth > MaxSCEVOperationsImplicationDepth)
11111     return false;
11112 
11113   // We only want to work with GT comparison so far.
11114   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11115     Pred = CmpInst::getSwappedPredicate(Pred);
11116     std::swap(LHS, RHS);
11117     std::swap(FoundLHS, FoundRHS);
11118   }
11119 
11120   // For unsigned, try to reduce it to corresponding signed comparison.
11121   if (Pred == ICmpInst::ICMP_UGT)
11122     // We can replace unsigned predicate with its signed counterpart if all
11123     // involved values are non-negative.
11124     // TODO: We could have better support for unsigned.
11125     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11126       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11127       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11128       // use this fact to prove that LHS and RHS are non-negative.
11129       const SCEV *MinusOne = getMinusOne(LHS->getType());
11130       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11131                                 FoundRHS) &&
11132           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11133                                 FoundRHS))
11134         Pred = ICmpInst::ICMP_SGT;
11135     }
11136 
11137   if (Pred != ICmpInst::ICMP_SGT)
11138     return false;
11139 
11140   auto GetOpFromSExt = [&](const SCEV *S) {
11141     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11142       return Ext->getOperand();
11143     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11144     // the constant in some cases.
11145     return S;
11146   };
11147 
11148   // Acquire values from extensions.
11149   auto *OrigLHS = LHS;
11150   auto *OrigFoundLHS = FoundLHS;
11151   LHS = GetOpFromSExt(LHS);
11152   FoundLHS = GetOpFromSExt(FoundLHS);
11153 
11154   // Is the SGT predicate can be proved trivially or using the found context.
11155   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11156     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11157            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11158                                   FoundRHS, Depth + 1);
11159   };
11160 
11161   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11162     // We want to avoid creation of any new non-constant SCEV. Since we are
11163     // going to compare the operands to RHS, we should be certain that we don't
11164     // need any size extensions for this. So let's decline all cases when the
11165     // sizes of types of LHS and RHS do not match.
11166     // TODO: Maybe try to get RHS from sext to catch more cases?
11167     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11168       return false;
11169 
11170     // Should not overflow.
11171     if (!LHSAddExpr->hasNoSignedWrap())
11172       return false;
11173 
11174     auto *LL = LHSAddExpr->getOperand(0);
11175     auto *LR = LHSAddExpr->getOperand(1);
11176     auto *MinusOne = getMinusOne(RHS->getType());
11177 
11178     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11179     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11180       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11181     };
11182     // Try to prove the following rule:
11183     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11184     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11185     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11186       return true;
11187   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11188     Value *LL, *LR;
11189     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11190 
11191     using namespace llvm::PatternMatch;
11192 
11193     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11194       // Rules for division.
11195       // We are going to perform some comparisons with Denominator and its
11196       // derivative expressions. In general case, creating a SCEV for it may
11197       // lead to a complex analysis of the entire graph, and in particular it
11198       // can request trip count recalculation for the same loop. This would
11199       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11200       // this, we only want to create SCEVs that are constants in this section.
11201       // So we bail if Denominator is not a constant.
11202       if (!isa<ConstantInt>(LR))
11203         return false;
11204 
11205       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11206 
11207       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11208       // then a SCEV for the numerator already exists and matches with FoundLHS.
11209       auto *Numerator = getExistingSCEV(LL);
11210       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11211         return false;
11212 
11213       // Make sure that the numerator matches with FoundLHS and the denominator
11214       // is positive.
11215       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11216         return false;
11217 
11218       auto *DTy = Denominator->getType();
11219       auto *FRHSTy = FoundRHS->getType();
11220       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11221         // One of types is a pointer and another one is not. We cannot extend
11222         // them properly to a wider type, so let us just reject this case.
11223         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11224         // to avoid this check.
11225         return false;
11226 
11227       // Given that:
11228       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11229       auto *WTy = getWiderType(DTy, FRHSTy);
11230       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11231       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11232 
11233       // Try to prove the following rule:
11234       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11235       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11236       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11237       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11238       if (isKnownNonPositive(RHS) &&
11239           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11240         return true;
11241 
11242       // Try to prove the following rule:
11243       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11244       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11245       // If we divide it by Denominator > 2, then:
11246       // 1. If FoundLHS is negative, then the result is 0.
11247       // 2. If FoundLHS is non-negative, then the result is non-negative.
11248       // Anyways, the result is non-negative.
11249       auto *MinusOne = getMinusOne(WTy);
11250       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11251       if (isKnownNegative(RHS) &&
11252           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11253         return true;
11254     }
11255   }
11256 
11257   // If our expression contained SCEVUnknown Phis, and we split it down and now
11258   // need to prove something for them, try to prove the predicate for every
11259   // possible incoming values of those Phis.
11260   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11261     return true;
11262 
11263   return false;
11264 }
11265 
11266 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11267                                         const SCEV *LHS, const SCEV *RHS) {
11268   // zext x u<= sext x, sext x s<= zext x
11269   switch (Pred) {
11270   case ICmpInst::ICMP_SGE:
11271     std::swap(LHS, RHS);
11272     LLVM_FALLTHROUGH;
11273   case ICmpInst::ICMP_SLE: {
11274     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11275     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11276     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11277     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11278       return true;
11279     break;
11280   }
11281   case ICmpInst::ICMP_UGE:
11282     std::swap(LHS, RHS);
11283     LLVM_FALLTHROUGH;
11284   case ICmpInst::ICMP_ULE: {
11285     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11286     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11287     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11288     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11289       return true;
11290     break;
11291   }
11292   default:
11293     break;
11294   };
11295   return false;
11296 }
11297 
11298 bool
11299 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11300                                            const SCEV *LHS, const SCEV *RHS) {
11301   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11302          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11303          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11304          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11305          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11306 }
11307 
11308 bool
11309 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11310                                              const SCEV *LHS, const SCEV *RHS,
11311                                              const SCEV *FoundLHS,
11312                                              const SCEV *FoundRHS) {
11313   switch (Pred) {
11314   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11315   case ICmpInst::ICMP_EQ:
11316   case ICmpInst::ICMP_NE:
11317     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11318       return true;
11319     break;
11320   case ICmpInst::ICMP_SLT:
11321   case ICmpInst::ICMP_SLE:
11322     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11323         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11324       return true;
11325     break;
11326   case ICmpInst::ICMP_SGT:
11327   case ICmpInst::ICMP_SGE:
11328     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11329         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11330       return true;
11331     break;
11332   case ICmpInst::ICMP_ULT:
11333   case ICmpInst::ICMP_ULE:
11334     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11335         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11336       return true;
11337     break;
11338   case ICmpInst::ICMP_UGT:
11339   case ICmpInst::ICMP_UGE:
11340     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11341         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11342       return true;
11343     break;
11344   }
11345 
11346   // Maybe it can be proved via operations?
11347   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11348     return true;
11349 
11350   return false;
11351 }
11352 
11353 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11354                                                      const SCEV *LHS,
11355                                                      const SCEV *RHS,
11356                                                      const SCEV *FoundLHS,
11357                                                      const SCEV *FoundRHS) {
11358   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11359     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11360     // reduce the compile time impact of this optimization.
11361     return false;
11362 
11363   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11364   if (!Addend)
11365     return false;
11366 
11367   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11368 
11369   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11370   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11371   ConstantRange FoundLHSRange =
11372       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
11373 
11374   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11375   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11376 
11377   // We can also compute the range of values for `LHS` that satisfy the
11378   // consequent, "`LHS` `Pred` `RHS`":
11379   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11380   // The antecedent implies the consequent if every value of `LHS` that
11381   // satisfies the antecedent also satisfies the consequent.
11382   return LHSRange.icmp(Pred, ConstRHS);
11383 }
11384 
11385 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11386                                         bool IsSigned) {
11387   assert(isKnownPositive(Stride) && "Positive stride expected!");
11388 
11389   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11390   const SCEV *One = getOne(Stride->getType());
11391 
11392   if (IsSigned) {
11393     APInt MaxRHS = getSignedRangeMax(RHS);
11394     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11395     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11396 
11397     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11398     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11399   }
11400 
11401   APInt MaxRHS = getUnsignedRangeMax(RHS);
11402   APInt MaxValue = APInt::getMaxValue(BitWidth);
11403   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11404 
11405   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11406   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11407 }
11408 
11409 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11410                                         bool IsSigned) {
11411 
11412   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11413   const SCEV *One = getOne(Stride->getType());
11414 
11415   if (IsSigned) {
11416     APInt MinRHS = getSignedRangeMin(RHS);
11417     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11418     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11419 
11420     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11421     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11422   }
11423 
11424   APInt MinRHS = getUnsignedRangeMin(RHS);
11425   APInt MinValue = APInt::getMinValue(BitWidth);
11426   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11427 
11428   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11429   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11430 }
11431 
11432 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta,
11433                                             const SCEV *Step) {
11434   const SCEV *One = getOne(Step->getType());
11435   Delta = getAddExpr(Delta, getMinusSCEV(Step, One));
11436   return getUDivExpr(Delta, Step);
11437 }
11438 
11439 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11440                                                     const SCEV *Stride,
11441                                                     const SCEV *End,
11442                                                     unsigned BitWidth,
11443                                                     bool IsSigned) {
11444 
11445   assert(!isKnownNonPositive(Stride) &&
11446          "Stride is expected strictly positive!");
11447   // Calculate the maximum backedge count based on the range of values
11448   // permitted by Start, End, and Stride.
11449   const SCEV *MaxBECount;
11450   APInt MinStart =
11451       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11452 
11453   APInt StrideForMaxBECount =
11454       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11455 
11456   // We already know that the stride is positive, so we paper over conservatism
11457   // in our range computation by forcing StrideForMaxBECount to be at least one.
11458   // In theory this is unnecessary, but we expect MaxBECount to be a
11459   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11460   // is nothing to constant fold it to).
11461   APInt One(BitWidth, 1, IsSigned);
11462   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11463 
11464   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11465                             : APInt::getMaxValue(BitWidth);
11466   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11467 
11468   // Although End can be a MAX expression we estimate MaxEnd considering only
11469   // the case End = RHS of the loop termination condition. This is safe because
11470   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11471   // taken count.
11472   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11473                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11474 
11475   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11476                               getConstant(StrideForMaxBECount) /* Step */);
11477 
11478   return MaxBECount;
11479 }
11480 
11481 ScalarEvolution::ExitLimit
11482 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11483                                   const Loop *L, bool IsSigned,
11484                                   bool ControlsExit, bool AllowPredicates) {
11485   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11486 
11487   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11488   bool PredicatedIV = false;
11489 
11490   if (!IV && AllowPredicates) {
11491     // Try to make this an AddRec using runtime tests, in the first X
11492     // iterations of this loop, where X is the SCEV expression found by the
11493     // algorithm below.
11494     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11495     PredicatedIV = true;
11496   }
11497 
11498   // Avoid weird loops
11499   if (!IV || IV->getLoop() != L || !IV->isAffine())
11500     return getCouldNotCompute();
11501 
11502   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11503   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11504   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
11505 
11506   const SCEV *Stride = IV->getStepRecurrence(*this);
11507 
11508   bool PositiveStride = isKnownPositive(Stride);
11509 
11510   // Avoid negative or zero stride values.
11511   if (!PositiveStride) {
11512     // We can compute the correct backedge taken count for loops with unknown
11513     // strides if we can prove that the loop is not an infinite loop with side
11514     // effects. Here's the loop structure we are trying to handle -
11515     //
11516     // i = start
11517     // do {
11518     //   A[i] = i;
11519     //   i += s;
11520     // } while (i < end);
11521     //
11522     // The backedge taken count for such loops is evaluated as -
11523     // (max(end, start + stride) - start - 1) /u stride
11524     //
11525     // The additional preconditions that we need to check to prove correctness
11526     // of the above formula is as follows -
11527     //
11528     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11529     //    NoWrap flag).
11530     // b) loop is single exit with no side effects.
11531     //
11532     //
11533     // Precondition a) implies that if the stride is negative, this is a single
11534     // trip loop. The backedge taken count formula reduces to zero in this case.
11535     //
11536     // Precondition b) implies that the unknown stride cannot be zero otherwise
11537     // we have UB.
11538     //
11539     // The positive stride case is the same as isKnownPositive(Stride) returning
11540     // true (original behavior of the function).
11541     //
11542     // We want to make sure that the stride is truly unknown as there are edge
11543     // cases where ScalarEvolution propagates no wrap flags to the
11544     // post-increment/decrement IV even though the increment/decrement operation
11545     // itself is wrapping. The computed backedge taken count may be wrong in
11546     // such cases. This is prevented by checking that the stride is not known to
11547     // be either positive or non-positive. For example, no wrap flags are
11548     // propagated to the post-increment IV of this loop with a trip count of 2 -
11549     //
11550     // unsigned char i;
11551     // for(i=127; i<128; i+=129)
11552     //   A[i] = i;
11553     //
11554     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11555         !loopIsFiniteByAssumption(L))
11556       return getCouldNotCompute();
11557   } else if (!Stride->isOne() && !NoWrap) {
11558     auto isUBOnWrap = [&]() {
11559       // Can we prove this loop *must* be UB if overflow of IV occurs?
11560       // Reasoning goes as follows:
11561       // * Suppose the IV did self wrap.
11562       // * If Stride evenly divides the iteration space, then once wrap
11563       //   occurs, the loop must revisit the same values.
11564       // * We know that RHS is invariant, and that none of those values
11565       //   caused this exit to be taken previously.  Thus, this exit is
11566       //   dynamically dead.
11567       // * If this is the sole exit, then a dead exit implies the loop
11568       //   must be infinite if there are no abnormal exits.
11569       // * If the loop were infinite, then it must either not be mustprogress
11570       //   or have side effects. Otherwise, it must be UB.
11571       // * It can't (by assumption), be UB so we have contradicted our
11572       //   premise and can conclude the IV did not in fact self-wrap.
11573       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
11574       // follows trivially from the fact that every (un)signed-wrapped, but
11575       // not self-wrapped value must be LT than the last value before
11576       // (un)signed wrap.  Since we know that last value didn't exit, nor
11577       // will any smaller one.
11578 
11579       if (!isLoopInvariant(RHS, L))
11580         return false;
11581 
11582       auto *StrideC = dyn_cast<SCEVConstant>(Stride);
11583       if (!StrideC || !StrideC->getAPInt().isPowerOf2())
11584         return false;
11585 
11586       if (!ControlsExit || !loopHasNoAbnormalExits(L))
11587         return false;
11588 
11589       return loopIsFiniteByAssumption(L);
11590     };
11591 
11592     // Avoid proven overflow cases: this will ensure that the backedge taken
11593     // count will not generate any unsigned overflow. Relaxed no-overflow
11594     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11595     // undefined behaviors like the case of C language.
11596     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
11597       return getCouldNotCompute();
11598   }
11599 
11600   const SCEV *Start = IV->getStart();
11601 
11602   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
11603   // Use integer-typed versions for actual computation.
11604   const SCEV *OrigStart = Start;
11605   const SCEV *OrigRHS = RHS;
11606   if (Start->getType()->isPointerTy()) {
11607     Start = getLosslessPtrToIntExpr(Start);
11608     if (isa<SCEVCouldNotCompute>(Start))
11609       return Start;
11610   }
11611   if (RHS->getType()->isPointerTy()) {
11612     RHS = getLosslessPtrToIntExpr(RHS);
11613     if (isa<SCEVCouldNotCompute>(RHS))
11614       return RHS;
11615   }
11616 
11617   const SCEV *End = RHS;
11618   // When the RHS is not invariant, we do not know the end bound of the loop and
11619   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11620   // calculate the MaxBECount, given the start, stride and max value for the end
11621   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11622   // checked above).
11623   if (!isLoopInvariant(RHS, L)) {
11624     const SCEV *MaxBECount = computeMaxBECountForLT(
11625         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11626     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11627                      false /*MaxOrZero*/, Predicates);
11628   }
11629   // If the backedge is taken at least once, then it will be taken
11630   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11631   // is the LHS value of the less-than comparison the first time it is evaluated
11632   // and End is the RHS.
11633   const SCEV *BECountIfBackedgeTaken =
11634     computeBECount(getMinusSCEV(End, Start), Stride);
11635   // If the loop entry is guarded by the result of the backedge test of the
11636   // first loop iteration, then we know the backedge will be taken at least
11637   // once and so the backedge taken count is as above. If not then we use the
11638   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11639   // as if the backedge is taken at least once max(End,Start) is End and so the
11640   // result is as above, and if not max(End,Start) is Start so we get a backedge
11641   // count of zero.
11642   const SCEV *BECount;
11643   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(OrigStart, Stride), OrigRHS))
11644     BECount = BECountIfBackedgeTaken;
11645   else {
11646     // If we know that RHS >= Start in the context of loop, then we know that
11647     // max(RHS, Start) = RHS at this point.
11648     if (isLoopEntryGuardedByCond(
11649             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, OrigRHS, OrigStart))
11650       End = RHS;
11651     else
11652       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11653     BECount = computeBECount(getMinusSCEV(End, Start), Stride);
11654   }
11655 
11656   const SCEV *MaxBECount;
11657   bool MaxOrZero = false;
11658   if (isa<SCEVConstant>(BECount))
11659     MaxBECount = BECount;
11660   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11661     // If we know exactly how many times the backedge will be taken if it's
11662     // taken at least once, then the backedge count will either be that or
11663     // zero.
11664     MaxBECount = BECountIfBackedgeTaken;
11665     MaxOrZero = true;
11666   } else {
11667     MaxBECount = computeMaxBECountForLT(
11668         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11669   }
11670 
11671   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11672       !isa<SCEVCouldNotCompute>(BECount))
11673     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11674 
11675   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11676 }
11677 
11678 ScalarEvolution::ExitLimit
11679 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11680                                      const Loop *L, bool IsSigned,
11681                                      bool ControlsExit, bool AllowPredicates) {
11682   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11683   // We handle only IV > Invariant
11684   if (!isLoopInvariant(RHS, L))
11685     return getCouldNotCompute();
11686 
11687   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11688   if (!IV && AllowPredicates)
11689     // Try to make this an AddRec using runtime tests, in the first X
11690     // iterations of this loop, where X is the SCEV expression found by the
11691     // algorithm below.
11692     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11693 
11694   // Avoid weird loops
11695   if (!IV || IV->getLoop() != L || !IV->isAffine())
11696     return getCouldNotCompute();
11697 
11698   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11699   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11700   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
11701 
11702   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11703 
11704   // Avoid negative or zero stride values
11705   if (!isKnownPositive(Stride))
11706     return getCouldNotCompute();
11707 
11708   // Avoid proven overflow cases: this will ensure that the backedge taken count
11709   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11710   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11711   // behaviors like the case of C language.
11712   if (!Stride->isOne() && !NoWrap)
11713     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
11714       return getCouldNotCompute();
11715 
11716   const SCEV *Start = IV->getStart();
11717   const SCEV *End = RHS;
11718   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11719     // If we know that Start >= RHS in the context of loop, then we know that
11720     // min(RHS, Start) = RHS at this point.
11721     if (isLoopEntryGuardedByCond(
11722             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11723       End = RHS;
11724     else
11725       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11726   }
11727 
11728   if (Start->getType()->isPointerTy()) {
11729     Start = getLosslessPtrToIntExpr(Start);
11730     if (isa<SCEVCouldNotCompute>(Start))
11731       return Start;
11732   }
11733   if (End->getType()->isPointerTy()) {
11734     End = getLosslessPtrToIntExpr(End);
11735     if (isa<SCEVCouldNotCompute>(End))
11736       return End;
11737   }
11738 
11739   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride);
11740 
11741   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11742                             : getUnsignedRangeMax(Start);
11743 
11744   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11745                              : getUnsignedRangeMin(Stride);
11746 
11747   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11748   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11749                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11750 
11751   // Although End can be a MIN expression we estimate MinEnd considering only
11752   // the case End = RHS. This is safe because in the other case (Start - End)
11753   // is zero, leading to a zero maximum backedge taken count.
11754   APInt MinEnd =
11755     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11756              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11757 
11758   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11759                                ? BECount
11760                                : computeBECount(getConstant(MaxStart - MinEnd),
11761                                                 getConstant(MinStride));
11762 
11763   if (isa<SCEVCouldNotCompute>(MaxBECount))
11764     MaxBECount = BECount;
11765 
11766   return ExitLimit(BECount, MaxBECount, false, Predicates);
11767 }
11768 
11769 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11770                                                     ScalarEvolution &SE) const {
11771   if (Range.isFullSet())  // Infinite loop.
11772     return SE.getCouldNotCompute();
11773 
11774   // If the start is a non-zero constant, shift the range to simplify things.
11775   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11776     if (!SC->getValue()->isZero()) {
11777       SmallVector<const SCEV *, 4> Operands(operands());
11778       Operands[0] = SE.getZero(SC->getType());
11779       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11780                                              getNoWrapFlags(FlagNW));
11781       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11782         return ShiftedAddRec->getNumIterationsInRange(
11783             Range.subtract(SC->getAPInt()), SE);
11784       // This is strange and shouldn't happen.
11785       return SE.getCouldNotCompute();
11786     }
11787 
11788   // The only time we can solve this is when we have all constant indices.
11789   // Otherwise, we cannot determine the overflow conditions.
11790   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11791     return SE.getCouldNotCompute();
11792 
11793   // Okay at this point we know that all elements of the chrec are constants and
11794   // that the start element is zero.
11795 
11796   // First check to see if the range contains zero.  If not, the first
11797   // iteration exits.
11798   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11799   if (!Range.contains(APInt(BitWidth, 0)))
11800     return SE.getZero(getType());
11801 
11802   if (isAffine()) {
11803     // If this is an affine expression then we have this situation:
11804     //   Solve {0,+,A} in Range  ===  Ax in Range
11805 
11806     // We know that zero is in the range.  If A is positive then we know that
11807     // the upper value of the range must be the first possible exit value.
11808     // If A is negative then the lower of the range is the last possible loop
11809     // value.  Also note that we already checked for a full range.
11810     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11811     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11812 
11813     // The exit value should be (End+A)/A.
11814     APInt ExitVal = (End + A).udiv(A);
11815     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11816 
11817     // Evaluate at the exit value.  If we really did fall out of the valid
11818     // range, then we computed our trip count, otherwise wrap around or other
11819     // things must have happened.
11820     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11821     if (Range.contains(Val->getValue()))
11822       return SE.getCouldNotCompute();  // Something strange happened
11823 
11824     // Ensure that the previous value is in the range.  This is a sanity check.
11825     assert(Range.contains(
11826            EvaluateConstantChrecAtConstant(this,
11827            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11828            "Linear scev computation is off in a bad way!");
11829     return SE.getConstant(ExitValue);
11830   }
11831 
11832   if (isQuadratic()) {
11833     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11834       return SE.getConstant(S.getValue());
11835   }
11836 
11837   return SE.getCouldNotCompute();
11838 }
11839 
11840 const SCEVAddRecExpr *
11841 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11842   assert(getNumOperands() > 1 && "AddRec with zero step?");
11843   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11844   // but in this case we cannot guarantee that the value returned will be an
11845   // AddRec because SCEV does not have a fixed point where it stops
11846   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11847   // may happen if we reach arithmetic depth limit while simplifying. So we
11848   // construct the returned value explicitly.
11849   SmallVector<const SCEV *, 3> Ops;
11850   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11851   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11852   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11853     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11854   // We know that the last operand is not a constant zero (otherwise it would
11855   // have been popped out earlier). This guarantees us that if the result has
11856   // the same last operand, then it will also not be popped out, meaning that
11857   // the returned value will be an AddRec.
11858   const SCEV *Last = getOperand(getNumOperands() - 1);
11859   assert(!Last->isZero() && "Recurrency with zero step?");
11860   Ops.push_back(Last);
11861   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11862                                                SCEV::FlagAnyWrap));
11863 }
11864 
11865 // Return true when S contains at least an undef value.
11866 static inline bool containsUndefs(const SCEV *S) {
11867   return SCEVExprContains(S, [](const SCEV *S) {
11868     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11869       return isa<UndefValue>(SU->getValue());
11870     return false;
11871   });
11872 }
11873 
11874 namespace {
11875 
11876 // Collect all steps of SCEV expressions.
11877 struct SCEVCollectStrides {
11878   ScalarEvolution &SE;
11879   SmallVectorImpl<const SCEV *> &Strides;
11880 
11881   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11882       : SE(SE), Strides(S) {}
11883 
11884   bool follow(const SCEV *S) {
11885     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11886       Strides.push_back(AR->getStepRecurrence(SE));
11887     return true;
11888   }
11889 
11890   bool isDone() const { return false; }
11891 };
11892 
11893 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11894 struct SCEVCollectTerms {
11895   SmallVectorImpl<const SCEV *> &Terms;
11896 
11897   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11898 
11899   bool follow(const SCEV *S) {
11900     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11901         isa<SCEVSignExtendExpr>(S)) {
11902       if (!containsUndefs(S))
11903         Terms.push_back(S);
11904 
11905       // Stop recursion: once we collected a term, do not walk its operands.
11906       return false;
11907     }
11908 
11909     // Keep looking.
11910     return true;
11911   }
11912 
11913   bool isDone() const { return false; }
11914 };
11915 
11916 // Check if a SCEV contains an AddRecExpr.
11917 struct SCEVHasAddRec {
11918   bool &ContainsAddRec;
11919 
11920   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11921     ContainsAddRec = false;
11922   }
11923 
11924   bool follow(const SCEV *S) {
11925     if (isa<SCEVAddRecExpr>(S)) {
11926       ContainsAddRec = true;
11927 
11928       // Stop recursion: once we collected a term, do not walk its operands.
11929       return false;
11930     }
11931 
11932     // Keep looking.
11933     return true;
11934   }
11935 
11936   bool isDone() const { return false; }
11937 };
11938 
11939 // Find factors that are multiplied with an expression that (possibly as a
11940 // subexpression) contains an AddRecExpr. In the expression:
11941 //
11942 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11943 //
11944 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11945 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11946 // parameters as they form a product with an induction variable.
11947 //
11948 // This collector expects all array size parameters to be in the same MulExpr.
11949 // It might be necessary to later add support for collecting parameters that are
11950 // spread over different nested MulExpr.
11951 struct SCEVCollectAddRecMultiplies {
11952   SmallVectorImpl<const SCEV *> &Terms;
11953   ScalarEvolution &SE;
11954 
11955   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11956       : Terms(T), SE(SE) {}
11957 
11958   bool follow(const SCEV *S) {
11959     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11960       bool HasAddRec = false;
11961       SmallVector<const SCEV *, 0> Operands;
11962       for (auto Op : Mul->operands()) {
11963         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11964         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11965           Operands.push_back(Op);
11966         } else if (Unknown) {
11967           HasAddRec = true;
11968         } else {
11969           bool ContainsAddRec = false;
11970           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11971           visitAll(Op, ContiansAddRec);
11972           HasAddRec |= ContainsAddRec;
11973         }
11974       }
11975       if (Operands.size() == 0)
11976         return true;
11977 
11978       if (!HasAddRec)
11979         return false;
11980 
11981       Terms.push_back(SE.getMulExpr(Operands));
11982       // Stop recursion: once we collected a term, do not walk its operands.
11983       return false;
11984     }
11985 
11986     // Keep looking.
11987     return true;
11988   }
11989 
11990   bool isDone() const { return false; }
11991 };
11992 
11993 } // end anonymous namespace
11994 
11995 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11996 /// two places:
11997 ///   1) The strides of AddRec expressions.
11998 ///   2) Unknowns that are multiplied with AddRec expressions.
11999 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
12000     SmallVectorImpl<const SCEV *> &Terms) {
12001   SmallVector<const SCEV *, 4> Strides;
12002   SCEVCollectStrides StrideCollector(*this, Strides);
12003   visitAll(Expr, StrideCollector);
12004 
12005   LLVM_DEBUG({
12006     dbgs() << "Strides:\n";
12007     for (const SCEV *S : Strides)
12008       dbgs() << *S << "\n";
12009   });
12010 
12011   for (const SCEV *S : Strides) {
12012     SCEVCollectTerms TermCollector(Terms);
12013     visitAll(S, TermCollector);
12014   }
12015 
12016   LLVM_DEBUG({
12017     dbgs() << "Terms:\n";
12018     for (const SCEV *T : Terms)
12019       dbgs() << *T << "\n";
12020   });
12021 
12022   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
12023   visitAll(Expr, MulCollector);
12024 }
12025 
12026 static bool findArrayDimensionsRec(ScalarEvolution &SE,
12027                                    SmallVectorImpl<const SCEV *> &Terms,
12028                                    SmallVectorImpl<const SCEV *> &Sizes) {
12029   int Last = Terms.size() - 1;
12030   const SCEV *Step = Terms[Last];
12031 
12032   // End of recursion.
12033   if (Last == 0) {
12034     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
12035       SmallVector<const SCEV *, 2> Qs;
12036       for (const SCEV *Op : M->operands())
12037         if (!isa<SCEVConstant>(Op))
12038           Qs.push_back(Op);
12039 
12040       Step = SE.getMulExpr(Qs);
12041     }
12042 
12043     Sizes.push_back(Step);
12044     return true;
12045   }
12046 
12047   for (const SCEV *&Term : Terms) {
12048     // Normalize the terms before the next call to findArrayDimensionsRec.
12049     const SCEV *Q, *R;
12050     SCEVDivision::divide(SE, Term, Step, &Q, &R);
12051 
12052     // Bail out when GCD does not evenly divide one of the terms.
12053     if (!R->isZero())
12054       return false;
12055 
12056     Term = Q;
12057   }
12058 
12059   // Remove all SCEVConstants.
12060   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
12061 
12062   if (Terms.size() > 0)
12063     if (!findArrayDimensionsRec(SE, Terms, Sizes))
12064       return false;
12065 
12066   Sizes.push_back(Step);
12067   return true;
12068 }
12069 
12070 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
12071 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
12072   for (const SCEV *T : Terms)
12073     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
12074       return true;
12075 
12076   return false;
12077 }
12078 
12079 // Return the number of product terms in S.
12080 static inline int numberOfTerms(const SCEV *S) {
12081   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
12082     return Expr->getNumOperands();
12083   return 1;
12084 }
12085 
12086 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
12087   if (isa<SCEVConstant>(T))
12088     return nullptr;
12089 
12090   if (isa<SCEVUnknown>(T))
12091     return T;
12092 
12093   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
12094     SmallVector<const SCEV *, 2> Factors;
12095     for (const SCEV *Op : M->operands())
12096       if (!isa<SCEVConstant>(Op))
12097         Factors.push_back(Op);
12098 
12099     return SE.getMulExpr(Factors);
12100   }
12101 
12102   return T;
12103 }
12104 
12105 /// Return the size of an element read or written by Inst.
12106 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12107   Type *Ty;
12108   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12109     Ty = Store->getValueOperand()->getType();
12110   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12111     Ty = Load->getType();
12112   else
12113     return nullptr;
12114 
12115   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12116   return getSizeOfExpr(ETy, Ty);
12117 }
12118 
12119 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
12120                                           SmallVectorImpl<const SCEV *> &Sizes,
12121                                           const SCEV *ElementSize) {
12122   if (Terms.size() < 1 || !ElementSize)
12123     return;
12124 
12125   // Early return when Terms do not contain parameters: we do not delinearize
12126   // non parametric SCEVs.
12127   if (!containsParameters(Terms))
12128     return;
12129 
12130   LLVM_DEBUG({
12131     dbgs() << "Terms:\n";
12132     for (const SCEV *T : Terms)
12133       dbgs() << *T << "\n";
12134   });
12135 
12136   // Remove duplicates.
12137   array_pod_sort(Terms.begin(), Terms.end());
12138   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
12139 
12140   // Put larger terms first.
12141   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
12142     return numberOfTerms(LHS) > numberOfTerms(RHS);
12143   });
12144 
12145   // Try to divide all terms by the element size. If term is not divisible by
12146   // element size, proceed with the original term.
12147   for (const SCEV *&Term : Terms) {
12148     const SCEV *Q, *R;
12149     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
12150     if (!Q->isZero())
12151       Term = Q;
12152   }
12153 
12154   SmallVector<const SCEV *, 4> NewTerms;
12155 
12156   // Remove constant factors.
12157   for (const SCEV *T : Terms)
12158     if (const SCEV *NewT = removeConstantFactors(*this, T))
12159       NewTerms.push_back(NewT);
12160 
12161   LLVM_DEBUG({
12162     dbgs() << "Terms after sorting:\n";
12163     for (const SCEV *T : NewTerms)
12164       dbgs() << *T << "\n";
12165   });
12166 
12167   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
12168     Sizes.clear();
12169     return;
12170   }
12171 
12172   // The last element to be pushed into Sizes is the size of an element.
12173   Sizes.push_back(ElementSize);
12174 
12175   LLVM_DEBUG({
12176     dbgs() << "Sizes:\n";
12177     for (const SCEV *S : Sizes)
12178       dbgs() << *S << "\n";
12179   });
12180 }
12181 
12182 void ScalarEvolution::computeAccessFunctions(
12183     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
12184     SmallVectorImpl<const SCEV *> &Sizes) {
12185   // Early exit in case this SCEV is not an affine multivariate function.
12186   if (Sizes.empty())
12187     return;
12188 
12189   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
12190     if (!AR->isAffine())
12191       return;
12192 
12193   const SCEV *Res = Expr;
12194   int Last = Sizes.size() - 1;
12195   for (int i = Last; i >= 0; i--) {
12196     const SCEV *Q, *R;
12197     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
12198 
12199     LLVM_DEBUG({
12200       dbgs() << "Res: " << *Res << "\n";
12201       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
12202       dbgs() << "Res divided by Sizes[i]:\n";
12203       dbgs() << "Quotient: " << *Q << "\n";
12204       dbgs() << "Remainder: " << *R << "\n";
12205     });
12206 
12207     Res = Q;
12208 
12209     // Do not record the last subscript corresponding to the size of elements in
12210     // the array.
12211     if (i == Last) {
12212 
12213       // Bail out if the remainder is too complex.
12214       if (isa<SCEVAddRecExpr>(R)) {
12215         Subscripts.clear();
12216         Sizes.clear();
12217         return;
12218       }
12219 
12220       continue;
12221     }
12222 
12223     // Record the access function for the current subscript.
12224     Subscripts.push_back(R);
12225   }
12226 
12227   // Also push in last position the remainder of the last division: it will be
12228   // the access function of the innermost dimension.
12229   Subscripts.push_back(Res);
12230 
12231   std::reverse(Subscripts.begin(), Subscripts.end());
12232 
12233   LLVM_DEBUG({
12234     dbgs() << "Subscripts:\n";
12235     for (const SCEV *S : Subscripts)
12236       dbgs() << *S << "\n";
12237   });
12238 }
12239 
12240 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
12241 /// sizes of an array access. Returns the remainder of the delinearization that
12242 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
12243 /// the multiples of SCEV coefficients: that is a pattern matching of sub
12244 /// expressions in the stride and base of a SCEV corresponding to the
12245 /// computation of a GCD (greatest common divisor) of base and stride.  When
12246 /// SCEV->delinearize fails, it returns the SCEV unchanged.
12247 ///
12248 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
12249 ///
12250 ///  void foo(long n, long m, long o, double A[n][m][o]) {
12251 ///
12252 ///    for (long i = 0; i < n; i++)
12253 ///      for (long j = 0; j < m; j++)
12254 ///        for (long k = 0; k < o; k++)
12255 ///          A[i][j][k] = 1.0;
12256 ///  }
12257 ///
12258 /// the delinearization input is the following AddRec SCEV:
12259 ///
12260 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
12261 ///
12262 /// From this SCEV, we are able to say that the base offset of the access is %A
12263 /// because it appears as an offset that does not divide any of the strides in
12264 /// the loops:
12265 ///
12266 ///  CHECK: Base offset: %A
12267 ///
12268 /// and then SCEV->delinearize determines the size of some of the dimensions of
12269 /// the array as these are the multiples by which the strides are happening:
12270 ///
12271 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
12272 ///
12273 /// Note that the outermost dimension remains of UnknownSize because there are
12274 /// no strides that would help identifying the size of the last dimension: when
12275 /// the array has been statically allocated, one could compute the size of that
12276 /// dimension by dividing the overall size of the array by the size of the known
12277 /// dimensions: %m * %o * 8.
12278 ///
12279 /// Finally delinearize provides the access functions for the array reference
12280 /// that does correspond to A[i][j][k] of the above C testcase:
12281 ///
12282 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
12283 ///
12284 /// The testcases are checking the output of a function pass:
12285 /// DelinearizationPass that walks through all loads and stores of a function
12286 /// asking for the SCEV of the memory access with respect to all enclosing
12287 /// loops, calling SCEV->delinearize on that and printing the results.
12288 void ScalarEvolution::delinearize(const SCEV *Expr,
12289                                  SmallVectorImpl<const SCEV *> &Subscripts,
12290                                  SmallVectorImpl<const SCEV *> &Sizes,
12291                                  const SCEV *ElementSize) {
12292   // First step: collect parametric terms.
12293   SmallVector<const SCEV *, 4> Terms;
12294   collectParametricTerms(Expr, Terms);
12295 
12296   if (Terms.empty())
12297     return;
12298 
12299   // Second step: find subscript sizes.
12300   findArrayDimensions(Terms, Sizes, ElementSize);
12301 
12302   if (Sizes.empty())
12303     return;
12304 
12305   // Third step: compute the access functions for each subscript.
12306   computeAccessFunctions(Expr, Subscripts, Sizes);
12307 
12308   if (Subscripts.empty())
12309     return;
12310 
12311   LLVM_DEBUG({
12312     dbgs() << "succeeded to delinearize " << *Expr << "\n";
12313     dbgs() << "ArrayDecl[UnknownSize]";
12314     for (const SCEV *S : Sizes)
12315       dbgs() << "[" << *S << "]";
12316 
12317     dbgs() << "\nArrayRef";
12318     for (const SCEV *S : Subscripts)
12319       dbgs() << "[" << *S << "]";
12320     dbgs() << "\n";
12321   });
12322 }
12323 
12324 bool ScalarEvolution::getIndexExpressionsFromGEP(
12325     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
12326     SmallVectorImpl<int> &Sizes) {
12327   assert(Subscripts.empty() && Sizes.empty() &&
12328          "Expected output lists to be empty on entry to this function.");
12329   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
12330   Type *Ty = GEP->getPointerOperandType();
12331   bool DroppedFirstDim = false;
12332   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
12333     const SCEV *Expr = getSCEV(GEP->getOperand(i));
12334     if (i == 1) {
12335       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
12336         Ty = PtrTy->getElementType();
12337       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
12338         Ty = ArrayTy->getElementType();
12339       } else {
12340         Subscripts.clear();
12341         Sizes.clear();
12342         return false;
12343       }
12344       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
12345         if (Const->getValue()->isZero()) {
12346           DroppedFirstDim = true;
12347           continue;
12348         }
12349       Subscripts.push_back(Expr);
12350       continue;
12351     }
12352 
12353     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
12354     if (!ArrayTy) {
12355       Subscripts.clear();
12356       Sizes.clear();
12357       return false;
12358     }
12359 
12360     Subscripts.push_back(Expr);
12361     if (!(DroppedFirstDim && i == 2))
12362       Sizes.push_back(ArrayTy->getNumElements());
12363 
12364     Ty = ArrayTy->getElementType();
12365   }
12366   return !Subscripts.empty();
12367 }
12368 
12369 //===----------------------------------------------------------------------===//
12370 //                   SCEVCallbackVH Class Implementation
12371 //===----------------------------------------------------------------------===//
12372 
12373 void ScalarEvolution::SCEVCallbackVH::deleted() {
12374   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12375   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12376     SE->ConstantEvolutionLoopExitValue.erase(PN);
12377   SE->eraseValueFromMap(getValPtr());
12378   // this now dangles!
12379 }
12380 
12381 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12382   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12383 
12384   // Forget all the expressions associated with users of the old value,
12385   // so that future queries will recompute the expressions using the new
12386   // value.
12387   Value *Old = getValPtr();
12388   SmallVector<User *, 16> Worklist(Old->users());
12389   SmallPtrSet<User *, 8> Visited;
12390   while (!Worklist.empty()) {
12391     User *U = Worklist.pop_back_val();
12392     // Deleting the Old value will cause this to dangle. Postpone
12393     // that until everything else is done.
12394     if (U == Old)
12395       continue;
12396     if (!Visited.insert(U).second)
12397       continue;
12398     if (PHINode *PN = dyn_cast<PHINode>(U))
12399       SE->ConstantEvolutionLoopExitValue.erase(PN);
12400     SE->eraseValueFromMap(U);
12401     llvm::append_range(Worklist, U->users());
12402   }
12403   // Delete the Old value.
12404   if (PHINode *PN = dyn_cast<PHINode>(Old))
12405     SE->ConstantEvolutionLoopExitValue.erase(PN);
12406   SE->eraseValueFromMap(Old);
12407   // this now dangles!
12408 }
12409 
12410 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12411   : CallbackVH(V), SE(se) {}
12412 
12413 //===----------------------------------------------------------------------===//
12414 //                   ScalarEvolution Class Implementation
12415 //===----------------------------------------------------------------------===//
12416 
12417 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12418                                  AssumptionCache &AC, DominatorTree &DT,
12419                                  LoopInfo &LI)
12420     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12421       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12422       LoopDispositions(64), BlockDispositions(64) {
12423   // To use guards for proving predicates, we need to scan every instruction in
12424   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12425   // time if the IR does not actually contain any calls to
12426   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12427   //
12428   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12429   // to _add_ guards to the module when there weren't any before, and wants
12430   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12431   // efficient in lieu of being smart in that rather obscure case.
12432 
12433   auto *GuardDecl = F.getParent()->getFunction(
12434       Intrinsic::getName(Intrinsic::experimental_guard));
12435   HasGuards = GuardDecl && !GuardDecl->use_empty();
12436 }
12437 
12438 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12439     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12440       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12441       ValueExprMap(std::move(Arg.ValueExprMap)),
12442       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12443       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12444       PendingMerges(std::move(Arg.PendingMerges)),
12445       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12446       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12447       PredicatedBackedgeTakenCounts(
12448           std::move(Arg.PredicatedBackedgeTakenCounts)),
12449       ConstantEvolutionLoopExitValue(
12450           std::move(Arg.ConstantEvolutionLoopExitValue)),
12451       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12452       LoopDispositions(std::move(Arg.LoopDispositions)),
12453       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12454       BlockDispositions(std::move(Arg.BlockDispositions)),
12455       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12456       SignedRanges(std::move(Arg.SignedRanges)),
12457       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12458       UniquePreds(std::move(Arg.UniquePreds)),
12459       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12460       LoopUsers(std::move(Arg.LoopUsers)),
12461       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12462       FirstUnknown(Arg.FirstUnknown) {
12463   Arg.FirstUnknown = nullptr;
12464 }
12465 
12466 ScalarEvolution::~ScalarEvolution() {
12467   // Iterate through all the SCEVUnknown instances and call their
12468   // destructors, so that they release their references to their values.
12469   for (SCEVUnknown *U = FirstUnknown; U;) {
12470     SCEVUnknown *Tmp = U;
12471     U = U->Next;
12472     Tmp->~SCEVUnknown();
12473   }
12474   FirstUnknown = nullptr;
12475 
12476   ExprValueMap.clear();
12477   ValueExprMap.clear();
12478   HasRecMap.clear();
12479   BackedgeTakenCounts.clear();
12480   PredicatedBackedgeTakenCounts.clear();
12481 
12482   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12483   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12484   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12485   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12486   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12487 }
12488 
12489 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12490   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12491 }
12492 
12493 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12494                           const Loop *L) {
12495   // Print all inner loops first
12496   for (Loop *I : *L)
12497     PrintLoopInfo(OS, SE, I);
12498 
12499   OS << "Loop ";
12500   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12501   OS << ": ";
12502 
12503   SmallVector<BasicBlock *, 8> ExitingBlocks;
12504   L->getExitingBlocks(ExitingBlocks);
12505   if (ExitingBlocks.size() != 1)
12506     OS << "<multiple exits> ";
12507 
12508   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12509     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12510   else
12511     OS << "Unpredictable backedge-taken count.\n";
12512 
12513   if (ExitingBlocks.size() > 1)
12514     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12515       OS << "  exit count for " << ExitingBlock->getName() << ": "
12516          << *SE->getExitCount(L, ExitingBlock) << "\n";
12517     }
12518 
12519   OS << "Loop ";
12520   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12521   OS << ": ";
12522 
12523   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12524     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12525     if (SE->isBackedgeTakenCountMaxOrZero(L))
12526       OS << ", actual taken count either this or zero.";
12527   } else {
12528     OS << "Unpredictable max backedge-taken count. ";
12529   }
12530 
12531   OS << "\n"
12532         "Loop ";
12533   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12534   OS << ": ";
12535 
12536   SCEVUnionPredicate Pred;
12537   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12538   if (!isa<SCEVCouldNotCompute>(PBT)) {
12539     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12540     OS << " Predicates:\n";
12541     Pred.print(OS, 4);
12542   } else {
12543     OS << "Unpredictable predicated backedge-taken count. ";
12544   }
12545   OS << "\n";
12546 
12547   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12548     OS << "Loop ";
12549     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12550     OS << ": ";
12551     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12552   }
12553 }
12554 
12555 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12556   switch (LD) {
12557   case ScalarEvolution::LoopVariant:
12558     return "Variant";
12559   case ScalarEvolution::LoopInvariant:
12560     return "Invariant";
12561   case ScalarEvolution::LoopComputable:
12562     return "Computable";
12563   }
12564   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12565 }
12566 
12567 void ScalarEvolution::print(raw_ostream &OS) const {
12568   // ScalarEvolution's implementation of the print method is to print
12569   // out SCEV values of all instructions that are interesting. Doing
12570   // this potentially causes it to create new SCEV objects though,
12571   // which technically conflicts with the const qualifier. This isn't
12572   // observable from outside the class though, so casting away the
12573   // const isn't dangerous.
12574   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12575 
12576   if (ClassifyExpressions) {
12577     OS << "Classifying expressions for: ";
12578     F.printAsOperand(OS, /*PrintType=*/false);
12579     OS << "\n";
12580     for (Instruction &I : instructions(F))
12581       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12582         OS << I << '\n';
12583         OS << "  -->  ";
12584         const SCEV *SV = SE.getSCEV(&I);
12585         SV->print(OS);
12586         if (!isa<SCEVCouldNotCompute>(SV)) {
12587           OS << " U: ";
12588           SE.getUnsignedRange(SV).print(OS);
12589           OS << " S: ";
12590           SE.getSignedRange(SV).print(OS);
12591         }
12592 
12593         const Loop *L = LI.getLoopFor(I.getParent());
12594 
12595         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12596         if (AtUse != SV) {
12597           OS << "  -->  ";
12598           AtUse->print(OS);
12599           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12600             OS << " U: ";
12601             SE.getUnsignedRange(AtUse).print(OS);
12602             OS << " S: ";
12603             SE.getSignedRange(AtUse).print(OS);
12604           }
12605         }
12606 
12607         if (L) {
12608           OS << "\t\t" "Exits: ";
12609           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12610           if (!SE.isLoopInvariant(ExitValue, L)) {
12611             OS << "<<Unknown>>";
12612           } else {
12613             OS << *ExitValue;
12614           }
12615 
12616           bool First = true;
12617           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12618             if (First) {
12619               OS << "\t\t" "LoopDispositions: { ";
12620               First = false;
12621             } else {
12622               OS << ", ";
12623             }
12624 
12625             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12626             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12627           }
12628 
12629           for (auto *InnerL : depth_first(L)) {
12630             if (InnerL == L)
12631               continue;
12632             if (First) {
12633               OS << "\t\t" "LoopDispositions: { ";
12634               First = false;
12635             } else {
12636               OS << ", ";
12637             }
12638 
12639             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12640             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12641           }
12642 
12643           OS << " }";
12644         }
12645 
12646         OS << "\n";
12647       }
12648   }
12649 
12650   OS << "Determining loop execution counts for: ";
12651   F.printAsOperand(OS, /*PrintType=*/false);
12652   OS << "\n";
12653   for (Loop *I : LI)
12654     PrintLoopInfo(OS, &SE, I);
12655 }
12656 
12657 ScalarEvolution::LoopDisposition
12658 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12659   auto &Values = LoopDispositions[S];
12660   for (auto &V : Values) {
12661     if (V.getPointer() == L)
12662       return V.getInt();
12663   }
12664   Values.emplace_back(L, LoopVariant);
12665   LoopDisposition D = computeLoopDisposition(S, L);
12666   auto &Values2 = LoopDispositions[S];
12667   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12668     if (V.getPointer() == L) {
12669       V.setInt(D);
12670       break;
12671     }
12672   }
12673   return D;
12674 }
12675 
12676 ScalarEvolution::LoopDisposition
12677 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12678   switch (S->getSCEVType()) {
12679   case scConstant:
12680     return LoopInvariant;
12681   case scPtrToInt:
12682   case scTruncate:
12683   case scZeroExtend:
12684   case scSignExtend:
12685     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12686   case scAddRecExpr: {
12687     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12688 
12689     // If L is the addrec's loop, it's computable.
12690     if (AR->getLoop() == L)
12691       return LoopComputable;
12692 
12693     // Add recurrences are never invariant in the function-body (null loop).
12694     if (!L)
12695       return LoopVariant;
12696 
12697     // Everything that is not defined at loop entry is variant.
12698     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12699       return LoopVariant;
12700     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12701            " dominate the contained loop's header?");
12702 
12703     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12704     if (AR->getLoop()->contains(L))
12705       return LoopInvariant;
12706 
12707     // This recurrence is variant w.r.t. L if any of its operands
12708     // are variant.
12709     for (auto *Op : AR->operands())
12710       if (!isLoopInvariant(Op, L))
12711         return LoopVariant;
12712 
12713     // Otherwise it's loop-invariant.
12714     return LoopInvariant;
12715   }
12716   case scAddExpr:
12717   case scMulExpr:
12718   case scUMaxExpr:
12719   case scSMaxExpr:
12720   case scUMinExpr:
12721   case scSMinExpr: {
12722     bool HasVarying = false;
12723     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12724       LoopDisposition D = getLoopDisposition(Op, L);
12725       if (D == LoopVariant)
12726         return LoopVariant;
12727       if (D == LoopComputable)
12728         HasVarying = true;
12729     }
12730     return HasVarying ? LoopComputable : LoopInvariant;
12731   }
12732   case scUDivExpr: {
12733     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12734     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12735     if (LD == LoopVariant)
12736       return LoopVariant;
12737     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12738     if (RD == LoopVariant)
12739       return LoopVariant;
12740     return (LD == LoopInvariant && RD == LoopInvariant) ?
12741            LoopInvariant : LoopComputable;
12742   }
12743   case scUnknown:
12744     // All non-instruction values are loop invariant.  All instructions are loop
12745     // invariant if they are not contained in the specified loop.
12746     // Instructions are never considered invariant in the function body
12747     // (null loop) because they are defined within the "loop".
12748     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12749       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12750     return LoopInvariant;
12751   case scCouldNotCompute:
12752     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12753   }
12754   llvm_unreachable("Unknown SCEV kind!");
12755 }
12756 
12757 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12758   return getLoopDisposition(S, L) == LoopInvariant;
12759 }
12760 
12761 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12762   return getLoopDisposition(S, L) == LoopComputable;
12763 }
12764 
12765 ScalarEvolution::BlockDisposition
12766 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12767   auto &Values = BlockDispositions[S];
12768   for (auto &V : Values) {
12769     if (V.getPointer() == BB)
12770       return V.getInt();
12771   }
12772   Values.emplace_back(BB, DoesNotDominateBlock);
12773   BlockDisposition D = computeBlockDisposition(S, BB);
12774   auto &Values2 = BlockDispositions[S];
12775   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12776     if (V.getPointer() == BB) {
12777       V.setInt(D);
12778       break;
12779     }
12780   }
12781   return D;
12782 }
12783 
12784 ScalarEvolution::BlockDisposition
12785 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12786   switch (S->getSCEVType()) {
12787   case scConstant:
12788     return ProperlyDominatesBlock;
12789   case scPtrToInt:
12790   case scTruncate:
12791   case scZeroExtend:
12792   case scSignExtend:
12793     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12794   case scAddRecExpr: {
12795     // This uses a "dominates" query instead of "properly dominates" query
12796     // to test for proper dominance too, because the instruction which
12797     // produces the addrec's value is a PHI, and a PHI effectively properly
12798     // dominates its entire containing block.
12799     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12800     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12801       return DoesNotDominateBlock;
12802 
12803     // Fall through into SCEVNAryExpr handling.
12804     LLVM_FALLTHROUGH;
12805   }
12806   case scAddExpr:
12807   case scMulExpr:
12808   case scUMaxExpr:
12809   case scSMaxExpr:
12810   case scUMinExpr:
12811   case scSMinExpr: {
12812     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12813     bool Proper = true;
12814     for (const SCEV *NAryOp : NAry->operands()) {
12815       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12816       if (D == DoesNotDominateBlock)
12817         return DoesNotDominateBlock;
12818       if (D == DominatesBlock)
12819         Proper = false;
12820     }
12821     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12822   }
12823   case scUDivExpr: {
12824     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12825     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12826     BlockDisposition LD = getBlockDisposition(LHS, BB);
12827     if (LD == DoesNotDominateBlock)
12828       return DoesNotDominateBlock;
12829     BlockDisposition RD = getBlockDisposition(RHS, BB);
12830     if (RD == DoesNotDominateBlock)
12831       return DoesNotDominateBlock;
12832     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12833       ProperlyDominatesBlock : DominatesBlock;
12834   }
12835   case scUnknown:
12836     if (Instruction *I =
12837           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12838       if (I->getParent() == BB)
12839         return DominatesBlock;
12840       if (DT.properlyDominates(I->getParent(), BB))
12841         return ProperlyDominatesBlock;
12842       return DoesNotDominateBlock;
12843     }
12844     return ProperlyDominatesBlock;
12845   case scCouldNotCompute:
12846     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12847   }
12848   llvm_unreachable("Unknown SCEV kind!");
12849 }
12850 
12851 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12852   return getBlockDisposition(S, BB) >= DominatesBlock;
12853 }
12854 
12855 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12856   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12857 }
12858 
12859 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12860   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12861 }
12862 
12863 void
12864 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12865   ValuesAtScopes.erase(S);
12866   LoopDispositions.erase(S);
12867   BlockDispositions.erase(S);
12868   UnsignedRanges.erase(S);
12869   SignedRanges.erase(S);
12870   ExprValueMap.erase(S);
12871   HasRecMap.erase(S);
12872   MinTrailingZerosCache.erase(S);
12873 
12874   for (auto I = PredicatedSCEVRewrites.begin();
12875        I != PredicatedSCEVRewrites.end();) {
12876     std::pair<const SCEV *, const Loop *> Entry = I->first;
12877     if (Entry.first == S)
12878       PredicatedSCEVRewrites.erase(I++);
12879     else
12880       ++I;
12881   }
12882 
12883   auto RemoveSCEVFromBackedgeMap =
12884       [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12885         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12886           BackedgeTakenInfo &BEInfo = I->second;
12887           if (BEInfo.hasOperand(S))
12888             Map.erase(I++);
12889           else
12890             ++I;
12891         }
12892       };
12893 
12894   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12895   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12896 }
12897 
12898 void
12899 ScalarEvolution::getUsedLoops(const SCEV *S,
12900                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12901   struct FindUsedLoops {
12902     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12903         : LoopsUsed(LoopsUsed) {}
12904     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12905     bool follow(const SCEV *S) {
12906       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12907         LoopsUsed.insert(AR->getLoop());
12908       return true;
12909     }
12910 
12911     bool isDone() const { return false; }
12912   };
12913 
12914   FindUsedLoops F(LoopsUsed);
12915   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12916 }
12917 
12918 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12919   SmallPtrSet<const Loop *, 8> LoopsUsed;
12920   getUsedLoops(S, LoopsUsed);
12921   for (auto *L : LoopsUsed)
12922     LoopUsers[L].push_back(S);
12923 }
12924 
12925 void ScalarEvolution::verify() const {
12926   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12927   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12928 
12929   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12930 
12931   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12932   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12933     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12934 
12935     const SCEV *visitConstant(const SCEVConstant *Constant) {
12936       return SE.getConstant(Constant->getAPInt());
12937     }
12938 
12939     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12940       return SE.getUnknown(Expr->getValue());
12941     }
12942 
12943     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12944       return SE.getCouldNotCompute();
12945     }
12946   };
12947 
12948   SCEVMapper SCM(SE2);
12949 
12950   while (!LoopStack.empty()) {
12951     auto *L = LoopStack.pop_back_val();
12952     llvm::append_range(LoopStack, *L);
12953 
12954     auto *CurBECount = SCM.visit(
12955         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12956     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12957 
12958     if (CurBECount == SE2.getCouldNotCompute() ||
12959         NewBECount == SE2.getCouldNotCompute()) {
12960       // NB! This situation is legal, but is very suspicious -- whatever pass
12961       // change the loop to make a trip count go from could not compute to
12962       // computable or vice-versa *should have* invalidated SCEV.  However, we
12963       // choose not to assert here (for now) since we don't want false
12964       // positives.
12965       continue;
12966     }
12967 
12968     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12969       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12970       // not propagate undef aggressively).  This means we can (and do) fail
12971       // verification in cases where a transform makes the trip count of a loop
12972       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12973       // both cases the loop iterates "undef" times, but SCEV thinks we
12974       // increased the trip count of the loop by 1 incorrectly.
12975       continue;
12976     }
12977 
12978     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12979         SE.getTypeSizeInBits(NewBECount->getType()))
12980       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12981     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12982              SE.getTypeSizeInBits(NewBECount->getType()))
12983       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12984 
12985     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12986 
12987     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12988     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12989       dbgs() << "Trip Count for " << *L << " Changed!\n";
12990       dbgs() << "Old: " << *CurBECount << "\n";
12991       dbgs() << "New: " << *NewBECount << "\n";
12992       dbgs() << "Delta: " << *Delta << "\n";
12993       std::abort();
12994     }
12995   }
12996 
12997   // Collect all valid loops currently in LoopInfo.
12998   SmallPtrSet<Loop *, 32> ValidLoops;
12999   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13000   while (!Worklist.empty()) {
13001     Loop *L = Worklist.pop_back_val();
13002     if (ValidLoops.contains(L))
13003       continue;
13004     ValidLoops.insert(L);
13005     Worklist.append(L->begin(), L->end());
13006   }
13007   // Check for SCEV expressions referencing invalid/deleted loops.
13008   for (auto &KV : ValueExprMap) {
13009     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
13010     if (!AR)
13011       continue;
13012     assert(ValidLoops.contains(AR->getLoop()) &&
13013            "AddRec references invalid loop");
13014   }
13015 }
13016 
13017 bool ScalarEvolution::invalidate(
13018     Function &F, const PreservedAnalyses &PA,
13019     FunctionAnalysisManager::Invalidator &Inv) {
13020   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13021   // of its dependencies is invalidated.
13022   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13023   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13024          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13025          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13026          Inv.invalidate<LoopAnalysis>(F, PA);
13027 }
13028 
13029 AnalysisKey ScalarEvolutionAnalysis::Key;
13030 
13031 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13032                                              FunctionAnalysisManager &AM) {
13033   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13034                          AM.getResult<AssumptionAnalysis>(F),
13035                          AM.getResult<DominatorTreeAnalysis>(F),
13036                          AM.getResult<LoopAnalysis>(F));
13037 }
13038 
13039 PreservedAnalyses
13040 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13041   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13042   return PreservedAnalyses::all();
13043 }
13044 
13045 PreservedAnalyses
13046 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13047   // For compatibility with opt's -analyze feature under legacy pass manager
13048   // which was not ported to NPM. This keeps tests using
13049   // update_analyze_test_checks.py working.
13050   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13051      << F.getName() << "':\n";
13052   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13053   return PreservedAnalyses::all();
13054 }
13055 
13056 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13057                       "Scalar Evolution Analysis", false, true)
13058 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13059 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13060 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13061 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13062 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13063                     "Scalar Evolution Analysis", false, true)
13064 
13065 char ScalarEvolutionWrapperPass::ID = 0;
13066 
13067 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13068   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13069 }
13070 
13071 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13072   SE.reset(new ScalarEvolution(
13073       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13074       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13075       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13076       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13077   return false;
13078 }
13079 
13080 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13081 
13082 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13083   SE->print(OS);
13084 }
13085 
13086 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13087   if (!VerifySCEV)
13088     return;
13089 
13090   SE->verify();
13091 }
13092 
13093 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13094   AU.setPreservesAll();
13095   AU.addRequiredTransitive<AssumptionCacheTracker>();
13096   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13097   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13098   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13099 }
13100 
13101 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13102                                                         const SCEV *RHS) {
13103   FoldingSetNodeID ID;
13104   assert(LHS->getType() == RHS->getType() &&
13105          "Type mismatch between LHS and RHS");
13106   // Unique this node based on the arguments
13107   ID.AddInteger(SCEVPredicate::P_Equal);
13108   ID.AddPointer(LHS);
13109   ID.AddPointer(RHS);
13110   void *IP = nullptr;
13111   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13112     return S;
13113   SCEVEqualPredicate *Eq = new (SCEVAllocator)
13114       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
13115   UniquePreds.InsertNode(Eq, IP);
13116   return Eq;
13117 }
13118 
13119 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13120     const SCEVAddRecExpr *AR,
13121     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13122   FoldingSetNodeID ID;
13123   // Unique this node based on the arguments
13124   ID.AddInteger(SCEVPredicate::P_Wrap);
13125   ID.AddPointer(AR);
13126   ID.AddInteger(AddedFlags);
13127   void *IP = nullptr;
13128   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13129     return S;
13130   auto *OF = new (SCEVAllocator)
13131       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13132   UniquePreds.InsertNode(OF, IP);
13133   return OF;
13134 }
13135 
13136 namespace {
13137 
13138 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13139 public:
13140 
13141   /// Rewrites \p S in the context of a loop L and the SCEV predication
13142   /// infrastructure.
13143   ///
13144   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13145   /// equivalences present in \p Pred.
13146   ///
13147   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13148   /// \p NewPreds such that the result will be an AddRecExpr.
13149   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13150                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13151                              SCEVUnionPredicate *Pred) {
13152     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13153     return Rewriter.visit(S);
13154   }
13155 
13156   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13157     if (Pred) {
13158       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
13159       for (auto *Pred : ExprPreds)
13160         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
13161           if (IPred->getLHS() == Expr)
13162             return IPred->getRHS();
13163     }
13164     return convertToAddRecWithPreds(Expr);
13165   }
13166 
13167   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13168     const SCEV *Operand = visit(Expr->getOperand());
13169     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13170     if (AR && AR->getLoop() == L && AR->isAffine()) {
13171       // This couldn't be folded because the operand didn't have the nuw
13172       // flag. Add the nusw flag as an assumption that we could make.
13173       const SCEV *Step = AR->getStepRecurrence(SE);
13174       Type *Ty = Expr->getType();
13175       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13176         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13177                                 SE.getSignExtendExpr(Step, Ty), L,
13178                                 AR->getNoWrapFlags());
13179     }
13180     return SE.getZeroExtendExpr(Operand, Expr->getType());
13181   }
13182 
13183   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13184     const SCEV *Operand = visit(Expr->getOperand());
13185     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13186     if (AR && AR->getLoop() == L && AR->isAffine()) {
13187       // This couldn't be folded because the operand didn't have the nsw
13188       // flag. Add the nssw flag as an assumption that we could make.
13189       const SCEV *Step = AR->getStepRecurrence(SE);
13190       Type *Ty = Expr->getType();
13191       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13192         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13193                                 SE.getSignExtendExpr(Step, Ty), L,
13194                                 AR->getNoWrapFlags());
13195     }
13196     return SE.getSignExtendExpr(Operand, Expr->getType());
13197   }
13198 
13199 private:
13200   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13201                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13202                         SCEVUnionPredicate *Pred)
13203       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13204 
13205   bool addOverflowAssumption(const SCEVPredicate *P) {
13206     if (!NewPreds) {
13207       // Check if we've already made this assumption.
13208       return Pred && Pred->implies(P);
13209     }
13210     NewPreds->insert(P);
13211     return true;
13212   }
13213 
13214   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13215                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13216     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13217     return addOverflowAssumption(A);
13218   }
13219 
13220   // If \p Expr represents a PHINode, we try to see if it can be represented
13221   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13222   // to add this predicate as a runtime overflow check, we return the AddRec.
13223   // If \p Expr does not meet these conditions (is not a PHI node, or we
13224   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13225   // return \p Expr.
13226   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13227     if (!isa<PHINode>(Expr->getValue()))
13228       return Expr;
13229     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13230     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13231     if (!PredicatedRewrite)
13232       return Expr;
13233     for (auto *P : PredicatedRewrite->second){
13234       // Wrap predicates from outer loops are not supported.
13235       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13236         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
13237         if (L != AR->getLoop())
13238           return Expr;
13239       }
13240       if (!addOverflowAssumption(P))
13241         return Expr;
13242     }
13243     return PredicatedRewrite->first;
13244   }
13245 
13246   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13247   SCEVUnionPredicate *Pred;
13248   const Loop *L;
13249 };
13250 
13251 } // end anonymous namespace
13252 
13253 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13254                                                    SCEVUnionPredicate &Preds) {
13255   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13256 }
13257 
13258 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13259     const SCEV *S, const Loop *L,
13260     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13261   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13262   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13263   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13264 
13265   if (!AddRec)
13266     return nullptr;
13267 
13268   // Since the transformation was successful, we can now transfer the SCEV
13269   // predicates.
13270   for (auto *P : TransformPreds)
13271     Preds.insert(P);
13272 
13273   return AddRec;
13274 }
13275 
13276 /// SCEV predicates
13277 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13278                              SCEVPredicateKind Kind)
13279     : FastID(ID), Kind(Kind) {}
13280 
13281 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13282                                        const SCEV *LHS, const SCEV *RHS)
13283     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13284   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13285   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13286 }
13287 
13288 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13289   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13290 
13291   if (!Op)
13292     return false;
13293 
13294   return Op->LHS == LHS && Op->RHS == RHS;
13295 }
13296 
13297 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13298 
13299 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13300 
13301 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13302   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13303 }
13304 
13305 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13306                                      const SCEVAddRecExpr *AR,
13307                                      IncrementWrapFlags Flags)
13308     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13309 
13310 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13311 
13312 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13313   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13314 
13315   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13316 }
13317 
13318 bool SCEVWrapPredicate::isAlwaysTrue() const {
13319   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13320   IncrementWrapFlags IFlags = Flags;
13321 
13322   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13323     IFlags = clearFlags(IFlags, IncrementNSSW);
13324 
13325   return IFlags == IncrementAnyWrap;
13326 }
13327 
13328 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13329   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13330   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13331     OS << "<nusw>";
13332   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13333     OS << "<nssw>";
13334   OS << "\n";
13335 }
13336 
13337 SCEVWrapPredicate::IncrementWrapFlags
13338 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13339                                    ScalarEvolution &SE) {
13340   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13341   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13342 
13343   // We can safely transfer the NSW flag as NSSW.
13344   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13345     ImpliedFlags = IncrementNSSW;
13346 
13347   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13348     // If the increment is positive, the SCEV NUW flag will also imply the
13349     // WrapPredicate NUSW flag.
13350     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13351       if (Step->getValue()->getValue().isNonNegative())
13352         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13353   }
13354 
13355   return ImpliedFlags;
13356 }
13357 
13358 /// Union predicates don't get cached so create a dummy set ID for it.
13359 SCEVUnionPredicate::SCEVUnionPredicate()
13360     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13361 
13362 bool SCEVUnionPredicate::isAlwaysTrue() const {
13363   return all_of(Preds,
13364                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13365 }
13366 
13367 ArrayRef<const SCEVPredicate *>
13368 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13369   auto I = SCEVToPreds.find(Expr);
13370   if (I == SCEVToPreds.end())
13371     return ArrayRef<const SCEVPredicate *>();
13372   return I->second;
13373 }
13374 
13375 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13376   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13377     return all_of(Set->Preds,
13378                   [this](const SCEVPredicate *I) { return this->implies(I); });
13379 
13380   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13381   if (ScevPredsIt == SCEVToPreds.end())
13382     return false;
13383   auto &SCEVPreds = ScevPredsIt->second;
13384 
13385   return any_of(SCEVPreds,
13386                 [N](const SCEVPredicate *I) { return I->implies(N); });
13387 }
13388 
13389 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13390 
13391 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13392   for (auto Pred : Preds)
13393     Pred->print(OS, Depth);
13394 }
13395 
13396 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13397   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13398     for (auto Pred : Set->Preds)
13399       add(Pred);
13400     return;
13401   }
13402 
13403   if (implies(N))
13404     return;
13405 
13406   const SCEV *Key = N->getExpr();
13407   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13408                 " associated expression!");
13409 
13410   SCEVToPreds[Key].push_back(N);
13411   Preds.push_back(N);
13412 }
13413 
13414 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13415                                                      Loop &L)
13416     : SE(SE), L(L) {}
13417 
13418 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13419   const SCEV *Expr = SE.getSCEV(V);
13420   RewriteEntry &Entry = RewriteMap[Expr];
13421 
13422   // If we already have an entry and the version matches, return it.
13423   if (Entry.second && Generation == Entry.first)
13424     return Entry.second;
13425 
13426   // We found an entry but it's stale. Rewrite the stale entry
13427   // according to the current predicate.
13428   if (Entry.second)
13429     Expr = Entry.second;
13430 
13431   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13432   Entry = {Generation, NewSCEV};
13433 
13434   return NewSCEV;
13435 }
13436 
13437 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13438   if (!BackedgeCount) {
13439     SCEVUnionPredicate BackedgePred;
13440     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13441     addPredicate(BackedgePred);
13442   }
13443   return BackedgeCount;
13444 }
13445 
13446 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13447   if (Preds.implies(&Pred))
13448     return;
13449   Preds.add(&Pred);
13450   updateGeneration();
13451 }
13452 
13453 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13454   return Preds;
13455 }
13456 
13457 void PredicatedScalarEvolution::updateGeneration() {
13458   // If the generation number wrapped recompute everything.
13459   if (++Generation == 0) {
13460     for (auto &II : RewriteMap) {
13461       const SCEV *Rewritten = II.second.second;
13462       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13463     }
13464   }
13465 }
13466 
13467 void PredicatedScalarEvolution::setNoOverflow(
13468     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13469   const SCEV *Expr = getSCEV(V);
13470   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13471 
13472   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13473 
13474   // Clear the statically implied flags.
13475   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13476   addPredicate(*SE.getWrapPredicate(AR, Flags));
13477 
13478   auto II = FlagsMap.insert({V, Flags});
13479   if (!II.second)
13480     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13481 }
13482 
13483 bool PredicatedScalarEvolution::hasNoOverflow(
13484     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13485   const SCEV *Expr = getSCEV(V);
13486   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13487 
13488   Flags = SCEVWrapPredicate::clearFlags(
13489       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13490 
13491   auto II = FlagsMap.find(V);
13492 
13493   if (II != FlagsMap.end())
13494     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13495 
13496   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13497 }
13498 
13499 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13500   const SCEV *Expr = this->getSCEV(V);
13501   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13502   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13503 
13504   if (!New)
13505     return nullptr;
13506 
13507   for (auto *P : NewPreds)
13508     Preds.add(P);
13509 
13510   updateGeneration();
13511   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13512   return New;
13513 }
13514 
13515 PredicatedScalarEvolution::PredicatedScalarEvolution(
13516     const PredicatedScalarEvolution &Init)
13517     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13518       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13519   for (auto I : Init.FlagsMap)
13520     FlagsMap.insert(I);
13521 }
13522 
13523 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13524   // For each block.
13525   for (auto *BB : L.getBlocks())
13526     for (auto &I : *BB) {
13527       if (!SE.isSCEVable(I.getType()))
13528         continue;
13529 
13530       auto *Expr = SE.getSCEV(&I);
13531       auto II = RewriteMap.find(Expr);
13532 
13533       if (II == RewriteMap.end())
13534         continue;
13535 
13536       // Don't print things that are not interesting.
13537       if (II->second.second == Expr)
13538         continue;
13539 
13540       OS.indent(Depth) << "[PSE]" << I << ":\n";
13541       OS.indent(Depth + 2) << *Expr << "\n";
13542       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13543     }
13544 }
13545 
13546 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13547 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13548 // for URem with constant power-of-2 second operands.
13549 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13550 // 4, A / B becomes X / 8).
13551 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13552                                 const SCEV *&RHS) {
13553   // Try to match 'zext (trunc A to iB) to iY', which is used
13554   // for URem with constant power-of-2 second operands. Make sure the size of
13555   // the operand A matches the size of the whole expressions.
13556   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13557     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13558       LHS = Trunc->getOperand();
13559       // Bail out if the type of the LHS is larger than the type of the
13560       // expression for now.
13561       if (getTypeSizeInBits(LHS->getType()) >
13562           getTypeSizeInBits(Expr->getType()))
13563         return false;
13564       if (LHS->getType() != Expr->getType())
13565         LHS = getZeroExtendExpr(LHS, Expr->getType());
13566       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13567                         << getTypeSizeInBits(Trunc->getType()));
13568       return true;
13569     }
13570   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13571   if (Add == nullptr || Add->getNumOperands() != 2)
13572     return false;
13573 
13574   const SCEV *A = Add->getOperand(1);
13575   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13576 
13577   if (Mul == nullptr)
13578     return false;
13579 
13580   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13581     // (SomeExpr + (-(SomeExpr / B) * B)).
13582     if (Expr == getURemExpr(A, B)) {
13583       LHS = A;
13584       RHS = B;
13585       return true;
13586     }
13587     return false;
13588   };
13589 
13590   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13591   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13592     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13593            MatchURemWithDivisor(Mul->getOperand(2));
13594 
13595   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13596   if (Mul->getNumOperands() == 2)
13597     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13598            MatchURemWithDivisor(Mul->getOperand(0)) ||
13599            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13600            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13601   return false;
13602 }
13603 
13604 const SCEV *
13605 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13606   SmallVector<BasicBlock*, 16> ExitingBlocks;
13607   L->getExitingBlocks(ExitingBlocks);
13608 
13609   // Form an expression for the maximum exit count possible for this loop. We
13610   // merge the max and exact information to approximate a version of
13611   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13612   SmallVector<const SCEV*, 4> ExitCounts;
13613   for (BasicBlock *ExitingBB : ExitingBlocks) {
13614     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13615     if (isa<SCEVCouldNotCompute>(ExitCount))
13616       ExitCount = getExitCount(L, ExitingBB,
13617                                   ScalarEvolution::ConstantMaximum);
13618     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13619       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13620              "We should only have known counts for exiting blocks that "
13621              "dominate latch!");
13622       ExitCounts.push_back(ExitCount);
13623     }
13624   }
13625   if (ExitCounts.empty())
13626     return getCouldNotCompute();
13627   return getUMinFromMismatchedTypes(ExitCounts);
13628 }
13629 
13630 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13631 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13632 /// we cannot guarantee that the replacement is loop invariant in the loop of
13633 /// the AddRec.
13634 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13635   ValueToSCEVMapTy &Map;
13636 
13637 public:
13638   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13639       : SCEVRewriteVisitor(SE), Map(M) {}
13640 
13641   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13642 
13643   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13644     auto I = Map.find(Expr->getValue());
13645     if (I == Map.end())
13646       return Expr;
13647     return I->second;
13648   }
13649 };
13650 
13651 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13652   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13653                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13654     // If we have LHS == 0, check if LHS is computing a property of some unknown
13655     // SCEV %v which we can rewrite %v to express explicitly.
13656     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13657     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13658         RHSC->getValue()->isNullValue()) {
13659       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13660       // explicitly express that.
13661       const SCEV *URemLHS = nullptr;
13662       const SCEV *URemRHS = nullptr;
13663       if (matchURem(LHS, URemLHS, URemRHS)) {
13664         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13665           Value *V = LHSUnknown->getValue();
13666           auto Multiple =
13667               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13668                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13669           RewriteMap[V] = Multiple;
13670           return;
13671         }
13672       }
13673     }
13674 
13675     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
13676       std::swap(LHS, RHS);
13677       Predicate = CmpInst::getSwappedPredicate(Predicate);
13678     }
13679 
13680     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
13681     // create this form when combining two checks of the form (X u< C2 + C1) and
13682     // (X >=u C1).
13683     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() {
13684       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
13685       if (!AddExpr || AddExpr->getNumOperands() != 2)
13686         return false;
13687 
13688       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
13689       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
13690       auto *C2 = dyn_cast<SCEVConstant>(RHS);
13691       if (!C1 || !C2 || !LHSUnknown)
13692         return false;
13693 
13694       auto ExactRegion =
13695           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
13696               .sub(C1->getAPInt());
13697 
13698       // Bail out, unless we have a non-wrapping, monotonic range.
13699       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
13700         return false;
13701       auto I = RewriteMap.find(LHSUnknown->getValue());
13702       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13703       RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(
13704           getConstant(ExactRegion.getUnsignedMin()),
13705           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
13706       return true;
13707     };
13708     if (MatchRangeCheckIdiom())
13709       return;
13710 
13711     // For now, limit to conditions that provide information about unknown
13712     // expressions. RHS also cannot contain add recurrences.
13713     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13714     if (!LHSUnknown || containsAddRecurrence(RHS))
13715       return;
13716 
13717     // Check whether LHS has already been rewritten. In that case we want to
13718     // chain further rewrites onto the already rewritten value.
13719     auto I = RewriteMap.find(LHSUnknown->getValue());
13720     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13721     const SCEV *RewrittenRHS = nullptr;
13722     switch (Predicate) {
13723     case CmpInst::ICMP_ULT:
13724       RewrittenRHS =
13725           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13726       break;
13727     case CmpInst::ICMP_SLT:
13728       RewrittenRHS =
13729           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13730       break;
13731     case CmpInst::ICMP_ULE:
13732       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
13733       break;
13734     case CmpInst::ICMP_SLE:
13735       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
13736       break;
13737     case CmpInst::ICMP_UGT:
13738       RewrittenRHS =
13739           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13740       break;
13741     case CmpInst::ICMP_SGT:
13742       RewrittenRHS =
13743           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13744       break;
13745     case CmpInst::ICMP_UGE:
13746       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
13747       break;
13748     case CmpInst::ICMP_SGE:
13749       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
13750       break;
13751     case CmpInst::ICMP_EQ:
13752       if (isa<SCEVConstant>(RHS))
13753         RewrittenRHS = RHS;
13754       break;
13755     case CmpInst::ICMP_NE:
13756       if (isa<SCEVConstant>(RHS) &&
13757           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13758         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
13759       break;
13760     default:
13761       break;
13762     }
13763 
13764     if (RewrittenRHS)
13765       RewriteMap[LHSUnknown->getValue()] = RewrittenRHS;
13766   };
13767   // Starting at the loop predecessor, climb up the predecessor chain, as long
13768   // as there are predecessors that can be found that have unique successors
13769   // leading to the original header.
13770   // TODO: share this logic with isLoopEntryGuardedByCond.
13771   ValueToSCEVMapTy RewriteMap;
13772   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13773            L->getLoopPredecessor(), L->getHeader());
13774        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13775 
13776     const BranchInst *LoopEntryPredicate =
13777         dyn_cast<BranchInst>(Pair.first->getTerminator());
13778     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13779       continue;
13780 
13781     bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second;
13782     SmallVector<Value *, 8> Worklist;
13783     SmallPtrSet<Value *, 8> Visited;
13784     Worklist.push_back(LoopEntryPredicate->getCondition());
13785     while (!Worklist.empty()) {
13786       Value *Cond = Worklist.pop_back_val();
13787       if (!Visited.insert(Cond).second)
13788         continue;
13789 
13790       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13791         auto Predicate =
13792             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
13793         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13794                          getSCEV(Cmp->getOperand(1)), RewriteMap);
13795         continue;
13796       }
13797 
13798       Value *L, *R;
13799       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
13800                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
13801         Worklist.push_back(L);
13802         Worklist.push_back(R);
13803       }
13804     }
13805   }
13806 
13807   // Also collect information from assumptions dominating the loop.
13808   for (auto &AssumeVH : AC.assumptions()) {
13809     if (!AssumeVH)
13810       continue;
13811     auto *AssumeI = cast<CallInst>(AssumeVH);
13812     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13813     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13814       continue;
13815     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13816                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13817   }
13818 
13819   if (RewriteMap.empty())
13820     return Expr;
13821   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13822   return Rewriter.visit(Expr);
13823 }
13824