xref: /freebsd-src/contrib/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision b3edf4467982447620505a28fc82e38a414c07dc)
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/STLExtras.h"
68 #include "llvm/ADT/ScopeExit.h"
69 #include "llvm/ADT/Sequence.h"
70 #include "llvm/ADT/SmallPtrSet.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/ADT/StringExtras.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/Analysis/AssumptionCache.h"
77 #include "llvm/Analysis/ConstantFolding.h"
78 #include "llvm/Analysis/InstructionSimplify.h"
79 #include "llvm/Analysis/LoopInfo.h"
80 #include "llvm/Analysis/MemoryBuiltins.h"
81 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
82 #include "llvm/Analysis/TargetLibraryInfo.h"
83 #include "llvm/Analysis/ValueTracking.h"
84 #include "llvm/Config/llvm-config.h"
85 #include "llvm/IR/Argument.h"
86 #include "llvm/IR/BasicBlock.h"
87 #include "llvm/IR/CFG.h"
88 #include "llvm/IR/Constant.h"
89 #include "llvm/IR/ConstantRange.h"
90 #include "llvm/IR/Constants.h"
91 #include "llvm/IR/DataLayout.h"
92 #include "llvm/IR/DerivedTypes.h"
93 #include "llvm/IR/Dominators.h"
94 #include "llvm/IR/Function.h"
95 #include "llvm/IR/GlobalAlias.h"
96 #include "llvm/IR/GlobalValue.h"
97 #include "llvm/IR/InstIterator.h"
98 #include "llvm/IR/InstrTypes.h"
99 #include "llvm/IR/Instruction.h"
100 #include "llvm/IR/Instructions.h"
101 #include "llvm/IR/IntrinsicInst.h"
102 #include "llvm/IR/Intrinsics.h"
103 #include "llvm/IR/LLVMContext.h"
104 #include "llvm/IR/Operator.h"
105 #include "llvm/IR/PatternMatch.h"
106 #include "llvm/IR/Type.h"
107 #include "llvm/IR/Use.h"
108 #include "llvm/IR/User.h"
109 #include "llvm/IR/Value.h"
110 #include "llvm/IR/Verifier.h"
111 #include "llvm/InitializePasses.h"
112 #include "llvm/Pass.h"
113 #include "llvm/Support/Casting.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/ErrorHandling.h"
118 #include "llvm/Support/KnownBits.h"
119 #include "llvm/Support/SaveAndRestore.h"
120 #include "llvm/Support/raw_ostream.h"
121 #include <algorithm>
122 #include <cassert>
123 #include <climits>
124 #include <cstdint>
125 #include <cstdlib>
126 #include <map>
127 #include <memory>
128 #include <numeric>
129 #include <optional>
130 #include <tuple>
131 #include <utility>
132 #include <vector>
133 
134 using namespace llvm;
135 using namespace PatternMatch;
136 
137 #define DEBUG_TYPE "scalar-evolution"
138 
139 STATISTIC(NumExitCountsComputed,
140           "Number of loop exits with predictable exit counts");
141 STATISTIC(NumExitCountsNotComputed,
142           "Number of loop exits without predictable exit counts");
143 STATISTIC(NumBruteForceTripCountsComputed,
144           "Number of loops with trip counts computed by force");
145 
146 #ifdef EXPENSIVE_CHECKS
147 bool llvm::VerifySCEV = true;
148 #else
149 bool llvm::VerifySCEV = false;
150 #endif
151 
152 static cl::opt<unsigned>
153     MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
154                             cl::desc("Maximum number of iterations SCEV will "
155                                      "symbolically execute a constant "
156                                      "derived loop"),
157                             cl::init(100));
158 
159 static cl::opt<bool, true> VerifySCEVOpt(
160     "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163     "verify-scev-strict", cl::Hidden,
164     cl::desc("Enable stricter verification with -verify-scev is passed"));
165 
166 static cl::opt<bool> VerifyIR(
167     "scev-verify-ir", cl::Hidden,
168     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
169     cl::init(false));
170 
171 static cl::opt<unsigned> MulOpsInlineThreshold(
172     "scev-mulops-inline-threshold", cl::Hidden,
173     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
174     cl::init(32));
175 
176 static cl::opt<unsigned> AddOpsInlineThreshold(
177     "scev-addops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining addition operands into a SCEV"),
179     cl::init(500));
180 
181 static cl::opt<unsigned> MaxSCEVCompareDepth(
182     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
183     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
184     cl::init(32));
185 
186 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
187     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
189     cl::init(2));
190 
191 static cl::opt<unsigned> MaxValueCompareDepth(
192     "scalar-evolution-max-value-compare-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive value complexity comparisons"),
194     cl::init(2));
195 
196 static cl::opt<unsigned>
197     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
198                   cl::desc("Maximum depth of recursive arithmetics"),
199                   cl::init(32));
200 
201 static cl::opt<unsigned> MaxConstantEvolvingDepth(
202     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
203     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
204 
205 static cl::opt<unsigned>
206     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
207                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
208                  cl::init(8));
209 
210 static cl::opt<unsigned>
211     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
212                   cl::desc("Max coefficients in AddRec during evolving"),
213                   cl::init(8));
214 
215 static cl::opt<unsigned>
216     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
217                   cl::desc("Size of the expression which is considered huge"),
218                   cl::init(4096));
219 
220 static cl::opt<unsigned> RangeIterThreshold(
221     "scev-range-iter-threshold", cl::Hidden,
222     cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
223     cl::init(32));
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 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
237     "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
238     cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
239              "Phi strongly connected components"),
240     cl::init(8));
241 
242 static cl::opt<bool>
243     EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
244                             cl::desc("Handle <= and >= in finite loops"),
245                             cl::init(true));
246 
247 static cl::opt<bool> UseContextForNoWrapFlagInference(
248     "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
249     cl::desc("Infer nuw/nsw flags using context where suitable"),
250     cl::init(true));
251 
252 //===----------------------------------------------------------------------===//
253 //                           SCEV class definitions
254 //===----------------------------------------------------------------------===//
255 
256 //===----------------------------------------------------------------------===//
257 // Implementation of the SCEV class.
258 //
259 
260 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
261 LLVM_DUMP_METHOD void SCEV::dump() const {
262   print(dbgs());
263   dbgs() << '\n';
264 }
265 #endif
266 
267 void SCEV::print(raw_ostream &OS) const {
268   switch (getSCEVType()) {
269   case scConstant:
270     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
271     return;
272   case scVScale:
273     OS << "vscale";
274     return;
275   case scPtrToInt: {
276     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
277     const SCEV *Op = PtrToInt->getOperand();
278     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
279        << *PtrToInt->getType() << ")";
280     return;
281   }
282   case scTruncate: {
283     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
284     const SCEV *Op = Trunc->getOperand();
285     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
286        << *Trunc->getType() << ")";
287     return;
288   }
289   case scZeroExtend: {
290     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
291     const SCEV *Op = ZExt->getOperand();
292     OS << "(zext " << *Op->getType() << " " << *Op << " to "
293        << *ZExt->getType() << ")";
294     return;
295   }
296   case scSignExtend: {
297     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
298     const SCEV *Op = SExt->getOperand();
299     OS << "(sext " << *Op->getType() << " " << *Op << " to "
300        << *SExt->getType() << ")";
301     return;
302   }
303   case scAddRecExpr: {
304     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
305     OS << "{" << *AR->getOperand(0);
306     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
307       OS << ",+," << *AR->getOperand(i);
308     OS << "}<";
309     if (AR->hasNoUnsignedWrap())
310       OS << "nuw><";
311     if (AR->hasNoSignedWrap())
312       OS << "nsw><";
313     if (AR->hasNoSelfWrap() &&
314         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
315       OS << "nw><";
316     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
317     OS << ">";
318     return;
319   }
320   case scAddExpr:
321   case scMulExpr:
322   case scUMaxExpr:
323   case scSMaxExpr:
324   case scUMinExpr:
325   case scSMinExpr:
326   case scSequentialUMinExpr: {
327     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
328     const char *OpStr = nullptr;
329     switch (NAry->getSCEVType()) {
330     case scAddExpr: OpStr = " + "; break;
331     case scMulExpr: OpStr = " * "; break;
332     case scUMaxExpr: OpStr = " umax "; break;
333     case scSMaxExpr: OpStr = " smax "; break;
334     case scUMinExpr:
335       OpStr = " umin ";
336       break;
337     case scSMinExpr:
338       OpStr = " smin ";
339       break;
340     case scSequentialUMinExpr:
341       OpStr = " umin_seq ";
342       break;
343     default:
344       llvm_unreachable("There are no other nary expression types.");
345     }
346     OS << "(";
347     ListSeparator LS(OpStr);
348     for (const SCEV *Op : NAry->operands())
349       OS << LS << *Op;
350     OS << ")";
351     switch (NAry->getSCEVType()) {
352     case scAddExpr:
353     case scMulExpr:
354       if (NAry->hasNoUnsignedWrap())
355         OS << "<nuw>";
356       if (NAry->hasNoSignedWrap())
357         OS << "<nsw>";
358       break;
359     default:
360       // Nothing to print for other nary expressions.
361       break;
362     }
363     return;
364   }
365   case scUDivExpr: {
366     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
367     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
368     return;
369   }
370   case scUnknown:
371     cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
372     return;
373   case scCouldNotCompute:
374     OS << "***COULDNOTCOMPUTE***";
375     return;
376   }
377   llvm_unreachable("Unknown SCEV kind!");
378 }
379 
380 Type *SCEV::getType() const {
381   switch (getSCEVType()) {
382   case scConstant:
383     return cast<SCEVConstant>(this)->getType();
384   case scVScale:
385     return cast<SCEVVScale>(this)->getType();
386   case scPtrToInt:
387   case scTruncate:
388   case scZeroExtend:
389   case scSignExtend:
390     return cast<SCEVCastExpr>(this)->getType();
391   case scAddRecExpr:
392     return cast<SCEVAddRecExpr>(this)->getType();
393   case scMulExpr:
394     return cast<SCEVMulExpr>(this)->getType();
395   case scUMaxExpr:
396   case scSMaxExpr:
397   case scUMinExpr:
398   case scSMinExpr:
399     return cast<SCEVMinMaxExpr>(this)->getType();
400   case scSequentialUMinExpr:
401     return cast<SCEVSequentialMinMaxExpr>(this)->getType();
402   case scAddExpr:
403     return cast<SCEVAddExpr>(this)->getType();
404   case scUDivExpr:
405     return cast<SCEVUDivExpr>(this)->getType();
406   case scUnknown:
407     return cast<SCEVUnknown>(this)->getType();
408   case scCouldNotCompute:
409     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
410   }
411   llvm_unreachable("Unknown SCEV kind!");
412 }
413 
414 ArrayRef<const SCEV *> SCEV::operands() const {
415   switch (getSCEVType()) {
416   case scConstant:
417   case scVScale:
418   case scUnknown:
419     return {};
420   case scPtrToInt:
421   case scTruncate:
422   case scZeroExtend:
423   case scSignExtend:
424     return cast<SCEVCastExpr>(this)->operands();
425   case scAddRecExpr:
426   case scAddExpr:
427   case scMulExpr:
428   case scUMaxExpr:
429   case scSMaxExpr:
430   case scUMinExpr:
431   case scSMinExpr:
432   case scSequentialUMinExpr:
433     return cast<SCEVNAryExpr>(this)->operands();
434   case scUDivExpr:
435     return cast<SCEVUDivExpr>(this)->operands();
436   case scCouldNotCompute:
437     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
438   }
439   llvm_unreachable("Unknown SCEV kind!");
440 }
441 
442 bool SCEV::isZero() const {
443   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
444     return SC->getValue()->isZero();
445   return false;
446 }
447 
448 bool SCEV::isOne() const {
449   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
450     return SC->getValue()->isOne();
451   return false;
452 }
453 
454 bool SCEV::isAllOnesValue() const {
455   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
456     return SC->getValue()->isMinusOne();
457   return false;
458 }
459 
460 bool SCEV::isNonConstantNegative() const {
461   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
462   if (!Mul) return false;
463 
464   // If there is a constant factor, it will be first.
465   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
466   if (!SC) return false;
467 
468   // Return true if the value is negative, this matches things like (-42 * V).
469   return SC->getAPInt().isNegative();
470 }
471 
472 SCEVCouldNotCompute::SCEVCouldNotCompute() :
473   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
474 
475 bool SCEVCouldNotCompute::classof(const SCEV *S) {
476   return S->getSCEVType() == scCouldNotCompute;
477 }
478 
479 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
480   FoldingSetNodeID ID;
481   ID.AddInteger(scConstant);
482   ID.AddPointer(V);
483   void *IP = nullptr;
484   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
485   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
486   UniqueSCEVs.InsertNode(S, IP);
487   return S;
488 }
489 
490 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
491   return getConstant(ConstantInt::get(getContext(), Val));
492 }
493 
494 const SCEV *
495 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
496   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
497   return getConstant(ConstantInt::get(ITy, V, isSigned));
498 }
499 
500 const SCEV *ScalarEvolution::getVScale(Type *Ty) {
501   FoldingSetNodeID ID;
502   ID.AddInteger(scVScale);
503   ID.AddPointer(Ty);
504   void *IP = nullptr;
505   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
506     return S;
507   SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
508   UniqueSCEVs.InsertNode(S, IP);
509   return S;
510 }
511 
512 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
513                            const SCEV *op, Type *ty)
514     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
515 
516 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
517                                    Type *ITy)
518     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
519   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
520          "Must be a non-bit-width-changing pointer-to-integer cast!");
521 }
522 
523 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
524                                            SCEVTypes SCEVTy, const SCEV *op,
525                                            Type *ty)
526     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
527 
528 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
529                                    Type *ty)
530     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
531   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
532          "Cannot truncate non-integer value!");
533 }
534 
535 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
536                                        const SCEV *op, Type *ty)
537     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
538   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
539          "Cannot zero extend non-integer value!");
540 }
541 
542 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
543                                        const SCEV *op, Type *ty)
544     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
545   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
546          "Cannot sign extend non-integer value!");
547 }
548 
549 void SCEVUnknown::deleted() {
550   // Clear this SCEVUnknown from various maps.
551   SE->forgetMemoizedResults(this);
552 
553   // Remove this SCEVUnknown from the uniquing map.
554   SE->UniqueSCEVs.RemoveNode(this);
555 
556   // Release the value.
557   setValPtr(nullptr);
558 }
559 
560 void SCEVUnknown::allUsesReplacedWith(Value *New) {
561   // Clear this SCEVUnknown from various maps.
562   SE->forgetMemoizedResults(this);
563 
564   // Remove this SCEVUnknown from the uniquing map.
565   SE->UniqueSCEVs.RemoveNode(this);
566 
567   // Replace the value pointer in case someone is still using this SCEVUnknown.
568   setValPtr(New);
569 }
570 
571 //===----------------------------------------------------------------------===//
572 //                               SCEV Utilities
573 //===----------------------------------------------------------------------===//
574 
575 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
576 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
578 /// have been previously deemed to be "equally complex" by this routine.  It is
579 /// intended to avoid exponential time complexity in cases like:
580 ///
581 ///   %a = f(%x, %y)
582 ///   %b = f(%a, %a)
583 ///   %c = f(%b, %b)
584 ///
585 ///   %d = f(%x, %y)
586 ///   %e = f(%d, %d)
587 ///   %f = f(%e, %e)
588 ///
589 ///   CompareValueComplexity(%f, %c)
590 ///
591 /// Since we do not continue running this routine on expression trees once we
592 /// have seen unequal values, there is no need to track them in the cache.
593 static int
594 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
595                        const LoopInfo *const LI, Value *LV, Value *RV,
596                        unsigned Depth) {
597   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
598     return 0;
599 
600   // Order pointer values after integer values. This helps SCEVExpander form
601   // GEPs.
602   bool LIsPointer = LV->getType()->isPointerTy(),
603        RIsPointer = RV->getType()->isPointerTy();
604   if (LIsPointer != RIsPointer)
605     return (int)LIsPointer - (int)RIsPointer;
606 
607   // Compare getValueID values.
608   unsigned LID = LV->getValueID(), RID = RV->getValueID();
609   if (LID != RID)
610     return (int)LID - (int)RID;
611 
612   // Sort arguments by their position.
613   if (const auto *LA = dyn_cast<Argument>(LV)) {
614     const auto *RA = cast<Argument>(RV);
615     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
616     return (int)LArgNo - (int)RArgNo;
617   }
618 
619   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
620     const auto *RGV = cast<GlobalValue>(RV);
621 
622     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
623       auto LT = GV->getLinkage();
624       return !(GlobalValue::isPrivateLinkage(LT) ||
625                GlobalValue::isInternalLinkage(LT));
626     };
627 
628     // Use the names to distinguish the two values, but only if the
629     // names are semantically important.
630     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
631       return LGV->getName().compare(RGV->getName());
632   }
633 
634   // For instructions, compare their loop depth, and their operand count.  This
635   // is pretty loose.
636   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
637     const auto *RInst = cast<Instruction>(RV);
638 
639     // Compare loop depths.
640     const BasicBlock *LParent = LInst->getParent(),
641                      *RParent = RInst->getParent();
642     if (LParent != RParent) {
643       unsigned LDepth = LI->getLoopDepth(LParent),
644                RDepth = LI->getLoopDepth(RParent);
645       if (LDepth != RDepth)
646         return (int)LDepth - (int)RDepth;
647     }
648 
649     // Compare the number of operands.
650     unsigned LNumOps = LInst->getNumOperands(),
651              RNumOps = RInst->getNumOperands();
652     if (LNumOps != RNumOps)
653       return (int)LNumOps - (int)RNumOps;
654 
655     for (unsigned Idx : seq(LNumOps)) {
656       int Result =
657           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
658                                  RInst->getOperand(Idx), Depth + 1);
659       if (Result != 0)
660         return Result;
661     }
662   }
663 
664   EqCacheValue.unionSets(LV, RV);
665   return 0;
666 }
667 
668 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
669 // than RHS, respectively. A three-way result allows recursive comparisons to be
670 // more efficient.
671 // If the max analysis depth was reached, return std::nullopt, assuming we do
672 // not know if they are equivalent for sure.
673 static std::optional<int>
674 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
675                       EquivalenceClasses<const Value *> &EqCacheValue,
676                       const LoopInfo *const LI, const SCEV *LHS,
677                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
678   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
679   if (LHS == RHS)
680     return 0;
681 
682   // Primarily, sort the SCEVs by their getSCEVType().
683   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
684   if (LType != RType)
685     return (int)LType - (int)RType;
686 
687   if (EqCacheSCEV.isEquivalent(LHS, RHS))
688     return 0;
689 
690   if (Depth > MaxSCEVCompareDepth)
691     return std::nullopt;
692 
693   // Aside from the getSCEVType() ordering, the particular ordering
694   // isn't very important except that it's beneficial to be consistent,
695   // so that (a + b) and (b + a) don't end up as different expressions.
696   switch (LType) {
697   case scUnknown: {
698     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
699     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
700 
701     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
702                                    RU->getValue(), Depth + 1);
703     if (X == 0)
704       EqCacheSCEV.unionSets(LHS, RHS);
705     return X;
706   }
707 
708   case scConstant: {
709     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
710     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
711 
712     // Compare constant values.
713     const APInt &LA = LC->getAPInt();
714     const APInt &RA = RC->getAPInt();
715     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
716     if (LBitWidth != RBitWidth)
717       return (int)LBitWidth - (int)RBitWidth;
718     return LA.ult(RA) ? -1 : 1;
719   }
720 
721   case scVScale: {
722     const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
723     const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
724     return LTy->getBitWidth() - RTy->getBitWidth();
725   }
726 
727   case scAddRecExpr: {
728     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
729     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
730 
731     // There is always a dominance between two recs that are used by one SCEV,
732     // so we can safely sort recs by loop header dominance. We require such
733     // order in getAddExpr.
734     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
735     if (LLoop != RLoop) {
736       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
737       assert(LHead != RHead && "Two loops share the same header?");
738       if (DT.dominates(LHead, RHead))
739         return 1;
740       assert(DT.dominates(RHead, LHead) &&
741              "No dominance between recurrences used by one SCEV?");
742       return -1;
743     }
744 
745     [[fallthrough]];
746   }
747 
748   case scTruncate:
749   case scZeroExtend:
750   case scSignExtend:
751   case scPtrToInt:
752   case scAddExpr:
753   case scMulExpr:
754   case scUDivExpr:
755   case scSMaxExpr:
756   case scUMaxExpr:
757   case scSMinExpr:
758   case scUMinExpr:
759   case scSequentialUMinExpr: {
760     ArrayRef<const SCEV *> LOps = LHS->operands();
761     ArrayRef<const SCEV *> ROps = RHS->operands();
762 
763     // Lexicographically compare n-ary-like expressions.
764     unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
765     if (LNumOps != RNumOps)
766       return (int)LNumOps - (int)RNumOps;
767 
768     for (unsigned i = 0; i != LNumOps; ++i) {
769       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
770                                      ROps[i], DT, Depth + 1);
771       if (X != 0)
772         return X;
773     }
774     EqCacheSCEV.unionSets(LHS, RHS);
775     return 0;
776   }
777 
778   case scCouldNotCompute:
779     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
780   }
781   llvm_unreachable("Unknown SCEV kind!");
782 }
783 
784 /// Given a list of SCEV objects, order them by their complexity, and group
785 /// objects of the same complexity together by value.  When this routine is
786 /// finished, we know that any duplicates in the vector are consecutive and that
787 /// complexity is monotonically increasing.
788 ///
789 /// Note that we go take special precautions to ensure that we get deterministic
790 /// results from this routine.  In other words, we don't want the results of
791 /// this to depend on where the addresses of various SCEV objects happened to
792 /// land in memory.
793 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
794                               LoopInfo *LI, DominatorTree &DT) {
795   if (Ops.size() < 2) return;  // Noop
796 
797   EquivalenceClasses<const SCEV *> EqCacheSCEV;
798   EquivalenceClasses<const Value *> EqCacheValue;
799 
800   // Whether LHS has provably less complexity than RHS.
801   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
802     auto Complexity =
803         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
804     return Complexity && *Complexity < 0;
805   };
806   if (Ops.size() == 2) {
807     // This is the common case, which also happens to be trivially simple.
808     // Special case it.
809     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
810     if (IsLessComplex(RHS, LHS))
811       std::swap(LHS, RHS);
812     return;
813   }
814 
815   // Do the rough sort by complexity.
816   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
817     return IsLessComplex(LHS, RHS);
818   });
819 
820   // Now that we are sorted by complexity, group elements of the same
821   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
822   // be extremely short in practice.  Note that we take this approach because we
823   // do not want to depend on the addresses of the objects we are grouping.
824   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
825     const SCEV *S = Ops[i];
826     unsigned Complexity = S->getSCEVType();
827 
828     // If there are any objects of the same complexity and same value as this
829     // one, group them.
830     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
831       if (Ops[j] == S) { // Found a duplicate.
832         // Move it to immediately after i'th element.
833         std::swap(Ops[i+1], Ops[j]);
834         ++i;   // no need to rescan it.
835         if (i == e-2) return;  // Done!
836       }
837     }
838   }
839 }
840 
841 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
842 /// least HugeExprThreshold nodes).
843 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
844   return any_of(Ops, [](const SCEV *S) {
845     return S->getExpressionSize() >= HugeExprThreshold;
846   });
847 }
848 
849 //===----------------------------------------------------------------------===//
850 //                      Simple SCEV method implementations
851 //===----------------------------------------------------------------------===//
852 
853 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
854 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
855                                        ScalarEvolution &SE,
856                                        Type *ResultTy) {
857   // Handle the simplest case efficiently.
858   if (K == 1)
859     return SE.getTruncateOrZeroExtend(It, ResultTy);
860 
861   // We are using the following formula for BC(It, K):
862   //
863   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
864   //
865   // Suppose, W is the bitwidth of the return value.  We must be prepared for
866   // overflow.  Hence, we must assure that the result of our computation is
867   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
868   // safe in modular arithmetic.
869   //
870   // However, this code doesn't use exactly that formula; the formula it uses
871   // is something like the following, where T is the number of factors of 2 in
872   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
873   // exponentiation:
874   //
875   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
876   //
877   // This formula is trivially equivalent to the previous formula.  However,
878   // this formula can be implemented much more efficiently.  The trick is that
879   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
880   // arithmetic.  To do exact division in modular arithmetic, all we have
881   // to do is multiply by the inverse.  Therefore, this step can be done at
882   // width W.
883   //
884   // The next issue is how to safely do the division by 2^T.  The way this
885   // is done is by doing the multiplication step at a width of at least W + T
886   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
887   // when we perform the division by 2^T (which is equivalent to a right shift
888   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
889   // truncated out after the division by 2^T.
890   //
891   // In comparison to just directly using the first formula, this technique
892   // is much more efficient; using the first formula requires W * K bits,
893   // but this formula less than W + K bits. Also, the first formula requires
894   // a division step, whereas this formula only requires multiplies and shifts.
895   //
896   // It doesn't matter whether the subtraction step is done in the calculation
897   // width or the input iteration count's width; if the subtraction overflows,
898   // the result must be zero anyway.  We prefer here to do it in the width of
899   // the induction variable because it helps a lot for certain cases; CodeGen
900   // isn't smart enough to ignore the overflow, which leads to much less
901   // efficient code if the width of the subtraction is wider than the native
902   // register width.
903   //
904   // (It's possible to not widen at all by pulling out factors of 2 before
905   // the multiplication; for example, K=2 can be calculated as
906   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
907   // extra arithmetic, so it's not an obvious win, and it gets
908   // much more complicated for K > 3.)
909 
910   // Protection from insane SCEVs; this bound is conservative,
911   // but it probably doesn't matter.
912   if (K > 1000)
913     return SE.getCouldNotCompute();
914 
915   unsigned W = SE.getTypeSizeInBits(ResultTy);
916 
917   // Calculate K! / 2^T and T; we divide out the factors of two before
918   // multiplying for calculating K! / 2^T to avoid overflow.
919   // Other overflow doesn't matter because we only care about the bottom
920   // W bits of the result.
921   APInt OddFactorial(W, 1);
922   unsigned T = 1;
923   for (unsigned i = 3; i <= K; ++i) {
924     APInt Mult(W, i);
925     unsigned TwoFactors = Mult.countr_zero();
926     T += TwoFactors;
927     Mult.lshrInPlace(TwoFactors);
928     OddFactorial *= Mult;
929   }
930 
931   // We need at least W + T bits for the multiplication step
932   unsigned CalculationBits = W + T;
933 
934   // Calculate 2^T, at width T+W.
935   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
936 
937   // Calculate the multiplicative inverse of K! / 2^T;
938   // this multiplication factor will perform the exact division by
939   // K! / 2^T.
940   APInt Mod = APInt::getSignedMinValue(W+1);
941   APInt MultiplyFactor = OddFactorial.zext(W+1);
942   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
943   MultiplyFactor = MultiplyFactor.trunc(W);
944 
945   // Calculate the product, at width T+W
946   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
947                                                       CalculationBits);
948   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
949   for (unsigned i = 1; i != K; ++i) {
950     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
951     Dividend = SE.getMulExpr(Dividend,
952                              SE.getTruncateOrZeroExtend(S, CalculationTy));
953   }
954 
955   // Divide by 2^T
956   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
957 
958   // Truncate the result, and divide by K! / 2^T.
959 
960   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
961                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
962 }
963 
964 /// Return the value of this chain of recurrences at the specified iteration
965 /// number.  We can evaluate this recurrence by multiplying each element in the
966 /// chain by the binomial coefficient corresponding to it.  In other words, we
967 /// can evaluate {A,+,B,+,C,+,D} as:
968 ///
969 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
970 ///
971 /// where BC(It, k) stands for binomial coefficient.
972 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
973                                                 ScalarEvolution &SE) const {
974   return evaluateAtIteration(operands(), It, SE);
975 }
976 
977 const SCEV *
978 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
979                                     const SCEV *It, ScalarEvolution &SE) {
980   assert(Operands.size() > 0);
981   const SCEV *Result = Operands[0];
982   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
983     // The computation is correct in the face of overflow provided that the
984     // multiplication is performed _after_ the evaluation of the binomial
985     // coefficient.
986     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
987     if (isa<SCEVCouldNotCompute>(Coeff))
988       return Coeff;
989 
990     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
991   }
992   return Result;
993 }
994 
995 //===----------------------------------------------------------------------===//
996 //                    SCEV Expression folder implementations
997 //===----------------------------------------------------------------------===//
998 
999 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1000                                                      unsigned Depth) {
1001   assert(Depth <= 1 &&
1002          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1003 
1004   // We could be called with an integer-typed operands during SCEV rewrites.
1005   // Since the operand is an integer already, just perform zext/trunc/self cast.
1006   if (!Op->getType()->isPointerTy())
1007     return Op;
1008 
1009   // What would be an ID for such a SCEV cast expression?
1010   FoldingSetNodeID ID;
1011   ID.AddInteger(scPtrToInt);
1012   ID.AddPointer(Op);
1013 
1014   void *IP = nullptr;
1015 
1016   // Is there already an expression for such a cast?
1017   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1018     return S;
1019 
1020   // It isn't legal for optimizations to construct new ptrtoint expressions
1021   // for non-integral pointers.
1022   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1023     return getCouldNotCompute();
1024 
1025   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1026 
1027   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1028   // is sufficiently wide to represent all possible pointer values.
1029   // We could theoretically teach SCEV to truncate wider pointers, but
1030   // that isn't implemented for now.
1031   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1032       getDataLayout().getTypeSizeInBits(IntPtrTy))
1033     return getCouldNotCompute();
1034 
1035   // If not, is this expression something we can't reduce any further?
1036   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1037     // Perform some basic constant folding. If the operand of the ptr2int cast
1038     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1039     // left as-is), but produce a zero constant.
1040     // NOTE: We could handle a more general case, but lack motivational cases.
1041     if (isa<ConstantPointerNull>(U->getValue()))
1042       return getZero(IntPtrTy);
1043 
1044     // Create an explicit cast node.
1045     // We can reuse the existing insert position since if we get here,
1046     // we won't have made any changes which would invalidate it.
1047     SCEV *S = new (SCEVAllocator)
1048         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1049     UniqueSCEVs.InsertNode(S, IP);
1050     registerUser(S, Op);
1051     return S;
1052   }
1053 
1054   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1055                        "non-SCEVUnknown's.");
1056 
1057   // Otherwise, we've got some expression that is more complex than just a
1058   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1059   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1060   // only, and the expressions must otherwise be integer-typed.
1061   // So sink the cast down to the SCEVUnknown's.
1062 
1063   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1064   /// which computes a pointer-typed value, and rewrites the whole expression
1065   /// tree so that *all* the computations are done on integers, and the only
1066   /// pointer-typed operands in the expression are SCEVUnknown.
1067   class SCEVPtrToIntSinkingRewriter
1068       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1069     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1070 
1071   public:
1072     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1073 
1074     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1075       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1076       return Rewriter.visit(Scev);
1077     }
1078 
1079     const SCEV *visit(const SCEV *S) {
1080       Type *STy = S->getType();
1081       // If the expression is not pointer-typed, just keep it as-is.
1082       if (!STy->isPointerTy())
1083         return S;
1084       // Else, recursively sink the cast down into it.
1085       return Base::visit(S);
1086     }
1087 
1088     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1089       SmallVector<const SCEV *, 2> Operands;
1090       bool Changed = false;
1091       for (const auto *Op : Expr->operands()) {
1092         Operands.push_back(visit(Op));
1093         Changed |= Op != Operands.back();
1094       }
1095       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1096     }
1097 
1098     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1099       SmallVector<const SCEV *, 2> Operands;
1100       bool Changed = false;
1101       for (const auto *Op : Expr->operands()) {
1102         Operands.push_back(visit(Op));
1103         Changed |= Op != Operands.back();
1104       }
1105       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1106     }
1107 
1108     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1109       assert(Expr->getType()->isPointerTy() &&
1110              "Should only reach pointer-typed SCEVUnknown's.");
1111       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1112     }
1113   };
1114 
1115   // And actually perform the cast sinking.
1116   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1117   assert(IntOp->getType()->isIntegerTy() &&
1118          "We must have succeeded in sinking the cast, "
1119          "and ending up with an integer-typed expression!");
1120   return IntOp;
1121 }
1122 
1123 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1124   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1125 
1126   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1127   if (isa<SCEVCouldNotCompute>(IntOp))
1128     return IntOp;
1129 
1130   return getTruncateOrZeroExtend(IntOp, Ty);
1131 }
1132 
1133 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1134                                              unsigned Depth) {
1135   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1136          "This is not a truncating conversion!");
1137   assert(isSCEVable(Ty) &&
1138          "This is not a conversion to a SCEVable type!");
1139   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1140   Ty = getEffectiveSCEVType(Ty);
1141 
1142   FoldingSetNodeID ID;
1143   ID.AddInteger(scTruncate);
1144   ID.AddPointer(Op);
1145   ID.AddPointer(Ty);
1146   void *IP = nullptr;
1147   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1148 
1149   // Fold if the operand is constant.
1150   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1151     return getConstant(
1152       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1153 
1154   // trunc(trunc(x)) --> trunc(x)
1155   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1156     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1157 
1158   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1159   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1160     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1161 
1162   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1163   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1164     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1165 
1166   if (Depth > MaxCastDepth) {
1167     SCEV *S =
1168         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1169     UniqueSCEVs.InsertNode(S, IP);
1170     registerUser(S, Op);
1171     return S;
1172   }
1173 
1174   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1175   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1176   // if after transforming we have at most one truncate, not counting truncates
1177   // that replace other casts.
1178   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1179     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1180     SmallVector<const SCEV *, 4> Operands;
1181     unsigned numTruncs = 0;
1182     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1183          ++i) {
1184       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1185       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1186           isa<SCEVTruncateExpr>(S))
1187         numTruncs++;
1188       Operands.push_back(S);
1189     }
1190     if (numTruncs < 2) {
1191       if (isa<SCEVAddExpr>(Op))
1192         return getAddExpr(Operands);
1193       if (isa<SCEVMulExpr>(Op))
1194         return getMulExpr(Operands);
1195       llvm_unreachable("Unexpected SCEV type for Op.");
1196     }
1197     // Although we checked in the beginning that ID is not in the cache, it is
1198     // possible that during recursion and different modification ID was inserted
1199     // into the cache. So if we find it, just return it.
1200     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1201       return S;
1202   }
1203 
1204   // If the input value is a chrec scev, truncate the chrec's operands.
1205   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1206     SmallVector<const SCEV *, 4> Operands;
1207     for (const SCEV *Op : AddRec->operands())
1208       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1209     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1210   }
1211 
1212   // Return zero if truncating to known zeros.
1213   uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1214   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1215     return getZero(Ty);
1216 
1217   // The cast wasn't folded; create an explicit cast node. We can reuse
1218   // the existing insert position since if we get here, we won't have
1219   // made any changes which would invalidate it.
1220   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1221                                                  Op, Ty);
1222   UniqueSCEVs.InsertNode(S, IP);
1223   registerUser(S, Op);
1224   return S;
1225 }
1226 
1227 // Get the limit of a recurrence such that incrementing by Step cannot cause
1228 // signed overflow as long as the value of the recurrence within the
1229 // loop does not exceed this limit before incrementing.
1230 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1231                                                  ICmpInst::Predicate *Pred,
1232                                                  ScalarEvolution *SE) {
1233   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1234   if (SE->isKnownPositive(Step)) {
1235     *Pred = ICmpInst::ICMP_SLT;
1236     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1237                            SE->getSignedRangeMax(Step));
1238   }
1239   if (SE->isKnownNegative(Step)) {
1240     *Pred = ICmpInst::ICMP_SGT;
1241     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1242                            SE->getSignedRangeMin(Step));
1243   }
1244   return nullptr;
1245 }
1246 
1247 // Get the limit of a recurrence such that incrementing by Step cannot cause
1248 // unsigned overflow as long as the value of the recurrence within the loop does
1249 // not exceed this limit before incrementing.
1250 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1251                                                    ICmpInst::Predicate *Pred,
1252                                                    ScalarEvolution *SE) {
1253   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1254   *Pred = ICmpInst::ICMP_ULT;
1255 
1256   return SE->getConstant(APInt::getMinValue(BitWidth) -
1257                          SE->getUnsignedRangeMax(Step));
1258 }
1259 
1260 namespace {
1261 
1262 struct ExtendOpTraitsBase {
1263   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1264                                                           unsigned);
1265 };
1266 
1267 // Used to make code generic over signed and unsigned overflow.
1268 template <typename ExtendOp> struct ExtendOpTraits {
1269   // Members present:
1270   //
1271   // static const SCEV::NoWrapFlags WrapType;
1272   //
1273   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1274   //
1275   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1276   //                                           ICmpInst::Predicate *Pred,
1277   //                                           ScalarEvolution *SE);
1278 };
1279 
1280 template <>
1281 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1282   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1283 
1284   static const GetExtendExprTy GetExtendExpr;
1285 
1286   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1287                                              ICmpInst::Predicate *Pred,
1288                                              ScalarEvolution *SE) {
1289     return getSignedOverflowLimitForStep(Step, Pred, SE);
1290   }
1291 };
1292 
1293 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1294     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1295 
1296 template <>
1297 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1298   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1299 
1300   static const GetExtendExprTy GetExtendExpr;
1301 
1302   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303                                              ICmpInst::Predicate *Pred,
1304                                              ScalarEvolution *SE) {
1305     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1306   }
1307 };
1308 
1309 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1310     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1311 
1312 } // end anonymous namespace
1313 
1314 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1315 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1316 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1317 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1318 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1319 // expression "Step + sext/zext(PreIncAR)" is congruent with
1320 // "sext/zext(PostIncAR)"
1321 template <typename ExtendOpTy>
1322 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1323                                         ScalarEvolution *SE, unsigned Depth) {
1324   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1325   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1326 
1327   const Loop *L = AR->getLoop();
1328   const SCEV *Start = AR->getStart();
1329   const SCEV *Step = AR->getStepRecurrence(*SE);
1330 
1331   // Check for a simple looking step prior to loop entry.
1332   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1333   if (!SA)
1334     return nullptr;
1335 
1336   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1337   // subtraction is expensive. For this purpose, perform a quick and dirty
1338   // difference, by checking for Step in the operand list. Note, that
1339   // SA might have repeated ops, like %a + %a + ..., so only remove one.
1340   SmallVector<const SCEV *, 4> DiffOps(SA->operands());
1341   for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1342     if (*It == Step) {
1343       DiffOps.erase(It);
1344       break;
1345     }
1346 
1347   if (DiffOps.size() == SA->getNumOperands())
1348     return nullptr;
1349 
1350   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1351   // `Step`:
1352 
1353   // 1. NSW/NUW flags on the step increment.
1354   auto PreStartFlags =
1355     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1356   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1357   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1358       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1359 
1360   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1361   // "S+X does not sign/unsign-overflow".
1362   //
1363 
1364   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1365   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1366       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1367     return PreStart;
1368 
1369   // 2. Direct overflow check on the step operation's expression.
1370   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1371   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1372   const SCEV *OperandExtendedStart =
1373       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1374                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1375   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1376     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1377       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1378       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1379       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1380       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1381     }
1382     return PreStart;
1383   }
1384 
1385   // 3. Loop precondition.
1386   ICmpInst::Predicate Pred;
1387   const SCEV *OverflowLimit =
1388       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1389 
1390   if (OverflowLimit &&
1391       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1392     return PreStart;
1393 
1394   return nullptr;
1395 }
1396 
1397 // Get the normalized zero or sign extended expression for this AddRec's Start.
1398 template <typename ExtendOpTy>
1399 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1400                                         ScalarEvolution *SE,
1401                                         unsigned Depth) {
1402   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1403 
1404   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1405   if (!PreStart)
1406     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1407 
1408   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1409                                              Depth),
1410                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1411 }
1412 
1413 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1414 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1415 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1416 //
1417 // Formally:
1418 //
1419 //     {S,+,X} == {S-T,+,X} + T
1420 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1421 //
1422 // If ({S-T,+,X} + T) does not overflow  ... (1)
1423 //
1424 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1425 //
1426 // If {S-T,+,X} does not overflow  ... (2)
1427 //
1428 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1429 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1430 //
1431 // If (S-T)+T does not overflow  ... (3)
1432 //
1433 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1434 //      == {Ext(S),+,Ext(X)} == LHS
1435 //
1436 // Thus, if (1), (2) and (3) are true for some T, then
1437 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1438 //
1439 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1440 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1441 // to check for (1) and (2).
1442 //
1443 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1444 // is `Delta` (defined below).
1445 template <typename ExtendOpTy>
1446 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1447                                                 const SCEV *Step,
1448                                                 const Loop *L) {
1449   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1450 
1451   // We restrict `Start` to a constant to prevent SCEV from spending too much
1452   // time here.  It is correct (but more expensive) to continue with a
1453   // non-constant `Start` and do a general SCEV subtraction to compute
1454   // `PreStart` below.
1455   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1456   if (!StartC)
1457     return false;
1458 
1459   APInt StartAI = StartC->getAPInt();
1460 
1461   for (unsigned Delta : {-2, -1, 1, 2}) {
1462     const SCEV *PreStart = getConstant(StartAI - Delta);
1463 
1464     FoldingSetNodeID ID;
1465     ID.AddInteger(scAddRecExpr);
1466     ID.AddPointer(PreStart);
1467     ID.AddPointer(Step);
1468     ID.AddPointer(L);
1469     void *IP = nullptr;
1470     const auto *PreAR =
1471       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1472 
1473     // Give up if we don't already have the add recurrence we need because
1474     // actually constructing an add recurrence is relatively expensive.
1475     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1476       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1477       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1478       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1479           DeltaS, &Pred, this);
1480       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1481         return true;
1482     }
1483   }
1484 
1485   return false;
1486 }
1487 
1488 // Finds an integer D for an expression (C + x + y + ...) such that the top
1489 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1490 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1491 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1492 // the (C + x + y + ...) expression is \p WholeAddExpr.
1493 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1494                                             const SCEVConstant *ConstantTerm,
1495                                             const SCEVAddExpr *WholeAddExpr) {
1496   const APInt &C = ConstantTerm->getAPInt();
1497   const unsigned BitWidth = C.getBitWidth();
1498   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1499   uint32_t TZ = BitWidth;
1500   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1501     TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1502   if (TZ) {
1503     // Set D to be as many least significant bits of C as possible while still
1504     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1505     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1506   }
1507   return APInt(BitWidth, 0);
1508 }
1509 
1510 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1511 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1512 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1513 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1514 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1515                                             const APInt &ConstantStart,
1516                                             const SCEV *Step) {
1517   const unsigned BitWidth = ConstantStart.getBitWidth();
1518   const uint32_t TZ = SE.getMinTrailingZeros(Step);
1519   if (TZ)
1520     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1521                          : ConstantStart;
1522   return APInt(BitWidth, 0);
1523 }
1524 
1525 static void insertFoldCacheEntry(
1526     const ScalarEvolution::FoldID &ID, const SCEV *S,
1527     DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
1528     DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
1529         &FoldCacheUser) {
1530   auto I = FoldCache.insert({ID, S});
1531   if (!I.second) {
1532     // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1533     // entry.
1534     auto &UserIDs = FoldCacheUser[I.first->second];
1535     assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1536     for (unsigned I = 0; I != UserIDs.size(); ++I)
1537       if (UserIDs[I] == ID) {
1538         std::swap(UserIDs[I], UserIDs.back());
1539         break;
1540       }
1541     UserIDs.pop_back();
1542     I.first->second = S;
1543   }
1544   auto R = FoldCacheUser.insert({S, {}});
1545   R.first->second.push_back(ID);
1546 }
1547 
1548 const SCEV *
1549 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1550   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1551          "This is not an extending conversion!");
1552   assert(isSCEVable(Ty) &&
1553          "This is not a conversion to a SCEVable type!");
1554   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1555   Ty = getEffectiveSCEVType(Ty);
1556 
1557   FoldID ID(scZeroExtend, Op, Ty);
1558   auto Iter = FoldCache.find(ID);
1559   if (Iter != FoldCache.end())
1560     return Iter->second;
1561 
1562   const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1563   if (!isa<SCEVZeroExtendExpr>(S))
1564     insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1565   return S;
1566 }
1567 
1568 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1569                                                    unsigned Depth) {
1570   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1571          "This is not an extending conversion!");
1572   assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1573   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1574 
1575   // Fold if the operand is constant.
1576   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1577     return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1578 
1579   // zext(zext(x)) --> zext(x)
1580   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1581     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1582 
1583   // Before doing any expensive analysis, check to see if we've already
1584   // computed a SCEV for this Op and Ty.
1585   FoldingSetNodeID ID;
1586   ID.AddInteger(scZeroExtend);
1587   ID.AddPointer(Op);
1588   ID.AddPointer(Ty);
1589   void *IP = nullptr;
1590   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1591   if (Depth > MaxCastDepth) {
1592     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1593                                                      Op, Ty);
1594     UniqueSCEVs.InsertNode(S, IP);
1595     registerUser(S, Op);
1596     return S;
1597   }
1598 
1599   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1600   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1601     // It's possible the bits taken off by the truncate were all zero bits. If
1602     // so, we should be able to simplify this further.
1603     const SCEV *X = ST->getOperand();
1604     ConstantRange CR = getUnsignedRange(X);
1605     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1606     unsigned NewBits = getTypeSizeInBits(Ty);
1607     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1608             CR.zextOrTrunc(NewBits)))
1609       return getTruncateOrZeroExtend(X, Ty, Depth);
1610   }
1611 
1612   // If the input value is a chrec scev, and we can prove that the value
1613   // did not overflow the old, smaller, value, we can zero extend all of the
1614   // operands (often constants).  This allows analysis of something like
1615   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1616   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1617     if (AR->isAffine()) {
1618       const SCEV *Start = AR->getStart();
1619       const SCEV *Step = AR->getStepRecurrence(*this);
1620       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1621       const Loop *L = AR->getLoop();
1622 
1623       // If we have special knowledge that this addrec won't overflow,
1624       // we don't need to do any further analysis.
1625       if (AR->hasNoUnsignedWrap()) {
1626         Start =
1627             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1628         Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1629         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1630       }
1631 
1632       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1633       // Note that this serves two purposes: It filters out loops that are
1634       // simply not analyzable, and it covers the case where this code is
1635       // being called from within backedge-taken count analysis, such that
1636       // attempting to ask for the backedge-taken count would likely result
1637       // in infinite recursion. In the later case, the analysis code will
1638       // cope with a conservative value, and it will take care to purge
1639       // that value once it has finished.
1640       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1641       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1642         // Manually compute the final value for AR, checking for overflow.
1643 
1644         // Check whether the backedge-taken count can be losslessly casted to
1645         // the addrec's type. The count is always unsigned.
1646         const SCEV *CastedMaxBECount =
1647             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1648         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1649             CastedMaxBECount, MaxBECount->getType(), Depth);
1650         if (MaxBECount == RecastedMaxBECount) {
1651           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1652           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1653           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1654                                         SCEV::FlagAnyWrap, Depth + 1);
1655           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1656                                                           SCEV::FlagAnyWrap,
1657                                                           Depth + 1),
1658                                                WideTy, Depth + 1);
1659           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1660           const SCEV *WideMaxBECount =
1661             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1662           const SCEV *OperandExtendedAdd =
1663             getAddExpr(WideStart,
1664                        getMulExpr(WideMaxBECount,
1665                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1666                                   SCEV::FlagAnyWrap, Depth + 1),
1667                        SCEV::FlagAnyWrap, Depth + 1);
1668           if (ZAdd == OperandExtendedAdd) {
1669             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1670             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1671             // Return the expression with the addrec on the outside.
1672             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1673                                                              Depth + 1);
1674             Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1675             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1676           }
1677           // Similar to above, only this time treat the step value as signed.
1678           // This covers loops that count down.
1679           OperandExtendedAdd =
1680             getAddExpr(WideStart,
1681                        getMulExpr(WideMaxBECount,
1682                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1683                                   SCEV::FlagAnyWrap, Depth + 1),
1684                        SCEV::FlagAnyWrap, Depth + 1);
1685           if (ZAdd == OperandExtendedAdd) {
1686             // Cache knowledge of AR NW, which is propagated to this AddRec.
1687             // Negative step causes unsigned wrap, but it still can't self-wrap.
1688             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1689             // Return the expression with the addrec on the outside.
1690             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1691                                                              Depth + 1);
1692             Step = getSignExtendExpr(Step, Ty, Depth + 1);
1693             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1694           }
1695         }
1696       }
1697 
1698       // Normally, in the cases we can prove no-overflow via a
1699       // backedge guarding condition, we can also compute a backedge
1700       // taken count for the loop.  The exceptions are assumptions and
1701       // guards present in the loop -- SCEV is not great at exploiting
1702       // these to compute max backedge taken counts, but can still use
1703       // these to prove lack of overflow.  Use this fact to avoid
1704       // doing extra work that may not pay off.
1705       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1706           !AC.assumptions().empty()) {
1707 
1708         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1709         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1710         if (AR->hasNoUnsignedWrap()) {
1711           // Same as nuw case above - duplicated here to avoid a compile time
1712           // issue.  It's not clear that the order of checks does matter, but
1713           // it's one of two issue possible causes for a change which was
1714           // reverted.  Be conservative for the moment.
1715           Start =
1716               getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1717           Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1718           return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1719         }
1720 
1721         // For a negative step, we can extend the operands iff doing so only
1722         // traverses values in the range zext([0,UINT_MAX]).
1723         if (isKnownNegative(Step)) {
1724           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1725                                       getSignedRangeMin(Step));
1726           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1727               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1728             // Cache knowledge of AR NW, which is propagated to this
1729             // AddRec.  Negative step causes unsigned wrap, but it
1730             // still can't self-wrap.
1731             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1732             // Return the expression with the addrec on the outside.
1733             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1734                                                              Depth + 1);
1735             Step = getSignExtendExpr(Step, Ty, Depth + 1);
1736             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1737           }
1738         }
1739       }
1740 
1741       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1742       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1743       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1744       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1745         const APInt &C = SC->getAPInt();
1746         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1747         if (D != 0) {
1748           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1749           const SCEV *SResidual =
1750               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1751           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1752           return getAddExpr(SZExtD, SZExtR,
1753                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1754                             Depth + 1);
1755         }
1756       }
1757 
1758       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1759         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1760         Start =
1761             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1762         Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1763         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1764       }
1765     }
1766 
1767   // zext(A % B) --> zext(A) % zext(B)
1768   {
1769     const SCEV *LHS;
1770     const SCEV *RHS;
1771     if (matchURem(Op, LHS, RHS))
1772       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1773                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1774   }
1775 
1776   // zext(A / B) --> zext(A) / zext(B).
1777   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1778     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1779                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1780 
1781   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1782     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1783     if (SA->hasNoUnsignedWrap()) {
1784       // If the addition does not unsign overflow then we can, by definition,
1785       // commute the zero extension with the addition operation.
1786       SmallVector<const SCEV *, 4> Ops;
1787       for (const auto *Op : SA->operands())
1788         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1789       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1790     }
1791 
1792     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1793     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1794     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1795     //
1796     // Often address arithmetics contain expressions like
1797     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1798     // This transformation is useful while proving that such expressions are
1799     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1800     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1801       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1802       if (D != 0) {
1803         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1804         const SCEV *SResidual =
1805             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1806         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1807         return getAddExpr(SZExtD, SZExtR,
1808                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1809                           Depth + 1);
1810       }
1811     }
1812   }
1813 
1814   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1815     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1816     if (SM->hasNoUnsignedWrap()) {
1817       // If the multiply does not unsign overflow then we can, by definition,
1818       // commute the zero extension with the multiply operation.
1819       SmallVector<const SCEV *, 4> Ops;
1820       for (const auto *Op : SM->operands())
1821         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1822       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1823     }
1824 
1825     // zext(2^K * (trunc X to iN)) to iM ->
1826     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1827     //
1828     // Proof:
1829     //
1830     //     zext(2^K * (trunc X to iN)) to iM
1831     //   = zext((trunc X to iN) << K) to iM
1832     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1833     //     (because shl removes the top K bits)
1834     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1835     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1836     //
1837     if (SM->getNumOperands() == 2)
1838       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1839         if (MulLHS->getAPInt().isPowerOf2())
1840           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1841             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1842                                MulLHS->getAPInt().logBase2();
1843             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1844             return getMulExpr(
1845                 getZeroExtendExpr(MulLHS, Ty),
1846                 getZeroExtendExpr(
1847                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1848                 SCEV::FlagNUW, Depth + 1);
1849           }
1850   }
1851 
1852   // zext(umin(x, y)) -> umin(zext(x), zext(y))
1853   // zext(umax(x, y)) -> umax(zext(x), zext(y))
1854   if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1855     auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1856     SmallVector<const SCEV *, 4> Operands;
1857     for (auto *Operand : MinMax->operands())
1858       Operands.push_back(getZeroExtendExpr(Operand, Ty));
1859     if (isa<SCEVUMinExpr>(MinMax))
1860       return getUMinExpr(Operands);
1861     return getUMaxExpr(Operands);
1862   }
1863 
1864   // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1865   if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1866     assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1867     SmallVector<const SCEV *, 4> Operands;
1868     for (auto *Operand : MinMax->operands())
1869       Operands.push_back(getZeroExtendExpr(Operand, Ty));
1870     return getUMinExpr(Operands, /*Sequential*/ true);
1871   }
1872 
1873   // The cast wasn't folded; create an explicit cast node.
1874   // Recompute the insert position, as it may have been invalidated.
1875   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1876   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1877                                                    Op, Ty);
1878   UniqueSCEVs.InsertNode(S, IP);
1879   registerUser(S, Op);
1880   return S;
1881 }
1882 
1883 const SCEV *
1884 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1885   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1886          "This is not an extending conversion!");
1887   assert(isSCEVable(Ty) &&
1888          "This is not a conversion to a SCEVable type!");
1889   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1890   Ty = getEffectiveSCEVType(Ty);
1891 
1892   FoldID ID(scSignExtend, Op, Ty);
1893   auto Iter = FoldCache.find(ID);
1894   if (Iter != FoldCache.end())
1895     return Iter->second;
1896 
1897   const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1898   if (!isa<SCEVSignExtendExpr>(S))
1899     insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1900   return S;
1901 }
1902 
1903 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1904                                                    unsigned Depth) {
1905   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1906          "This is not an extending conversion!");
1907   assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1908   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1909   Ty = getEffectiveSCEVType(Ty);
1910 
1911   // Fold if the operand is constant.
1912   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1913     return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1914 
1915   // sext(sext(x)) --> sext(x)
1916   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1917     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1918 
1919   // sext(zext(x)) --> zext(x)
1920   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1921     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1922 
1923   // Before doing any expensive analysis, check to see if we've already
1924   // computed a SCEV for this Op and Ty.
1925   FoldingSetNodeID ID;
1926   ID.AddInteger(scSignExtend);
1927   ID.AddPointer(Op);
1928   ID.AddPointer(Ty);
1929   void *IP = nullptr;
1930   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1931   // Limit recursion depth.
1932   if (Depth > MaxCastDepth) {
1933     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1934                                                      Op, Ty);
1935     UniqueSCEVs.InsertNode(S, IP);
1936     registerUser(S, Op);
1937     return S;
1938   }
1939 
1940   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1941   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1942     // It's possible the bits taken off by the truncate were all sign bits. If
1943     // so, we should be able to simplify this further.
1944     const SCEV *X = ST->getOperand();
1945     ConstantRange CR = getSignedRange(X);
1946     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1947     unsigned NewBits = getTypeSizeInBits(Ty);
1948     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1949             CR.sextOrTrunc(NewBits)))
1950       return getTruncateOrSignExtend(X, Ty, Depth);
1951   }
1952 
1953   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1954     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1955     if (SA->hasNoSignedWrap()) {
1956       // If the addition does not sign overflow then we can, by definition,
1957       // commute the sign extension with the addition operation.
1958       SmallVector<const SCEV *, 4> Ops;
1959       for (const auto *Op : SA->operands())
1960         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1961       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1962     }
1963 
1964     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1965     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1966     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1967     //
1968     // For instance, this will bring two seemingly different expressions:
1969     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1970     //         sext(6 + 20 * %x + 24 * %y)
1971     // to the same form:
1972     //     2 + sext(4 + 20 * %x + 24 * %y)
1973     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1974       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1975       if (D != 0) {
1976         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1977         const SCEV *SResidual =
1978             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1979         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1980         return getAddExpr(SSExtD, SSExtR,
1981                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1982                           Depth + 1);
1983       }
1984     }
1985   }
1986   // If the input value is a chrec scev, and we can prove that the value
1987   // did not overflow the old, smaller, value, we can sign extend all of the
1988   // operands (often constants).  This allows analysis of something like
1989   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1990   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1991     if (AR->isAffine()) {
1992       const SCEV *Start = AR->getStart();
1993       const SCEV *Step = AR->getStepRecurrence(*this);
1994       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1995       const Loop *L = AR->getLoop();
1996 
1997       // If we have special knowledge that this addrec won't overflow,
1998       // we don't need to do any further analysis.
1999       if (AR->hasNoSignedWrap()) {
2000         Start =
2001             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2002         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2003         return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2004       }
2005 
2006       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2007       // Note that this serves two purposes: It filters out loops that are
2008       // simply not analyzable, and it covers the case where this code is
2009       // being called from within backedge-taken count analysis, such that
2010       // attempting to ask for the backedge-taken count would likely result
2011       // in infinite recursion. In the later case, the analysis code will
2012       // cope with a conservative value, and it will take care to purge
2013       // that value once it has finished.
2014       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2015       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2016         // Manually compute the final value for AR, checking for
2017         // overflow.
2018 
2019         // Check whether the backedge-taken count can be losslessly casted to
2020         // the addrec's type. The count is always unsigned.
2021         const SCEV *CastedMaxBECount =
2022             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2023         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2024             CastedMaxBECount, MaxBECount->getType(), Depth);
2025         if (MaxBECount == RecastedMaxBECount) {
2026           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2027           // Check whether Start+Step*MaxBECount has no signed overflow.
2028           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2029                                         SCEV::FlagAnyWrap, Depth + 1);
2030           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2031                                                           SCEV::FlagAnyWrap,
2032                                                           Depth + 1),
2033                                                WideTy, Depth + 1);
2034           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2035           const SCEV *WideMaxBECount =
2036             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2037           const SCEV *OperandExtendedAdd =
2038             getAddExpr(WideStart,
2039                        getMulExpr(WideMaxBECount,
2040                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2041                                   SCEV::FlagAnyWrap, Depth + 1),
2042                        SCEV::FlagAnyWrap, Depth + 1);
2043           if (SAdd == OperandExtendedAdd) {
2044             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2045             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2046             // Return the expression with the addrec on the outside.
2047             Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2048                                                              Depth + 1);
2049             Step = getSignExtendExpr(Step, Ty, Depth + 1);
2050             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2051           }
2052           // Similar to above, only this time treat the step value as unsigned.
2053           // This covers loops that count up with an unsigned step.
2054           OperandExtendedAdd =
2055             getAddExpr(WideStart,
2056                        getMulExpr(WideMaxBECount,
2057                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2058                                   SCEV::FlagAnyWrap, Depth + 1),
2059                        SCEV::FlagAnyWrap, Depth + 1);
2060           if (SAdd == OperandExtendedAdd) {
2061             // If AR wraps around then
2062             //
2063             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2064             // => SAdd != OperandExtendedAdd
2065             //
2066             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2067             // (SAdd == OperandExtendedAdd => AR is NW)
2068 
2069             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2070 
2071             // Return the expression with the addrec on the outside.
2072             Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2073                                                              Depth + 1);
2074             Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2075             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2076           }
2077         }
2078       }
2079 
2080       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2081       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2082       if (AR->hasNoSignedWrap()) {
2083         // Same as nsw case above - duplicated here to avoid a compile time
2084         // issue.  It's not clear that the order of checks does matter, but
2085         // it's one of two issue possible causes for a change which was
2086         // reverted.  Be conservative for the moment.
2087         Start =
2088             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2089         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2090         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2091       }
2092 
2093       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2094       // if D + (C - D + Step * n) could be proven to not signed wrap
2095       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2096       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2097         const APInt &C = SC->getAPInt();
2098         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2099         if (D != 0) {
2100           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2101           const SCEV *SResidual =
2102               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2103           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2104           return getAddExpr(SSExtD, SSExtR,
2105                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2106                             Depth + 1);
2107         }
2108       }
2109 
2110       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2111         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2112         Start =
2113             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2114         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2115         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2116       }
2117     }
2118 
2119   // If the input value is provably positive and we could not simplify
2120   // away the sext build a zext instead.
2121   if (isKnownNonNegative(Op))
2122     return getZeroExtendExpr(Op, Ty, Depth + 1);
2123 
2124   // sext(smin(x, y)) -> smin(sext(x), sext(y))
2125   // sext(smax(x, y)) -> smax(sext(x), sext(y))
2126   if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2127     auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2128     SmallVector<const SCEV *, 4> Operands;
2129     for (auto *Operand : MinMax->operands())
2130       Operands.push_back(getSignExtendExpr(Operand, Ty));
2131     if (isa<SCEVSMinExpr>(MinMax))
2132       return getSMinExpr(Operands);
2133     return getSMaxExpr(Operands);
2134   }
2135 
2136   // The cast wasn't folded; create an explicit cast node.
2137   // Recompute the insert position, as it may have been invalidated.
2138   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2139   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2140                                                    Op, Ty);
2141   UniqueSCEVs.InsertNode(S, IP);
2142   registerUser(S, { Op });
2143   return S;
2144 }
2145 
2146 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2147                                          Type *Ty) {
2148   switch (Kind) {
2149   case scTruncate:
2150     return getTruncateExpr(Op, Ty);
2151   case scZeroExtend:
2152     return getZeroExtendExpr(Op, Ty);
2153   case scSignExtend:
2154     return getSignExtendExpr(Op, Ty);
2155   case scPtrToInt:
2156     return getPtrToIntExpr(Op, Ty);
2157   default:
2158     llvm_unreachable("Not a SCEV cast expression!");
2159   }
2160 }
2161 
2162 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2163 /// unspecified bits out to the given type.
2164 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2165                                               Type *Ty) {
2166   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2167          "This is not an extending conversion!");
2168   assert(isSCEVable(Ty) &&
2169          "This is not a conversion to a SCEVable type!");
2170   Ty = getEffectiveSCEVType(Ty);
2171 
2172   // Sign-extend negative constants.
2173   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2174     if (SC->getAPInt().isNegative())
2175       return getSignExtendExpr(Op, Ty);
2176 
2177   // Peel off a truncate cast.
2178   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2179     const SCEV *NewOp = T->getOperand();
2180     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2181       return getAnyExtendExpr(NewOp, Ty);
2182     return getTruncateOrNoop(NewOp, Ty);
2183   }
2184 
2185   // Next try a zext cast. If the cast is folded, use it.
2186   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2187   if (!isa<SCEVZeroExtendExpr>(ZExt))
2188     return ZExt;
2189 
2190   // Next try a sext cast. If the cast is folded, use it.
2191   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2192   if (!isa<SCEVSignExtendExpr>(SExt))
2193     return SExt;
2194 
2195   // Force the cast to be folded into the operands of an addrec.
2196   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2197     SmallVector<const SCEV *, 4> Ops;
2198     for (const SCEV *Op : AR->operands())
2199       Ops.push_back(getAnyExtendExpr(Op, Ty));
2200     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2201   }
2202 
2203   // If the expression is obviously signed, use the sext cast value.
2204   if (isa<SCEVSMaxExpr>(Op))
2205     return SExt;
2206 
2207   // Absent any other information, use the zext cast value.
2208   return ZExt;
2209 }
2210 
2211 /// Process the given Ops list, which is a list of operands to be added under
2212 /// the given scale, update the given map. This is a helper function for
2213 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2214 /// that would form an add expression like this:
2215 ///
2216 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2217 ///
2218 /// where A and B are constants, update the map with these values:
2219 ///
2220 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2221 ///
2222 /// and add 13 + A*B*29 to AccumulatedConstant.
2223 /// This will allow getAddRecExpr to produce this:
2224 ///
2225 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2226 ///
2227 /// This form often exposes folding opportunities that are hidden in
2228 /// the original operand list.
2229 ///
2230 /// Return true iff it appears that any interesting folding opportunities
2231 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2232 /// the common case where no interesting opportunities are present, and
2233 /// is also used as a check to avoid infinite recursion.
2234 static bool
2235 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2236                              SmallVectorImpl<const SCEV *> &NewOps,
2237                              APInt &AccumulatedConstant,
2238                              ArrayRef<const SCEV *> Ops, const APInt &Scale,
2239                              ScalarEvolution &SE) {
2240   bool Interesting = false;
2241 
2242   // Iterate over the add operands. They are sorted, with constants first.
2243   unsigned i = 0;
2244   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2245     ++i;
2246     // Pull a buried constant out to the outside.
2247     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2248       Interesting = true;
2249     AccumulatedConstant += Scale * C->getAPInt();
2250   }
2251 
2252   // Next comes everything else. We're especially interested in multiplies
2253   // here, but they're in the middle, so just visit the rest with one loop.
2254   for (; i != Ops.size(); ++i) {
2255     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2256     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2257       APInt NewScale =
2258           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2259       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2260         // A multiplication of a constant with another add; recurse.
2261         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2262         Interesting |=
2263           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2264                                        Add->operands(), NewScale, SE);
2265       } else {
2266         // A multiplication of a constant with some other value. Update
2267         // the map.
2268         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2269         const SCEV *Key = SE.getMulExpr(MulOps);
2270         auto Pair = M.insert({Key, NewScale});
2271         if (Pair.second) {
2272           NewOps.push_back(Pair.first->first);
2273         } else {
2274           Pair.first->second += NewScale;
2275           // The map already had an entry for this value, which may indicate
2276           // a folding opportunity.
2277           Interesting = true;
2278         }
2279       }
2280     } else {
2281       // An ordinary operand. Update the map.
2282       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2283           M.insert({Ops[i], Scale});
2284       if (Pair.second) {
2285         NewOps.push_back(Pair.first->first);
2286       } else {
2287         Pair.first->second += Scale;
2288         // The map already had an entry for this value, which may indicate
2289         // a folding opportunity.
2290         Interesting = true;
2291       }
2292     }
2293   }
2294 
2295   return Interesting;
2296 }
2297 
2298 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2299                                       const SCEV *LHS, const SCEV *RHS,
2300                                       const Instruction *CtxI) {
2301   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2302                                             SCEV::NoWrapFlags, unsigned);
2303   switch (BinOp) {
2304   default:
2305     llvm_unreachable("Unsupported binary op");
2306   case Instruction::Add:
2307     Operation = &ScalarEvolution::getAddExpr;
2308     break;
2309   case Instruction::Sub:
2310     Operation = &ScalarEvolution::getMinusSCEV;
2311     break;
2312   case Instruction::Mul:
2313     Operation = &ScalarEvolution::getMulExpr;
2314     break;
2315   }
2316 
2317   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2318       Signed ? &ScalarEvolution::getSignExtendExpr
2319              : &ScalarEvolution::getZeroExtendExpr;
2320 
2321   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2322   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2323   auto *WideTy =
2324       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2325 
2326   const SCEV *A = (this->*Extension)(
2327       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2328   const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2329   const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2330   const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2331   if (A == B)
2332     return true;
2333   // Can we use context to prove the fact we need?
2334   if (!CtxI)
2335     return false;
2336   // TODO: Support mul.
2337   if (BinOp == Instruction::Mul)
2338     return false;
2339   auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2340   // TODO: Lift this limitation.
2341   if (!RHSC)
2342     return false;
2343   APInt C = RHSC->getAPInt();
2344   unsigned NumBits = C.getBitWidth();
2345   bool IsSub = (BinOp == Instruction::Sub);
2346   bool IsNegativeConst = (Signed && C.isNegative());
2347   // Compute the direction and magnitude by which we need to check overflow.
2348   bool OverflowDown = IsSub ^ IsNegativeConst;
2349   APInt Magnitude = C;
2350   if (IsNegativeConst) {
2351     if (C == APInt::getSignedMinValue(NumBits))
2352       // TODO: SINT_MIN on inversion gives the same negative value, we don't
2353       // want to deal with that.
2354       return false;
2355     Magnitude = -C;
2356   }
2357 
2358   ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
2359   if (OverflowDown) {
2360     // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2361     APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2362                        : APInt::getMinValue(NumBits);
2363     APInt Limit = Min + Magnitude;
2364     return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2365   } else {
2366     // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2367     APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2368                        : APInt::getMaxValue(NumBits);
2369     APInt Limit = Max - Magnitude;
2370     return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2371   }
2372 }
2373 
2374 std::optional<SCEV::NoWrapFlags>
2375 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2376     const OverflowingBinaryOperator *OBO) {
2377   // It cannot be done any better.
2378   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2379     return std::nullopt;
2380 
2381   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2382 
2383   if (OBO->hasNoUnsignedWrap())
2384     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2385   if (OBO->hasNoSignedWrap())
2386     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2387 
2388   bool Deduced = false;
2389 
2390   if (OBO->getOpcode() != Instruction::Add &&
2391       OBO->getOpcode() != Instruction::Sub &&
2392       OBO->getOpcode() != Instruction::Mul)
2393     return std::nullopt;
2394 
2395   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2396   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2397 
2398   const Instruction *CtxI =
2399       UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2400   if (!OBO->hasNoUnsignedWrap() &&
2401       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2402                       /* Signed */ false, LHS, RHS, CtxI)) {
2403     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2404     Deduced = true;
2405   }
2406 
2407   if (!OBO->hasNoSignedWrap() &&
2408       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2409                       /* Signed */ true, LHS, RHS, CtxI)) {
2410     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2411     Deduced = true;
2412   }
2413 
2414   if (Deduced)
2415     return Flags;
2416   return std::nullopt;
2417 }
2418 
2419 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2420 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2421 // can't-overflow flags for the operation if possible.
2422 static SCEV::NoWrapFlags
2423 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2424                       const ArrayRef<const SCEV *> Ops,
2425                       SCEV::NoWrapFlags Flags) {
2426   using namespace std::placeholders;
2427 
2428   using OBO = OverflowingBinaryOperator;
2429 
2430   bool CanAnalyze =
2431       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2432   (void)CanAnalyze;
2433   assert(CanAnalyze && "don't call from other places!");
2434 
2435   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2436   SCEV::NoWrapFlags SignOrUnsignWrap =
2437       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2438 
2439   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2440   auto IsKnownNonNegative = [&](const SCEV *S) {
2441     return SE->isKnownNonNegative(S);
2442   };
2443 
2444   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2445     Flags =
2446         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2447 
2448   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2449 
2450   if (SignOrUnsignWrap != SignOrUnsignMask &&
2451       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2452       isa<SCEVConstant>(Ops[0])) {
2453 
2454     auto Opcode = [&] {
2455       switch (Type) {
2456       case scAddExpr:
2457         return Instruction::Add;
2458       case scMulExpr:
2459         return Instruction::Mul;
2460       default:
2461         llvm_unreachable("Unexpected SCEV op.");
2462       }
2463     }();
2464 
2465     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2466 
2467     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2468     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2469       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2470           Opcode, C, OBO::NoSignedWrap);
2471       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2472         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2473     }
2474 
2475     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2476     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2477       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2478           Opcode, C, OBO::NoUnsignedWrap);
2479       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2480         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2481     }
2482   }
2483 
2484   // <0,+,nonnegative><nw> is also nuw
2485   // TODO: Add corresponding nsw case
2486   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2487       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2488       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2489     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2490 
2491   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2492   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2493       Ops.size() == 2) {
2494     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2495       if (UDiv->getOperand(1) == Ops[1])
2496         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2497     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2498       if (UDiv->getOperand(1) == Ops[0])
2499         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2500   }
2501 
2502   return Flags;
2503 }
2504 
2505 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2506   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2507 }
2508 
2509 /// Get a canonical add expression, or something simpler if possible.
2510 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2511                                         SCEV::NoWrapFlags OrigFlags,
2512                                         unsigned Depth) {
2513   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2514          "only nuw or nsw allowed");
2515   assert(!Ops.empty() && "Cannot get empty add!");
2516   if (Ops.size() == 1) return Ops[0];
2517 #ifndef NDEBUG
2518   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2519   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2520     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2521            "SCEVAddExpr operand types don't match!");
2522   unsigned NumPtrs = count_if(
2523       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2524   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2525 #endif
2526 
2527   // Sort by complexity, this groups all similar expression types together.
2528   GroupByComplexity(Ops, &LI, DT);
2529 
2530   // If there are any constants, fold them together.
2531   unsigned Idx = 0;
2532   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2533     ++Idx;
2534     assert(Idx < Ops.size());
2535     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2536       // We found two constants, fold them together!
2537       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2538       if (Ops.size() == 2) return Ops[0];
2539       Ops.erase(Ops.begin()+1);  // Erase the folded element
2540       LHSC = cast<SCEVConstant>(Ops[0]);
2541     }
2542 
2543     // If we are left with a constant zero being added, strip it off.
2544     if (LHSC->getValue()->isZero()) {
2545       Ops.erase(Ops.begin());
2546       --Idx;
2547     }
2548 
2549     if (Ops.size() == 1) return Ops[0];
2550   }
2551 
2552   // Delay expensive flag strengthening until necessary.
2553   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2554     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2555   };
2556 
2557   // Limit recursion calls depth.
2558   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2559     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2560 
2561   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2562     // Don't strengthen flags if we have no new information.
2563     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2564     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2565       Add->setNoWrapFlags(ComputeFlags(Ops));
2566     return S;
2567   }
2568 
2569   // Okay, check to see if the same value occurs in the operand list more than
2570   // once.  If so, merge them together into an multiply expression.  Since we
2571   // sorted the list, these values are required to be adjacent.
2572   Type *Ty = Ops[0]->getType();
2573   bool FoundMatch = false;
2574   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2575     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2576       // Scan ahead to count how many equal operands there are.
2577       unsigned Count = 2;
2578       while (i+Count != e && Ops[i+Count] == Ops[i])
2579         ++Count;
2580       // Merge the values into a multiply.
2581       const SCEV *Scale = getConstant(Ty, Count);
2582       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2583       if (Ops.size() == Count)
2584         return Mul;
2585       Ops[i] = Mul;
2586       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2587       --i; e -= Count - 1;
2588       FoundMatch = true;
2589     }
2590   if (FoundMatch)
2591     return getAddExpr(Ops, OrigFlags, Depth + 1);
2592 
2593   // Check for truncates. If all the operands are truncated from the same
2594   // type, see if factoring out the truncate would permit the result to be
2595   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2596   // if the contents of the resulting outer trunc fold to something simple.
2597   auto FindTruncSrcType = [&]() -> Type * {
2598     // We're ultimately looking to fold an addrec of truncs and muls of only
2599     // constants and truncs, so if we find any other types of SCEV
2600     // as operands of the addrec then we bail and return nullptr here.
2601     // Otherwise, we return the type of the operand of a trunc that we find.
2602     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2603       return T->getOperand()->getType();
2604     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2605       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2606       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2607         return T->getOperand()->getType();
2608     }
2609     return nullptr;
2610   };
2611   if (auto *SrcType = FindTruncSrcType()) {
2612     SmallVector<const SCEV *, 8> LargeOps;
2613     bool Ok = true;
2614     // Check all the operands to see if they can be represented in the
2615     // source type of the truncate.
2616     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2617       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2618         if (T->getOperand()->getType() != SrcType) {
2619           Ok = false;
2620           break;
2621         }
2622         LargeOps.push_back(T->getOperand());
2623       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2624         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2625       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2626         SmallVector<const SCEV *, 8> LargeMulOps;
2627         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2628           if (const SCEVTruncateExpr *T =
2629                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2630             if (T->getOperand()->getType() != SrcType) {
2631               Ok = false;
2632               break;
2633             }
2634             LargeMulOps.push_back(T->getOperand());
2635           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2636             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2637           } else {
2638             Ok = false;
2639             break;
2640           }
2641         }
2642         if (Ok)
2643           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2644       } else {
2645         Ok = false;
2646         break;
2647       }
2648     }
2649     if (Ok) {
2650       // Evaluate the expression in the larger type.
2651       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2652       // If it folds to something simple, use it. Otherwise, don't.
2653       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2654         return getTruncateExpr(Fold, Ty);
2655     }
2656   }
2657 
2658   if (Ops.size() == 2) {
2659     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2660     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2661     // C1).
2662     const SCEV *A = Ops[0];
2663     const SCEV *B = Ops[1];
2664     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2665     auto *C = dyn_cast<SCEVConstant>(A);
2666     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2667       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2668       auto C2 = C->getAPInt();
2669       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2670 
2671       APInt ConstAdd = C1 + C2;
2672       auto AddFlags = AddExpr->getNoWrapFlags();
2673       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2674       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2675           ConstAdd.ule(C1)) {
2676         PreservedFlags =
2677             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2678       }
2679 
2680       // Adding a constant with the same sign and small magnitude is NSW, if the
2681       // original AddExpr was NSW.
2682       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2683           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2684           ConstAdd.abs().ule(C1.abs())) {
2685         PreservedFlags =
2686             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2687       }
2688 
2689       if (PreservedFlags != SCEV::FlagAnyWrap) {
2690         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2691         NewOps[0] = getConstant(ConstAdd);
2692         return getAddExpr(NewOps, PreservedFlags);
2693       }
2694     }
2695   }
2696 
2697   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2698   if (Ops.size() == 2) {
2699     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2700     if (Mul && Mul->getNumOperands() == 2 &&
2701         Mul->getOperand(0)->isAllOnesValue()) {
2702       const SCEV *X;
2703       const SCEV *Y;
2704       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2705         return getMulExpr(Y, getUDivExpr(X, Y));
2706       }
2707     }
2708   }
2709 
2710   // Skip past any other cast SCEVs.
2711   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2712     ++Idx;
2713 
2714   // If there are add operands they would be next.
2715   if (Idx < Ops.size()) {
2716     bool DeletedAdd = false;
2717     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2718     // common NUW flag for expression after inlining. Other flags cannot be
2719     // preserved, because they may depend on the original order of operations.
2720     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2721     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2722       if (Ops.size() > AddOpsInlineThreshold ||
2723           Add->getNumOperands() > AddOpsInlineThreshold)
2724         break;
2725       // If we have an add, expand the add operands onto the end of the operands
2726       // list.
2727       Ops.erase(Ops.begin()+Idx);
2728       append_range(Ops, Add->operands());
2729       DeletedAdd = true;
2730       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2731     }
2732 
2733     // If we deleted at least one add, we added operands to the end of the list,
2734     // and they are not necessarily sorted.  Recurse to resort and resimplify
2735     // any operands we just acquired.
2736     if (DeletedAdd)
2737       return getAddExpr(Ops, CommonFlags, Depth + 1);
2738   }
2739 
2740   // Skip over the add expression until we get to a multiply.
2741   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2742     ++Idx;
2743 
2744   // Check to see if there are any folding opportunities present with
2745   // operands multiplied by constant values.
2746   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2747     uint64_t BitWidth = getTypeSizeInBits(Ty);
2748     DenseMap<const SCEV *, APInt> M;
2749     SmallVector<const SCEV *, 8> NewOps;
2750     APInt AccumulatedConstant(BitWidth, 0);
2751     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2752                                      Ops, APInt(BitWidth, 1), *this)) {
2753       struct APIntCompare {
2754         bool operator()(const APInt &LHS, const APInt &RHS) const {
2755           return LHS.ult(RHS);
2756         }
2757       };
2758 
2759       // Some interesting folding opportunity is present, so its worthwhile to
2760       // re-generate the operands list. Group the operands by constant scale,
2761       // to avoid multiplying by the same constant scale multiple times.
2762       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2763       for (const SCEV *NewOp : NewOps)
2764         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2765       // Re-generate the operands list.
2766       Ops.clear();
2767       if (AccumulatedConstant != 0)
2768         Ops.push_back(getConstant(AccumulatedConstant));
2769       for (auto &MulOp : MulOpLists) {
2770         if (MulOp.first == 1) {
2771           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2772         } else if (MulOp.first != 0) {
2773           Ops.push_back(getMulExpr(
2774               getConstant(MulOp.first),
2775               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2776               SCEV::FlagAnyWrap, Depth + 1));
2777         }
2778       }
2779       if (Ops.empty())
2780         return getZero(Ty);
2781       if (Ops.size() == 1)
2782         return Ops[0];
2783       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2784     }
2785   }
2786 
2787   // If we are adding something to a multiply expression, make sure the
2788   // something is not already an operand of the multiply.  If so, merge it into
2789   // the multiply.
2790   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2791     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2792     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2793       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2794       if (isa<SCEVConstant>(MulOpSCEV))
2795         continue;
2796       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2797         if (MulOpSCEV == Ops[AddOp]) {
2798           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2799           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2800           if (Mul->getNumOperands() != 2) {
2801             // If the multiply has more than two operands, we must get the
2802             // Y*Z term.
2803             SmallVector<const SCEV *, 4> MulOps(
2804                 Mul->operands().take_front(MulOp));
2805             append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2806             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2807           }
2808           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2809           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2810           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2811                                             SCEV::FlagAnyWrap, Depth + 1);
2812           if (Ops.size() == 2) return OuterMul;
2813           if (AddOp < Idx) {
2814             Ops.erase(Ops.begin()+AddOp);
2815             Ops.erase(Ops.begin()+Idx-1);
2816           } else {
2817             Ops.erase(Ops.begin()+Idx);
2818             Ops.erase(Ops.begin()+AddOp-1);
2819           }
2820           Ops.push_back(OuterMul);
2821           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2822         }
2823 
2824       // Check this multiply against other multiplies being added together.
2825       for (unsigned OtherMulIdx = Idx+1;
2826            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2827            ++OtherMulIdx) {
2828         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2829         // If MulOp occurs in OtherMul, we can fold the two multiplies
2830         // together.
2831         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2832              OMulOp != e; ++OMulOp)
2833           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2834             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2835             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2836             if (Mul->getNumOperands() != 2) {
2837               SmallVector<const SCEV *, 4> MulOps(
2838                   Mul->operands().take_front(MulOp));
2839               append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2840               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2841             }
2842             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2843             if (OtherMul->getNumOperands() != 2) {
2844               SmallVector<const SCEV *, 4> MulOps(
2845                   OtherMul->operands().take_front(OMulOp));
2846               append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2847               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2848             }
2849             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2850             const SCEV *InnerMulSum =
2851                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2852             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2853                                               SCEV::FlagAnyWrap, Depth + 1);
2854             if (Ops.size() == 2) return OuterMul;
2855             Ops.erase(Ops.begin()+Idx);
2856             Ops.erase(Ops.begin()+OtherMulIdx-1);
2857             Ops.push_back(OuterMul);
2858             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2859           }
2860       }
2861     }
2862   }
2863 
2864   // If there are any add recurrences in the operands list, see if any other
2865   // added values are loop invariant.  If so, we can fold them into the
2866   // recurrence.
2867   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2868     ++Idx;
2869 
2870   // Scan over all recurrences, trying to fold loop invariants into them.
2871   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2872     // Scan all of the other operands to this add and add them to the vector if
2873     // they are loop invariant w.r.t. the recurrence.
2874     SmallVector<const SCEV *, 8> LIOps;
2875     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2876     const Loop *AddRecLoop = AddRec->getLoop();
2877     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2878       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2879         LIOps.push_back(Ops[i]);
2880         Ops.erase(Ops.begin()+i);
2881         --i; --e;
2882       }
2883 
2884     // If we found some loop invariants, fold them into the recurrence.
2885     if (!LIOps.empty()) {
2886       // Compute nowrap flags for the addition of the loop-invariant ops and
2887       // the addrec. Temporarily push it as an operand for that purpose. These
2888       // flags are valid in the scope of the addrec only.
2889       LIOps.push_back(AddRec);
2890       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2891       LIOps.pop_back();
2892 
2893       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2894       LIOps.push_back(AddRec->getStart());
2895 
2896       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2897 
2898       // It is not in general safe to propagate flags valid on an add within
2899       // the addrec scope to one outside it.  We must prove that the inner
2900       // scope is guaranteed to execute if the outer one does to be able to
2901       // safely propagate.  We know the program is undefined if poison is
2902       // produced on the inner scoped addrec.  We also know that *for this use*
2903       // the outer scoped add can't overflow (because of the flags we just
2904       // computed for the inner scoped add) without the program being undefined.
2905       // Proving that entry to the outer scope neccesitates entry to the inner
2906       // scope, thus proves the program undefined if the flags would be violated
2907       // in the outer scope.
2908       SCEV::NoWrapFlags AddFlags = Flags;
2909       if (AddFlags != SCEV::FlagAnyWrap) {
2910         auto *DefI = getDefiningScopeBound(LIOps);
2911         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2912         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2913           AddFlags = SCEV::FlagAnyWrap;
2914       }
2915       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2916 
2917       // Build the new addrec. Propagate the NUW and NSW flags if both the
2918       // outer add and the inner addrec are guaranteed to have no overflow.
2919       // Always propagate NW.
2920       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2921       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2922 
2923       // If all of the other operands were loop invariant, we are done.
2924       if (Ops.size() == 1) return NewRec;
2925 
2926       // Otherwise, add the folded AddRec by the non-invariant parts.
2927       for (unsigned i = 0;; ++i)
2928         if (Ops[i] == AddRec) {
2929           Ops[i] = NewRec;
2930           break;
2931         }
2932       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2933     }
2934 
2935     // Okay, if there weren't any loop invariants to be folded, check to see if
2936     // there are multiple AddRec's with the same loop induction variable being
2937     // added together.  If so, we can fold them.
2938     for (unsigned OtherIdx = Idx+1;
2939          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2940          ++OtherIdx) {
2941       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2942       // so that the 1st found AddRecExpr is dominated by all others.
2943       assert(DT.dominates(
2944            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2945            AddRec->getLoop()->getHeader()) &&
2946         "AddRecExprs are not sorted in reverse dominance order?");
2947       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2948         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2949         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2950         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2951              ++OtherIdx) {
2952           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2953           if (OtherAddRec->getLoop() == AddRecLoop) {
2954             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2955                  i != e; ++i) {
2956               if (i >= AddRecOps.size()) {
2957                 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2958                 break;
2959               }
2960               SmallVector<const SCEV *, 2> TwoOps = {
2961                   AddRecOps[i], OtherAddRec->getOperand(i)};
2962               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2963             }
2964             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2965           }
2966         }
2967         // Step size has changed, so we cannot guarantee no self-wraparound.
2968         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2969         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2970       }
2971     }
2972 
2973     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2974     // next one.
2975   }
2976 
2977   // Okay, it looks like we really DO need an add expr.  Check to see if we
2978   // already have one, otherwise create a new one.
2979   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2980 }
2981 
2982 const SCEV *
2983 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2984                                     SCEV::NoWrapFlags Flags) {
2985   FoldingSetNodeID ID;
2986   ID.AddInteger(scAddExpr);
2987   for (const SCEV *Op : Ops)
2988     ID.AddPointer(Op);
2989   void *IP = nullptr;
2990   SCEVAddExpr *S =
2991       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2992   if (!S) {
2993     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2994     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2995     S = new (SCEVAllocator)
2996         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2997     UniqueSCEVs.InsertNode(S, IP);
2998     registerUser(S, Ops);
2999   }
3000   S->setNoWrapFlags(Flags);
3001   return S;
3002 }
3003 
3004 const SCEV *
3005 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3006                                        const Loop *L, SCEV::NoWrapFlags Flags) {
3007   FoldingSetNodeID ID;
3008   ID.AddInteger(scAddRecExpr);
3009   for (const SCEV *Op : Ops)
3010     ID.AddPointer(Op);
3011   ID.AddPointer(L);
3012   void *IP = nullptr;
3013   SCEVAddRecExpr *S =
3014       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3015   if (!S) {
3016     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3017     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3018     S = new (SCEVAllocator)
3019         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3020     UniqueSCEVs.InsertNode(S, IP);
3021     LoopUsers[L].push_back(S);
3022     registerUser(S, Ops);
3023   }
3024   setNoWrapFlags(S, Flags);
3025   return S;
3026 }
3027 
3028 const SCEV *
3029 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3030                                     SCEV::NoWrapFlags Flags) {
3031   FoldingSetNodeID ID;
3032   ID.AddInteger(scMulExpr);
3033   for (const SCEV *Op : Ops)
3034     ID.AddPointer(Op);
3035   void *IP = nullptr;
3036   SCEVMulExpr *S =
3037     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3038   if (!S) {
3039     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3040     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3041     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3042                                         O, Ops.size());
3043     UniqueSCEVs.InsertNode(S, IP);
3044     registerUser(S, Ops);
3045   }
3046   S->setNoWrapFlags(Flags);
3047   return S;
3048 }
3049 
3050 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3051   uint64_t k = i*j;
3052   if (j > 1 && k / j != i) Overflow = true;
3053   return k;
3054 }
3055 
3056 /// Compute the result of "n choose k", the binomial coefficient.  If an
3057 /// intermediate computation overflows, Overflow will be set and the return will
3058 /// be garbage. Overflow is not cleared on absence of overflow.
3059 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3060   // We use the multiplicative formula:
3061   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3062   // At each iteration, we take the n-th term of the numeral and divide by the
3063   // (k-n)th term of the denominator.  This division will always produce an
3064   // integral result, and helps reduce the chance of overflow in the
3065   // intermediate computations. However, we can still overflow even when the
3066   // final result would fit.
3067 
3068   if (n == 0 || n == k) return 1;
3069   if (k > n) return 0;
3070 
3071   if (k > n/2)
3072     k = n-k;
3073 
3074   uint64_t r = 1;
3075   for (uint64_t i = 1; i <= k; ++i) {
3076     r = umul_ov(r, n-(i-1), Overflow);
3077     r /= i;
3078   }
3079   return r;
3080 }
3081 
3082 /// Determine if any of the operands in this SCEV are a constant or if
3083 /// any of the add or multiply expressions in this SCEV contain a constant.
3084 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3085   struct FindConstantInAddMulChain {
3086     bool FoundConstant = false;
3087 
3088     bool follow(const SCEV *S) {
3089       FoundConstant |= isa<SCEVConstant>(S);
3090       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3091     }
3092 
3093     bool isDone() const {
3094       return FoundConstant;
3095     }
3096   };
3097 
3098   FindConstantInAddMulChain F;
3099   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3100   ST.visitAll(StartExpr);
3101   return F.FoundConstant;
3102 }
3103 
3104 /// Get a canonical multiply expression, or something simpler if possible.
3105 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3106                                         SCEV::NoWrapFlags OrigFlags,
3107                                         unsigned Depth) {
3108   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3109          "only nuw or nsw allowed");
3110   assert(!Ops.empty() && "Cannot get empty mul!");
3111   if (Ops.size() == 1) return Ops[0];
3112 #ifndef NDEBUG
3113   Type *ETy = Ops[0]->getType();
3114   assert(!ETy->isPointerTy());
3115   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3116     assert(Ops[i]->getType() == ETy &&
3117            "SCEVMulExpr operand types don't match!");
3118 #endif
3119 
3120   // Sort by complexity, this groups all similar expression types together.
3121   GroupByComplexity(Ops, &LI, DT);
3122 
3123   // If there are any constants, fold them together.
3124   unsigned Idx = 0;
3125   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3126     ++Idx;
3127     assert(Idx < Ops.size());
3128     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3129       // We found two constants, fold them together!
3130       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3131       if (Ops.size() == 2) return Ops[0];
3132       Ops.erase(Ops.begin()+1);  // Erase the folded element
3133       LHSC = cast<SCEVConstant>(Ops[0]);
3134     }
3135 
3136     // If we have a multiply of zero, it will always be zero.
3137     if (LHSC->getValue()->isZero())
3138       return LHSC;
3139 
3140     // If we are left with a constant one being multiplied, strip it off.
3141     if (LHSC->getValue()->isOne()) {
3142       Ops.erase(Ops.begin());
3143       --Idx;
3144     }
3145 
3146     if (Ops.size() == 1)
3147       return Ops[0];
3148   }
3149 
3150   // Delay expensive flag strengthening until necessary.
3151   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3152     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3153   };
3154 
3155   // Limit recursion calls depth.
3156   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3157     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3158 
3159   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3160     // Don't strengthen flags if we have no new information.
3161     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3162     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3163       Mul->setNoWrapFlags(ComputeFlags(Ops));
3164     return S;
3165   }
3166 
3167   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3168     if (Ops.size() == 2) {
3169       // C1*(C2+V) -> C1*C2 + C1*V
3170       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3171         // If any of Add's ops are Adds or Muls with a constant, apply this
3172         // transformation as well.
3173         //
3174         // TODO: There are some cases where this transformation is not
3175         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3176         // this transformation should be narrowed down.
3177         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3178           const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3179                                        SCEV::FlagAnyWrap, Depth + 1);
3180           const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3181                                        SCEV::FlagAnyWrap, Depth + 1);
3182           return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3183         }
3184 
3185       if (Ops[0]->isAllOnesValue()) {
3186         // If we have a mul by -1 of an add, try distributing the -1 among the
3187         // add operands.
3188         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3189           SmallVector<const SCEV *, 4> NewOps;
3190           bool AnyFolded = false;
3191           for (const SCEV *AddOp : Add->operands()) {
3192             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3193                                          Depth + 1);
3194             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3195             NewOps.push_back(Mul);
3196           }
3197           if (AnyFolded)
3198             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3199         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3200           // Negation preserves a recurrence's no self-wrap property.
3201           SmallVector<const SCEV *, 4> Operands;
3202           for (const SCEV *AddRecOp : AddRec->operands())
3203             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3204                                           Depth + 1));
3205           // Let M be the minimum representable signed value. AddRec with nsw
3206           // multiplied by -1 can have signed overflow if and only if it takes a
3207           // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3208           // maximum signed value. In all other cases signed overflow is
3209           // impossible.
3210           auto FlagsMask = SCEV::FlagNW;
3211           if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3212             auto MinInt =
3213                 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3214             if (getSignedRangeMin(AddRec) != MinInt)
3215               FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3216           }
3217           return getAddRecExpr(Operands, AddRec->getLoop(),
3218                                AddRec->getNoWrapFlags(FlagsMask));
3219         }
3220       }
3221     }
3222   }
3223 
3224   // Skip over the add expression until we get to a multiply.
3225   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3226     ++Idx;
3227 
3228   // If there are mul operands inline them all into this expression.
3229   if (Idx < Ops.size()) {
3230     bool DeletedMul = false;
3231     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3232       if (Ops.size() > MulOpsInlineThreshold)
3233         break;
3234       // If we have an mul, expand the mul operands onto the end of the
3235       // operands list.
3236       Ops.erase(Ops.begin()+Idx);
3237       append_range(Ops, Mul->operands());
3238       DeletedMul = true;
3239     }
3240 
3241     // If we deleted at least one mul, we added operands to the end of the
3242     // list, and they are not necessarily sorted.  Recurse to resort and
3243     // resimplify any operands we just acquired.
3244     if (DeletedMul)
3245       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3246   }
3247 
3248   // If there are any add recurrences in the operands list, see if any other
3249   // added values are loop invariant.  If so, we can fold them into the
3250   // recurrence.
3251   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3252     ++Idx;
3253 
3254   // Scan over all recurrences, trying to fold loop invariants into them.
3255   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3256     // Scan all of the other operands to this mul and add them to the vector
3257     // if they are loop invariant w.r.t. the recurrence.
3258     SmallVector<const SCEV *, 8> LIOps;
3259     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3260     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3261       if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3262         LIOps.push_back(Ops[i]);
3263         Ops.erase(Ops.begin()+i);
3264         --i; --e;
3265       }
3266 
3267     // If we found some loop invariants, fold them into the recurrence.
3268     if (!LIOps.empty()) {
3269       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3270       SmallVector<const SCEV *, 4> NewOps;
3271       NewOps.reserve(AddRec->getNumOperands());
3272       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3273 
3274       // If both the mul and addrec are nuw, we can preserve nuw.
3275       // If both the mul and addrec are nsw, we can only preserve nsw if either
3276       // a) they are also nuw, or
3277       // b) all multiplications of addrec operands with scale are nsw.
3278       SCEV::NoWrapFlags Flags =
3279           AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3280 
3281       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3282         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3283                                     SCEV::FlagAnyWrap, Depth + 1));
3284 
3285         if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3286           ConstantRange NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3287               Instruction::Mul, getSignedRange(Scale),
3288               OverflowingBinaryOperator::NoSignedWrap);
3289           if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3290             Flags = clearFlags(Flags, SCEV::FlagNSW);
3291         }
3292       }
3293 
3294       const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3295 
3296       // If all of the other operands were loop invariant, we are done.
3297       if (Ops.size() == 1) return NewRec;
3298 
3299       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3300       for (unsigned i = 0;; ++i)
3301         if (Ops[i] == AddRec) {
3302           Ops[i] = NewRec;
3303           break;
3304         }
3305       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3306     }
3307 
3308     // Okay, if there weren't any loop invariants to be folded, check to see
3309     // if there are multiple AddRec's with the same loop induction variable
3310     // being multiplied together.  If so, we can fold them.
3311 
3312     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3313     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3314     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3315     //   ]]],+,...up to x=2n}.
3316     // Note that the arguments to choose() are always integers with values
3317     // known at compile time, never SCEV objects.
3318     //
3319     // The implementation avoids pointless extra computations when the two
3320     // addrec's are of different length (mathematically, it's equivalent to
3321     // an infinite stream of zeros on the right).
3322     bool OpsModified = false;
3323     for (unsigned OtherIdx = Idx+1;
3324          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3325          ++OtherIdx) {
3326       const SCEVAddRecExpr *OtherAddRec =
3327         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3328       if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3329         continue;
3330 
3331       // Limit max number of arguments to avoid creation of unreasonably big
3332       // SCEVAddRecs with very complex operands.
3333       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3334           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3335         continue;
3336 
3337       bool Overflow = false;
3338       Type *Ty = AddRec->getType();
3339       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3340       SmallVector<const SCEV*, 7> AddRecOps;
3341       for (int x = 0, xe = AddRec->getNumOperands() +
3342              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3343         SmallVector <const SCEV *, 7> SumOps;
3344         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3345           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3346           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3347                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3348                z < ze && !Overflow; ++z) {
3349             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3350             uint64_t Coeff;
3351             if (LargerThan64Bits)
3352               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3353             else
3354               Coeff = Coeff1*Coeff2;
3355             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3356             const SCEV *Term1 = AddRec->getOperand(y-z);
3357             const SCEV *Term2 = OtherAddRec->getOperand(z);
3358             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3359                                         SCEV::FlagAnyWrap, Depth + 1));
3360           }
3361         }
3362         if (SumOps.empty())
3363           SumOps.push_back(getZero(Ty));
3364         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3365       }
3366       if (!Overflow) {
3367         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3368                                               SCEV::FlagAnyWrap);
3369         if (Ops.size() == 2) return NewAddRec;
3370         Ops[Idx] = NewAddRec;
3371         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3372         OpsModified = true;
3373         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3374         if (!AddRec)
3375           break;
3376       }
3377     }
3378     if (OpsModified)
3379       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3380 
3381     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3382     // next one.
3383   }
3384 
3385   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3386   // already have one, otherwise create a new one.
3387   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3388 }
3389 
3390 /// Represents an unsigned remainder expression based on unsigned division.
3391 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3392                                          const SCEV *RHS) {
3393   assert(getEffectiveSCEVType(LHS->getType()) ==
3394          getEffectiveSCEVType(RHS->getType()) &&
3395          "SCEVURemExpr operand types don't match!");
3396 
3397   // Short-circuit easy cases
3398   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3399     // If constant is one, the result is trivial
3400     if (RHSC->getValue()->isOne())
3401       return getZero(LHS->getType()); // X urem 1 --> 0
3402 
3403     // If constant is a power of two, fold into a zext(trunc(LHS)).
3404     if (RHSC->getAPInt().isPowerOf2()) {
3405       Type *FullTy = LHS->getType();
3406       Type *TruncTy =
3407           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3408       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3409     }
3410   }
3411 
3412   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3413   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3414   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3415   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3416 }
3417 
3418 /// Get a canonical unsigned division expression, or something simpler if
3419 /// possible.
3420 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3421                                          const SCEV *RHS) {
3422   assert(!LHS->getType()->isPointerTy() &&
3423          "SCEVUDivExpr operand can't be pointer!");
3424   assert(LHS->getType() == RHS->getType() &&
3425          "SCEVUDivExpr operand types don't match!");
3426 
3427   FoldingSetNodeID ID;
3428   ID.AddInteger(scUDivExpr);
3429   ID.AddPointer(LHS);
3430   ID.AddPointer(RHS);
3431   void *IP = nullptr;
3432   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3433     return S;
3434 
3435   // 0 udiv Y == 0
3436   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3437     if (LHSC->getValue()->isZero())
3438       return LHS;
3439 
3440   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3441     if (RHSC->getValue()->isOne())
3442       return LHS;                               // X udiv 1 --> x
3443     // If the denominator is zero, the result of the udiv is undefined. Don't
3444     // try to analyze it, because the resolution chosen here may differ from
3445     // the resolution chosen in other parts of the compiler.
3446     if (!RHSC->getValue()->isZero()) {
3447       // Determine if the division can be folded into the operands of
3448       // its operands.
3449       // TODO: Generalize this to non-constants by using known-bits information.
3450       Type *Ty = LHS->getType();
3451       unsigned LZ = RHSC->getAPInt().countl_zero();
3452       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3453       // For non-power-of-two values, effectively round the value up to the
3454       // nearest power of two.
3455       if (!RHSC->getAPInt().isPowerOf2())
3456         ++MaxShiftAmt;
3457       IntegerType *ExtTy =
3458         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3459       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3460         if (const SCEVConstant *Step =
3461             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3462           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3463           const APInt &StepInt = Step->getAPInt();
3464           const APInt &DivInt = RHSC->getAPInt();
3465           if (!StepInt.urem(DivInt) &&
3466               getZeroExtendExpr(AR, ExtTy) ==
3467               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3468                             getZeroExtendExpr(Step, ExtTy),
3469                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3470             SmallVector<const SCEV *, 4> Operands;
3471             for (const SCEV *Op : AR->operands())
3472               Operands.push_back(getUDivExpr(Op, RHS));
3473             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3474           }
3475           /// Get a canonical UDivExpr for a recurrence.
3476           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3477           // We can currently only fold X%N if X is constant.
3478           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3479           if (StartC && !DivInt.urem(StepInt) &&
3480               getZeroExtendExpr(AR, ExtTy) ==
3481               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3482                             getZeroExtendExpr(Step, ExtTy),
3483                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3484             const APInt &StartInt = StartC->getAPInt();
3485             const APInt &StartRem = StartInt.urem(StepInt);
3486             if (StartRem != 0) {
3487               const SCEV *NewLHS =
3488                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3489                                 AR->getLoop(), SCEV::FlagNW);
3490               if (LHS != NewLHS) {
3491                 LHS = NewLHS;
3492 
3493                 // Reset the ID to include the new LHS, and check if it is
3494                 // already cached.
3495                 ID.clear();
3496                 ID.AddInteger(scUDivExpr);
3497                 ID.AddPointer(LHS);
3498                 ID.AddPointer(RHS);
3499                 IP = nullptr;
3500                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3501                   return S;
3502               }
3503             }
3504           }
3505         }
3506       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3507       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3508         SmallVector<const SCEV *, 4> Operands;
3509         for (const SCEV *Op : M->operands())
3510           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3511         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3512           // Find an operand that's safely divisible.
3513           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3514             const SCEV *Op = M->getOperand(i);
3515             const SCEV *Div = getUDivExpr(Op, RHSC);
3516             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3517               Operands = SmallVector<const SCEV *, 4>(M->operands());
3518               Operands[i] = Div;
3519               return getMulExpr(Operands);
3520             }
3521           }
3522       }
3523 
3524       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3525       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3526         if (auto *DivisorConstant =
3527                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3528           bool Overflow = false;
3529           APInt NewRHS =
3530               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3531           if (Overflow) {
3532             return getConstant(RHSC->getType(), 0, false);
3533           }
3534           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3535         }
3536       }
3537 
3538       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3539       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3540         SmallVector<const SCEV *, 4> Operands;
3541         for (const SCEV *Op : A->operands())
3542           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3543         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3544           Operands.clear();
3545           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3546             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3547             if (isa<SCEVUDivExpr>(Op) ||
3548                 getMulExpr(Op, RHS) != A->getOperand(i))
3549               break;
3550             Operands.push_back(Op);
3551           }
3552           if (Operands.size() == A->getNumOperands())
3553             return getAddExpr(Operands);
3554         }
3555       }
3556 
3557       // Fold if both operands are constant.
3558       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3559         return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3560     }
3561   }
3562 
3563   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3564   // changes). Make sure we get a new one.
3565   IP = nullptr;
3566   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3567   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3568                                              LHS, RHS);
3569   UniqueSCEVs.InsertNode(S, IP);
3570   registerUser(S, {LHS, RHS});
3571   return S;
3572 }
3573 
3574 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3575   APInt A = C1->getAPInt().abs();
3576   APInt B = C2->getAPInt().abs();
3577   uint32_t ABW = A.getBitWidth();
3578   uint32_t BBW = B.getBitWidth();
3579 
3580   if (ABW > BBW)
3581     B = B.zext(ABW);
3582   else if (ABW < BBW)
3583     A = A.zext(BBW);
3584 
3585   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3586 }
3587 
3588 /// Get a canonical unsigned division expression, or something simpler if
3589 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3590 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3591 /// it's not exact because the udiv may be clearing bits.
3592 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3593                                               const SCEV *RHS) {
3594   // TODO: we could try to find factors in all sorts of things, but for now we
3595   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3596   // end of this file for inspiration.
3597 
3598   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3599   if (!Mul || !Mul->hasNoUnsignedWrap())
3600     return getUDivExpr(LHS, RHS);
3601 
3602   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3603     // If the mulexpr multiplies by a constant, then that constant must be the
3604     // first element of the mulexpr.
3605     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3606       if (LHSCst == RHSCst) {
3607         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3608         return getMulExpr(Operands);
3609       }
3610 
3611       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3612       // that there's a factor provided by one of the other terms. We need to
3613       // check.
3614       APInt Factor = gcd(LHSCst, RHSCst);
3615       if (!Factor.isIntN(1)) {
3616         LHSCst =
3617             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3618         RHSCst =
3619             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3620         SmallVector<const SCEV *, 2> Operands;
3621         Operands.push_back(LHSCst);
3622         append_range(Operands, Mul->operands().drop_front());
3623         LHS = getMulExpr(Operands);
3624         RHS = RHSCst;
3625         Mul = dyn_cast<SCEVMulExpr>(LHS);
3626         if (!Mul)
3627           return getUDivExactExpr(LHS, RHS);
3628       }
3629     }
3630   }
3631 
3632   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3633     if (Mul->getOperand(i) == RHS) {
3634       SmallVector<const SCEV *, 2> Operands;
3635       append_range(Operands, Mul->operands().take_front(i));
3636       append_range(Operands, Mul->operands().drop_front(i + 1));
3637       return getMulExpr(Operands);
3638     }
3639   }
3640 
3641   return getUDivExpr(LHS, RHS);
3642 }
3643 
3644 /// Get an add recurrence expression for the specified loop.  Simplify the
3645 /// expression as much as possible.
3646 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3647                                            const Loop *L,
3648                                            SCEV::NoWrapFlags Flags) {
3649   SmallVector<const SCEV *, 4> Operands;
3650   Operands.push_back(Start);
3651   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3652     if (StepChrec->getLoop() == L) {
3653       append_range(Operands, StepChrec->operands());
3654       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3655     }
3656 
3657   Operands.push_back(Step);
3658   return getAddRecExpr(Operands, L, Flags);
3659 }
3660 
3661 /// Get an add recurrence expression for the specified loop.  Simplify the
3662 /// expression as much as possible.
3663 const SCEV *
3664 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3665                                const Loop *L, SCEV::NoWrapFlags Flags) {
3666   if (Operands.size() == 1) return Operands[0];
3667 #ifndef NDEBUG
3668   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3669   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3670     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3671            "SCEVAddRecExpr operand types don't match!");
3672     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3673   }
3674   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3675     assert(isAvailableAtLoopEntry(Operands[i], L) &&
3676            "SCEVAddRecExpr operand is not available at loop entry!");
3677 #endif
3678 
3679   if (Operands.back()->isZero()) {
3680     Operands.pop_back();
3681     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3682   }
3683 
3684   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3685   // use that information to infer NUW and NSW flags. However, computing a
3686   // BE count requires calling getAddRecExpr, so we may not yet have a
3687   // meaningful BE count at this point (and if we don't, we'd be stuck
3688   // with a SCEVCouldNotCompute as the cached BE count).
3689 
3690   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3691 
3692   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3693   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3694     const Loop *NestedLoop = NestedAR->getLoop();
3695     if (L->contains(NestedLoop)
3696             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3697             : (!NestedLoop->contains(L) &&
3698                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3699       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3700       Operands[0] = NestedAR->getStart();
3701       // AddRecs require their operands be loop-invariant with respect to their
3702       // loops. Don't perform this transformation if it would break this
3703       // requirement.
3704       bool AllInvariant = all_of(
3705           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3706 
3707       if (AllInvariant) {
3708         // Create a recurrence for the outer loop with the same step size.
3709         //
3710         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3711         // inner recurrence has the same property.
3712         SCEV::NoWrapFlags OuterFlags =
3713           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3714 
3715         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3716         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3717           return isLoopInvariant(Op, NestedLoop);
3718         });
3719 
3720         if (AllInvariant) {
3721           // Ok, both add recurrences are valid after the transformation.
3722           //
3723           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3724           // the outer recurrence has the same property.
3725           SCEV::NoWrapFlags InnerFlags =
3726             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3727           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3728         }
3729       }
3730       // Reset Operands to its original state.
3731       Operands[0] = NestedAR;
3732     }
3733   }
3734 
3735   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3736   // already have one, otherwise create a new one.
3737   return getOrCreateAddRecExpr(Operands, L, Flags);
3738 }
3739 
3740 const SCEV *
3741 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3742                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3743   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3744   // getSCEV(Base)->getType() has the same address space as Base->getType()
3745   // because SCEV::getType() preserves the address space.
3746   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3747   const bool AssumeInBoundsFlags = [&]() {
3748     if (!GEP->isInBounds())
3749       return false;
3750 
3751     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3752     // but to do that, we have to ensure that said flag is valid in the entire
3753     // defined scope of the SCEV.
3754     auto *GEPI = dyn_cast<Instruction>(GEP);
3755     // TODO: non-instructions have global scope.  We might be able to prove
3756     // some global scope cases
3757     return GEPI && isSCEVExprNeverPoison(GEPI);
3758   }();
3759 
3760   SCEV::NoWrapFlags OffsetWrap =
3761     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3762 
3763   Type *CurTy = GEP->getType();
3764   bool FirstIter = true;
3765   SmallVector<const SCEV *, 4> Offsets;
3766   for (const SCEV *IndexExpr : IndexExprs) {
3767     // Compute the (potentially symbolic) offset in bytes for this index.
3768     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3769       // For a struct, add the member offset.
3770       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3771       unsigned FieldNo = Index->getZExtValue();
3772       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3773       Offsets.push_back(FieldOffset);
3774 
3775       // Update CurTy to the type of the field at Index.
3776       CurTy = STy->getTypeAtIndex(Index);
3777     } else {
3778       // Update CurTy to its element type.
3779       if (FirstIter) {
3780         assert(isa<PointerType>(CurTy) &&
3781                "The first index of a GEP indexes a pointer");
3782         CurTy = GEP->getSourceElementType();
3783         FirstIter = false;
3784       } else {
3785         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3786       }
3787       // For an array, add the element offset, explicitly scaled.
3788       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3789       // Getelementptr indices are signed.
3790       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3791 
3792       // Multiply the index by the element size to compute the element offset.
3793       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3794       Offsets.push_back(LocalOffset);
3795     }
3796   }
3797 
3798   // Handle degenerate case of GEP without offsets.
3799   if (Offsets.empty())
3800     return BaseExpr;
3801 
3802   // Add the offsets together, assuming nsw if inbounds.
3803   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3804   // Add the base address and the offset. We cannot use the nsw flag, as the
3805   // base address is unsigned. However, if we know that the offset is
3806   // non-negative, we can use nuw.
3807   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3808                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3809   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3810   assert(BaseExpr->getType() == GEPExpr->getType() &&
3811          "GEP should not change type mid-flight.");
3812   return GEPExpr;
3813 }
3814 
3815 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3816                                                ArrayRef<const SCEV *> Ops) {
3817   FoldingSetNodeID ID;
3818   ID.AddInteger(SCEVType);
3819   for (const SCEV *Op : Ops)
3820     ID.AddPointer(Op);
3821   void *IP = nullptr;
3822   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3823 }
3824 
3825 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3826   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3827   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3828 }
3829 
3830 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3831                                            SmallVectorImpl<const SCEV *> &Ops) {
3832   assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3833   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3834   if (Ops.size() == 1) return Ops[0];
3835 #ifndef NDEBUG
3836   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3837   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3838     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3839            "Operand types don't match!");
3840     assert(Ops[0]->getType()->isPointerTy() ==
3841                Ops[i]->getType()->isPointerTy() &&
3842            "min/max should be consistently pointerish");
3843   }
3844 #endif
3845 
3846   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3847   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3848 
3849   // Sort by complexity, this groups all similar expression types together.
3850   GroupByComplexity(Ops, &LI, DT);
3851 
3852   // Check if we have created the same expression before.
3853   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3854     return S;
3855   }
3856 
3857   // If there are any constants, fold them together.
3858   unsigned Idx = 0;
3859   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3860     ++Idx;
3861     assert(Idx < Ops.size());
3862     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3863       switch (Kind) {
3864       case scSMaxExpr:
3865         return APIntOps::smax(LHS, RHS);
3866       case scSMinExpr:
3867         return APIntOps::smin(LHS, RHS);
3868       case scUMaxExpr:
3869         return APIntOps::umax(LHS, RHS);
3870       case scUMinExpr:
3871         return APIntOps::umin(LHS, RHS);
3872       default:
3873         llvm_unreachable("Unknown SCEV min/max opcode");
3874       }
3875     };
3876 
3877     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3878       // We found two constants, fold them together!
3879       ConstantInt *Fold = ConstantInt::get(
3880           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3881       Ops[0] = getConstant(Fold);
3882       Ops.erase(Ops.begin()+1);  // Erase the folded element
3883       if (Ops.size() == 1) return Ops[0];
3884       LHSC = cast<SCEVConstant>(Ops[0]);
3885     }
3886 
3887     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3888     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3889 
3890     if (IsMax ? IsMinV : IsMaxV) {
3891       // If we are left with a constant minimum(/maximum)-int, strip it off.
3892       Ops.erase(Ops.begin());
3893       --Idx;
3894     } else if (IsMax ? IsMaxV : IsMinV) {
3895       // If we have a max(/min) with a constant maximum(/minimum)-int,
3896       // it will always be the extremum.
3897       return LHSC;
3898     }
3899 
3900     if (Ops.size() == 1) return Ops[0];
3901   }
3902 
3903   // Find the first operation of the same kind
3904   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3905     ++Idx;
3906 
3907   // Check to see if one of the operands is of the same kind. If so, expand its
3908   // operands onto our operand list, and recurse to simplify.
3909   if (Idx < Ops.size()) {
3910     bool DeletedAny = false;
3911     while (Ops[Idx]->getSCEVType() == Kind) {
3912       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3913       Ops.erase(Ops.begin()+Idx);
3914       append_range(Ops, SMME->operands());
3915       DeletedAny = true;
3916     }
3917 
3918     if (DeletedAny)
3919       return getMinMaxExpr(Kind, Ops);
3920   }
3921 
3922   // Okay, check to see if the same value occurs in the operand list twice.  If
3923   // so, delete one.  Since we sorted the list, these values are required to
3924   // be adjacent.
3925   llvm::CmpInst::Predicate GEPred =
3926       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3927   llvm::CmpInst::Predicate LEPred =
3928       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3929   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3930   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3931   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3932     if (Ops[i] == Ops[i + 1] ||
3933         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3934       //  X op Y op Y  -->  X op Y
3935       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3936       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3937       --i;
3938       --e;
3939     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3940                                                Ops[i + 1])) {
3941       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3942       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3943       --i;
3944       --e;
3945     }
3946   }
3947 
3948   if (Ops.size() == 1) return Ops[0];
3949 
3950   assert(!Ops.empty() && "Reduced smax down to nothing!");
3951 
3952   // Okay, it looks like we really DO need an expr.  Check to see if we
3953   // already have one, otherwise create a new one.
3954   FoldingSetNodeID ID;
3955   ID.AddInteger(Kind);
3956   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3957     ID.AddPointer(Ops[i]);
3958   void *IP = nullptr;
3959   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3960   if (ExistingSCEV)
3961     return ExistingSCEV;
3962   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3963   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3964   SCEV *S = new (SCEVAllocator)
3965       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3966 
3967   UniqueSCEVs.InsertNode(S, IP);
3968   registerUser(S, Ops);
3969   return S;
3970 }
3971 
3972 namespace {
3973 
3974 class SCEVSequentialMinMaxDeduplicatingVisitor final
3975     : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3976                          std::optional<const SCEV *>> {
3977   using RetVal = std::optional<const SCEV *>;
3978   using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3979 
3980   ScalarEvolution &SE;
3981   const SCEVTypes RootKind; // Must be a sequential min/max expression.
3982   const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3983   SmallPtrSet<const SCEV *, 16> SeenOps;
3984 
3985   bool canRecurseInto(SCEVTypes Kind) const {
3986     // We can only recurse into the SCEV expression of the same effective type
3987     // as the type of our root SCEV expression.
3988     return RootKind == Kind || NonSequentialRootKind == Kind;
3989   };
3990 
3991   RetVal visitAnyMinMaxExpr(const SCEV *S) {
3992     assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3993            "Only for min/max expressions.");
3994     SCEVTypes Kind = S->getSCEVType();
3995 
3996     if (!canRecurseInto(Kind))
3997       return S;
3998 
3999     auto *NAry = cast<SCEVNAryExpr>(S);
4000     SmallVector<const SCEV *> NewOps;
4001     bool Changed = visit(Kind, NAry->operands(), NewOps);
4002 
4003     if (!Changed)
4004       return S;
4005     if (NewOps.empty())
4006       return std::nullopt;
4007 
4008     return isa<SCEVSequentialMinMaxExpr>(S)
4009                ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4010                : SE.getMinMaxExpr(Kind, NewOps);
4011   }
4012 
4013   RetVal visit(const SCEV *S) {
4014     // Has the whole operand been seen already?
4015     if (!SeenOps.insert(S).second)
4016       return std::nullopt;
4017     return Base::visit(S);
4018   }
4019 
4020 public:
4021   SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4022                                            SCEVTypes RootKind)
4023       : SE(SE), RootKind(RootKind),
4024         NonSequentialRootKind(
4025             SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4026                 RootKind)) {}
4027 
4028   bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4029                          SmallVectorImpl<const SCEV *> &NewOps) {
4030     bool Changed = false;
4031     SmallVector<const SCEV *> Ops;
4032     Ops.reserve(OrigOps.size());
4033 
4034     for (const SCEV *Op : OrigOps) {
4035       RetVal NewOp = visit(Op);
4036       if (NewOp != Op)
4037         Changed = true;
4038       if (NewOp)
4039         Ops.emplace_back(*NewOp);
4040     }
4041 
4042     if (Changed)
4043       NewOps = std::move(Ops);
4044     return Changed;
4045   }
4046 
4047   RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4048 
4049   RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4050 
4051   RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4052 
4053   RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4054 
4055   RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4056 
4057   RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4058 
4059   RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4060 
4061   RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4062 
4063   RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4064 
4065   RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4066 
4067   RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4068     return visitAnyMinMaxExpr(Expr);
4069   }
4070 
4071   RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4072     return visitAnyMinMaxExpr(Expr);
4073   }
4074 
4075   RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4076     return visitAnyMinMaxExpr(Expr);
4077   }
4078 
4079   RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4080     return visitAnyMinMaxExpr(Expr);
4081   }
4082 
4083   RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4084     return visitAnyMinMaxExpr(Expr);
4085   }
4086 
4087   RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4088 
4089   RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4090 };
4091 
4092 } // namespace
4093 
4094 static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
4095   switch (Kind) {
4096   case scConstant:
4097   case scVScale:
4098   case scTruncate:
4099   case scZeroExtend:
4100   case scSignExtend:
4101   case scPtrToInt:
4102   case scAddExpr:
4103   case scMulExpr:
4104   case scUDivExpr:
4105   case scAddRecExpr:
4106   case scUMaxExpr:
4107   case scSMaxExpr:
4108   case scUMinExpr:
4109   case scSMinExpr:
4110   case scUnknown:
4111     // If any operand is poison, the whole expression is poison.
4112     return true;
4113   case scSequentialUMinExpr:
4114     // FIXME: if the *first* operand is poison, the whole expression is poison.
4115     return false; // Pessimistically, say that it does not propagate poison.
4116   case scCouldNotCompute:
4117     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4118   }
4119   llvm_unreachable("Unknown SCEV kind!");
4120 }
4121 
4122 namespace {
4123 // The only way poison may be introduced in a SCEV expression is from a
4124 // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4125 // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4126 // introduce poison -- they encode guaranteed, non-speculated knowledge.
4127 //
4128 // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4129 // with the notable exception of umin_seq, where only poison from the first
4130 // operand is (unconditionally) propagated.
4131 struct SCEVPoisonCollector {
4132   bool LookThroughMaybePoisonBlocking;
4133   SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4134   SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4135       : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4136 
4137   bool follow(const SCEV *S) {
4138     if (!LookThroughMaybePoisonBlocking &&
4139         !scevUnconditionallyPropagatesPoisonFromOperands(S->getSCEVType()))
4140       return false;
4141 
4142     if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4143       if (!isGuaranteedNotToBePoison(SU->getValue()))
4144         MaybePoison.insert(SU);
4145     }
4146     return true;
4147   }
4148   bool isDone() const { return false; }
4149 };
4150 } // namespace
4151 
4152 /// Return true if V is poison given that AssumedPoison is already poison.
4153 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4154   // First collect all SCEVs that might result in AssumedPoison to be poison.
4155   // We need to look through potentially poison-blocking operations here,
4156   // because we want to find all SCEVs that *might* result in poison, not only
4157   // those that are *required* to.
4158   SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4159   visitAll(AssumedPoison, PC1);
4160 
4161   // AssumedPoison is never poison. As the assumption is false, the implication
4162   // is true. Don't bother walking the other SCEV in this case.
4163   if (PC1.MaybePoison.empty())
4164     return true;
4165 
4166   // Collect all SCEVs in S that, if poison, *will* result in S being poison
4167   // as well. We cannot look through potentially poison-blocking operations
4168   // here, as their arguments only *may* make the result poison.
4169   SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4170   visitAll(S, PC2);
4171 
4172   // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4173   // it will also make S poison by being part of PC2.MaybePoison.
4174   return all_of(PC1.MaybePoison, [&](const SCEVUnknown *S) {
4175     return PC2.MaybePoison.contains(S);
4176   });
4177 }
4178 
4179 void ScalarEvolution::getPoisonGeneratingValues(
4180     SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4181   SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4182   visitAll(S, PC);
4183   for (const SCEVUnknown *SU : PC.MaybePoison)
4184     Result.insert(SU->getValue());
4185 }
4186 
4187 const SCEV *
4188 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4189                                          SmallVectorImpl<const SCEV *> &Ops) {
4190   assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4191          "Not a SCEVSequentialMinMaxExpr!");
4192   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4193   if (Ops.size() == 1)
4194     return Ops[0];
4195 #ifndef NDEBUG
4196   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4197   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4198     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4199            "Operand types don't match!");
4200     assert(Ops[0]->getType()->isPointerTy() ==
4201                Ops[i]->getType()->isPointerTy() &&
4202            "min/max should be consistently pointerish");
4203   }
4204 #endif
4205 
4206   // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4207   // so we can *NOT* do any kind of sorting of the expressions!
4208 
4209   // Check if we have created the same expression before.
4210   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4211     return S;
4212 
4213   // FIXME: there are *some* simplifications that we can do here.
4214 
4215   // Keep only the first instance of an operand.
4216   {
4217     SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4218     bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4219     if (Changed)
4220       return getSequentialMinMaxExpr(Kind, Ops);
4221   }
4222 
4223   // Check to see if one of the operands is of the same kind. If so, expand its
4224   // operands onto our operand list, and recurse to simplify.
4225   {
4226     unsigned Idx = 0;
4227     bool DeletedAny = false;
4228     while (Idx < Ops.size()) {
4229       if (Ops[Idx]->getSCEVType() != Kind) {
4230         ++Idx;
4231         continue;
4232       }
4233       const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4234       Ops.erase(Ops.begin() + Idx);
4235       Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4236                  SMME->operands().end());
4237       DeletedAny = true;
4238     }
4239 
4240     if (DeletedAny)
4241       return getSequentialMinMaxExpr(Kind, Ops);
4242   }
4243 
4244   const SCEV *SaturationPoint;
4245   ICmpInst::Predicate Pred;
4246   switch (Kind) {
4247   case scSequentialUMinExpr:
4248     SaturationPoint = getZero(Ops[0]->getType());
4249     Pred = ICmpInst::ICMP_ULE;
4250     break;
4251   default:
4252     llvm_unreachable("Not a sequential min/max type.");
4253   }
4254 
4255   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4256     // We can replace %x umin_seq %y with %x umin %y if either:
4257     //  * %y being poison implies %x is also poison.
4258     //  * %x cannot be the saturating value (e.g. zero for umin).
4259     if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4260         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4261                                         SaturationPoint)) {
4262       SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4263       Ops[i - 1] = getMinMaxExpr(
4264           SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4265           SeqOps);
4266       Ops.erase(Ops.begin() + i);
4267       return getSequentialMinMaxExpr(Kind, Ops);
4268     }
4269     // Fold %x umin_seq %y to %x if %x ule %y.
4270     // TODO: We might be able to prove the predicate for a later operand.
4271     if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4272       Ops.erase(Ops.begin() + i);
4273       return getSequentialMinMaxExpr(Kind, Ops);
4274     }
4275   }
4276 
4277   // Okay, it looks like we really DO need an expr.  Check to see if we
4278   // already have one, otherwise create a new one.
4279   FoldingSetNodeID ID;
4280   ID.AddInteger(Kind);
4281   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4282     ID.AddPointer(Ops[i]);
4283   void *IP = nullptr;
4284   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4285   if (ExistingSCEV)
4286     return ExistingSCEV;
4287 
4288   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4289   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4290   SCEV *S = new (SCEVAllocator)
4291       SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4292 
4293   UniqueSCEVs.InsertNode(S, IP);
4294   registerUser(S, Ops);
4295   return S;
4296 }
4297 
4298 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4299   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4300   return getSMaxExpr(Ops);
4301 }
4302 
4303 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4304   return getMinMaxExpr(scSMaxExpr, Ops);
4305 }
4306 
4307 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4308   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4309   return getUMaxExpr(Ops);
4310 }
4311 
4312 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4313   return getMinMaxExpr(scUMaxExpr, Ops);
4314 }
4315 
4316 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4317                                          const SCEV *RHS) {
4318   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4319   return getSMinExpr(Ops);
4320 }
4321 
4322 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4323   return getMinMaxExpr(scSMinExpr, Ops);
4324 }
4325 
4326 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4327                                          bool Sequential) {
4328   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4329   return getUMinExpr(Ops, Sequential);
4330 }
4331 
4332 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4333                                          bool Sequential) {
4334   return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4335                     : getMinMaxExpr(scUMinExpr, Ops);
4336 }
4337 
4338 const SCEV *
4339 ScalarEvolution::getSizeOfExpr(Type *IntTy, TypeSize Size) {
4340   const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4341   if (Size.isScalable())
4342     Res = getMulExpr(Res, getVScale(IntTy));
4343   return Res;
4344 }
4345 
4346 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4347   return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4348 }
4349 
4350 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4351   return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4352 }
4353 
4354 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4355                                              StructType *STy,
4356                                              unsigned FieldNo) {
4357   // We can bypass creating a target-independent constant expression and then
4358   // folding it back into a ConstantInt. This is just a compile-time
4359   // optimization.
4360   const StructLayout *SL = getDataLayout().getStructLayout(STy);
4361   assert(!SL->getSizeInBits().isScalable() &&
4362          "Cannot get offset for structure containing scalable vector types");
4363   return getConstant(IntTy, SL->getElementOffset(FieldNo));
4364 }
4365 
4366 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4367   // Don't attempt to do anything other than create a SCEVUnknown object
4368   // here.  createSCEV only calls getUnknown after checking for all other
4369   // interesting possibilities, and any other code that calls getUnknown
4370   // is doing so in order to hide a value from SCEV canonicalization.
4371 
4372   FoldingSetNodeID ID;
4373   ID.AddInteger(scUnknown);
4374   ID.AddPointer(V);
4375   void *IP = nullptr;
4376   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4377     assert(cast<SCEVUnknown>(S)->getValue() == V &&
4378            "Stale SCEVUnknown in uniquing map!");
4379     return S;
4380   }
4381   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4382                                             FirstUnknown);
4383   FirstUnknown = cast<SCEVUnknown>(S);
4384   UniqueSCEVs.InsertNode(S, IP);
4385   return S;
4386 }
4387 
4388 //===----------------------------------------------------------------------===//
4389 //            Basic SCEV Analysis and PHI Idiom Recognition Code
4390 //
4391 
4392 /// Test if values of the given type are analyzable within the SCEV
4393 /// framework. This primarily includes integer types, and it can optionally
4394 /// include pointer types if the ScalarEvolution class has access to
4395 /// target-specific information.
4396 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4397   // Integers and pointers are always SCEVable.
4398   return Ty->isIntOrPtrTy();
4399 }
4400 
4401 /// Return the size in bits of the specified type, for which isSCEVable must
4402 /// return true.
4403 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4404   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4405   if (Ty->isPointerTy())
4406     return getDataLayout().getIndexTypeSizeInBits(Ty);
4407   return getDataLayout().getTypeSizeInBits(Ty);
4408 }
4409 
4410 /// Return a type with the same bitwidth as the given type and which represents
4411 /// how SCEV will treat the given type, for which isSCEVable must return
4412 /// true. For pointer types, this is the pointer index sized integer type.
4413 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4414   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4415 
4416   if (Ty->isIntegerTy())
4417     return Ty;
4418 
4419   // The only other support type is pointer.
4420   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4421   return getDataLayout().getIndexType(Ty);
4422 }
4423 
4424 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4425   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4426 }
4427 
4428 bool ScalarEvolution::instructionCouldExistWithOperands(const SCEV *A,
4429                                                         const SCEV *B) {
4430   /// For a valid use point to exist, the defining scope of one operand
4431   /// must dominate the other.
4432   bool PreciseA, PreciseB;
4433   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4434   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4435   if (!PreciseA || !PreciseB)
4436     // Can't tell.
4437     return false;
4438   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4439     DT.dominates(ScopeB, ScopeA);
4440 }
4441 
4442 const SCEV *ScalarEvolution::getCouldNotCompute() {
4443   return CouldNotCompute.get();
4444 }
4445 
4446 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4447   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4448     auto *SU = dyn_cast<SCEVUnknown>(S);
4449     return SU && SU->getValue() == nullptr;
4450   });
4451 
4452   return !ContainsNulls;
4453 }
4454 
4455 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4456   HasRecMapType::iterator I = HasRecMap.find(S);
4457   if (I != HasRecMap.end())
4458     return I->second;
4459 
4460   bool FoundAddRec =
4461       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4462   HasRecMap.insert({S, FoundAddRec});
4463   return FoundAddRec;
4464 }
4465 
4466 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4467 /// by the value and offset from any ValueOffsetPair in the set.
4468 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4469   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4470   if (SI == ExprValueMap.end())
4471     return std::nullopt;
4472   return SI->second.getArrayRef();
4473 }
4474 
4475 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4476 /// cannot be used separately. eraseValueFromMap should be used to remove
4477 /// V from ValueExprMap and ExprValueMap at the same time.
4478 void ScalarEvolution::eraseValueFromMap(Value *V) {
4479   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4480   if (I != ValueExprMap.end()) {
4481     auto EVIt = ExprValueMap.find(I->second);
4482     bool Removed = EVIt->second.remove(V);
4483     (void) Removed;
4484     assert(Removed && "Value not in ExprValueMap?");
4485     ValueExprMap.erase(I);
4486   }
4487 }
4488 
4489 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4490   // A recursive query may have already computed the SCEV. It should be
4491   // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4492   // inferred nowrap flags.
4493   auto It = ValueExprMap.find_as(V);
4494   if (It == ValueExprMap.end()) {
4495     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4496     ExprValueMap[S].insert(V);
4497   }
4498 }
4499 
4500 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4501 /// create a new one.
4502 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4503   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4504 
4505   if (const SCEV *S = getExistingSCEV(V))
4506     return S;
4507   return createSCEVIter(V);
4508 }
4509 
4510 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4511   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4512 
4513   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4514   if (I != ValueExprMap.end()) {
4515     const SCEV *S = I->second;
4516     assert(checkValidity(S) &&
4517            "existing SCEV has not been properly invalidated");
4518     return S;
4519   }
4520   return nullptr;
4521 }
4522 
4523 /// Return a SCEV corresponding to -V = -1*V
4524 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4525                                              SCEV::NoWrapFlags Flags) {
4526   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4527     return getConstant(
4528                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4529 
4530   Type *Ty = V->getType();
4531   Ty = getEffectiveSCEVType(Ty);
4532   return getMulExpr(V, getMinusOne(Ty), Flags);
4533 }
4534 
4535 /// If Expr computes ~A, return A else return nullptr
4536 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4537   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4538   if (!Add || Add->getNumOperands() != 2 ||
4539       !Add->getOperand(0)->isAllOnesValue())
4540     return nullptr;
4541 
4542   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4543   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4544       !AddRHS->getOperand(0)->isAllOnesValue())
4545     return nullptr;
4546 
4547   return AddRHS->getOperand(1);
4548 }
4549 
4550 /// Return a SCEV corresponding to ~V = -1-V
4551 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4552   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4553 
4554   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4555     return getConstant(
4556                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4557 
4558   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4559   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4560     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4561       SmallVector<const SCEV *, 2> MatchedOperands;
4562       for (const SCEV *Operand : MME->operands()) {
4563         const SCEV *Matched = MatchNotExpr(Operand);
4564         if (!Matched)
4565           return (const SCEV *)nullptr;
4566         MatchedOperands.push_back(Matched);
4567       }
4568       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4569                            MatchedOperands);
4570     };
4571     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4572       return Replaced;
4573   }
4574 
4575   Type *Ty = V->getType();
4576   Ty = getEffectiveSCEVType(Ty);
4577   return getMinusSCEV(getMinusOne(Ty), V);
4578 }
4579 
4580 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4581   assert(P->getType()->isPointerTy());
4582 
4583   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4584     // The base of an AddRec is the first operand.
4585     SmallVector<const SCEV *> Ops{AddRec->operands()};
4586     Ops[0] = removePointerBase(Ops[0]);
4587     // Don't try to transfer nowrap flags for now. We could in some cases
4588     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4589     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4590   }
4591   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4592     // The base of an Add is the pointer operand.
4593     SmallVector<const SCEV *> Ops{Add->operands()};
4594     const SCEV **PtrOp = nullptr;
4595     for (const SCEV *&AddOp : Ops) {
4596       if (AddOp->getType()->isPointerTy()) {
4597         assert(!PtrOp && "Cannot have multiple pointer ops");
4598         PtrOp = &AddOp;
4599       }
4600     }
4601     *PtrOp = removePointerBase(*PtrOp);
4602     // Don't try to transfer nowrap flags for now. We could in some cases
4603     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4604     return getAddExpr(Ops);
4605   }
4606   // Any other expression must be a pointer base.
4607   return getZero(P->getType());
4608 }
4609 
4610 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4611                                           SCEV::NoWrapFlags Flags,
4612                                           unsigned Depth) {
4613   // Fast path: X - X --> 0.
4614   if (LHS == RHS)
4615     return getZero(LHS->getType());
4616 
4617   // If we subtract two pointers with different pointer bases, bail.
4618   // Eventually, we're going to add an assertion to getMulExpr that we
4619   // can't multiply by a pointer.
4620   if (RHS->getType()->isPointerTy()) {
4621     if (!LHS->getType()->isPointerTy() ||
4622         getPointerBase(LHS) != getPointerBase(RHS))
4623       return getCouldNotCompute();
4624     LHS = removePointerBase(LHS);
4625     RHS = removePointerBase(RHS);
4626   }
4627 
4628   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4629   // makes it so that we cannot make much use of NUW.
4630   auto AddFlags = SCEV::FlagAnyWrap;
4631   const bool RHSIsNotMinSigned =
4632       !getSignedRangeMin(RHS).isMinSignedValue();
4633   if (hasFlags(Flags, SCEV::FlagNSW)) {
4634     // Let M be the minimum representable signed value. Then (-1)*RHS
4635     // signed-wraps if and only if RHS is M. That can happen even for
4636     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4637     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4638     // (-1)*RHS, we need to prove that RHS != M.
4639     //
4640     // If LHS is non-negative and we know that LHS - RHS does not
4641     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4642     // either by proving that RHS > M or that LHS >= 0.
4643     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4644       AddFlags = SCEV::FlagNSW;
4645     }
4646   }
4647 
4648   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4649   // RHS is NSW and LHS >= 0.
4650   //
4651   // The difficulty here is that the NSW flag may have been proven
4652   // relative to a loop that is to be found in a recurrence in LHS and
4653   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4654   // larger scope than intended.
4655   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4656 
4657   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4658 }
4659 
4660 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4661                                                      unsigned Depth) {
4662   Type *SrcTy = V->getType();
4663   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4664          "Cannot truncate or zero extend with non-integer arguments!");
4665   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4666     return V;  // No conversion
4667   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4668     return getTruncateExpr(V, Ty, Depth);
4669   return getZeroExtendExpr(V, Ty, Depth);
4670 }
4671 
4672 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4673                                                      unsigned Depth) {
4674   Type *SrcTy = V->getType();
4675   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4676          "Cannot truncate or zero extend with non-integer arguments!");
4677   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4678     return V;  // No conversion
4679   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4680     return getTruncateExpr(V, Ty, Depth);
4681   return getSignExtendExpr(V, Ty, Depth);
4682 }
4683 
4684 const SCEV *
4685 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4686   Type *SrcTy = V->getType();
4687   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4688          "Cannot noop or zero extend with non-integer arguments!");
4689   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4690          "getNoopOrZeroExtend cannot truncate!");
4691   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4692     return V;  // No conversion
4693   return getZeroExtendExpr(V, Ty);
4694 }
4695 
4696 const SCEV *
4697 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4698   Type *SrcTy = V->getType();
4699   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4700          "Cannot noop or sign extend with non-integer arguments!");
4701   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4702          "getNoopOrSignExtend cannot truncate!");
4703   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4704     return V;  // No conversion
4705   return getSignExtendExpr(V, Ty);
4706 }
4707 
4708 const SCEV *
4709 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4710   Type *SrcTy = V->getType();
4711   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4712          "Cannot noop or any extend with non-integer arguments!");
4713   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4714          "getNoopOrAnyExtend cannot truncate!");
4715   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4716     return V;  // No conversion
4717   return getAnyExtendExpr(V, Ty);
4718 }
4719 
4720 const SCEV *
4721 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4722   Type *SrcTy = V->getType();
4723   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4724          "Cannot truncate or noop with non-integer arguments!");
4725   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4726          "getTruncateOrNoop cannot extend!");
4727   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4728     return V;  // No conversion
4729   return getTruncateExpr(V, Ty);
4730 }
4731 
4732 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4733                                                         const SCEV *RHS) {
4734   const SCEV *PromotedLHS = LHS;
4735   const SCEV *PromotedRHS = RHS;
4736 
4737   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4738     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4739   else
4740     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4741 
4742   return getUMaxExpr(PromotedLHS, PromotedRHS);
4743 }
4744 
4745 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4746                                                         const SCEV *RHS,
4747                                                         bool Sequential) {
4748   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4749   return getUMinFromMismatchedTypes(Ops, Sequential);
4750 }
4751 
4752 const SCEV *
4753 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4754                                             bool Sequential) {
4755   assert(!Ops.empty() && "At least one operand must be!");
4756   // Trivial case.
4757   if (Ops.size() == 1)
4758     return Ops[0];
4759 
4760   // Find the max type first.
4761   Type *MaxType = nullptr;
4762   for (const auto *S : Ops)
4763     if (MaxType)
4764       MaxType = getWiderType(MaxType, S->getType());
4765     else
4766       MaxType = S->getType();
4767   assert(MaxType && "Failed to find maximum type!");
4768 
4769   // Extend all ops to max type.
4770   SmallVector<const SCEV *, 2> PromotedOps;
4771   for (const auto *S : Ops)
4772     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4773 
4774   // Generate umin.
4775   return getUMinExpr(PromotedOps, Sequential);
4776 }
4777 
4778 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4779   // A pointer operand may evaluate to a nonpointer expression, such as null.
4780   if (!V->getType()->isPointerTy())
4781     return V;
4782 
4783   while (true) {
4784     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4785       V = AddRec->getStart();
4786     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4787       const SCEV *PtrOp = nullptr;
4788       for (const SCEV *AddOp : Add->operands()) {
4789         if (AddOp->getType()->isPointerTy()) {
4790           assert(!PtrOp && "Cannot have multiple pointer ops");
4791           PtrOp = AddOp;
4792         }
4793       }
4794       assert(PtrOp && "Must have pointer op");
4795       V = PtrOp;
4796     } else // Not something we can look further into.
4797       return V;
4798   }
4799 }
4800 
4801 /// Push users of the given Instruction onto the given Worklist.
4802 static void PushDefUseChildren(Instruction *I,
4803                                SmallVectorImpl<Instruction *> &Worklist,
4804                                SmallPtrSetImpl<Instruction *> &Visited) {
4805   // Push the def-use children onto the Worklist stack.
4806   for (User *U : I->users()) {
4807     auto *UserInsn = cast<Instruction>(U);
4808     if (Visited.insert(UserInsn).second)
4809       Worklist.push_back(UserInsn);
4810   }
4811 }
4812 
4813 namespace {
4814 
4815 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4816 /// expression in case its Loop is L. If it is not L then
4817 /// if IgnoreOtherLoops is true then use AddRec itself
4818 /// otherwise rewrite cannot be done.
4819 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4820 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4821 public:
4822   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4823                              bool IgnoreOtherLoops = true) {
4824     SCEVInitRewriter Rewriter(L, SE);
4825     const SCEV *Result = Rewriter.visit(S);
4826     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4827       return SE.getCouldNotCompute();
4828     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4829                ? SE.getCouldNotCompute()
4830                : Result;
4831   }
4832 
4833   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4834     if (!SE.isLoopInvariant(Expr, L))
4835       SeenLoopVariantSCEVUnknown = true;
4836     return Expr;
4837   }
4838 
4839   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4840     // Only re-write AddRecExprs for this loop.
4841     if (Expr->getLoop() == L)
4842       return Expr->getStart();
4843     SeenOtherLoops = true;
4844     return Expr;
4845   }
4846 
4847   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4848 
4849   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4850 
4851 private:
4852   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4853       : SCEVRewriteVisitor(SE), L(L) {}
4854 
4855   const Loop *L;
4856   bool SeenLoopVariantSCEVUnknown = false;
4857   bool SeenOtherLoops = false;
4858 };
4859 
4860 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4861 /// increment expression in case its Loop is L. If it is not L then
4862 /// use AddRec itself.
4863 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4864 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4865 public:
4866   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4867     SCEVPostIncRewriter Rewriter(L, SE);
4868     const SCEV *Result = Rewriter.visit(S);
4869     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4870         ? SE.getCouldNotCompute()
4871         : Result;
4872   }
4873 
4874   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4875     if (!SE.isLoopInvariant(Expr, L))
4876       SeenLoopVariantSCEVUnknown = true;
4877     return Expr;
4878   }
4879 
4880   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4881     // Only re-write AddRecExprs for this loop.
4882     if (Expr->getLoop() == L)
4883       return Expr->getPostIncExpr(SE);
4884     SeenOtherLoops = true;
4885     return Expr;
4886   }
4887 
4888   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4889 
4890   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4891 
4892 private:
4893   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4894       : SCEVRewriteVisitor(SE), L(L) {}
4895 
4896   const Loop *L;
4897   bool SeenLoopVariantSCEVUnknown = false;
4898   bool SeenOtherLoops = false;
4899 };
4900 
4901 /// This class evaluates the compare condition by matching it against the
4902 /// condition of loop latch. If there is a match we assume a true value
4903 /// for the condition while building SCEV nodes.
4904 class SCEVBackedgeConditionFolder
4905     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4906 public:
4907   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4908                              ScalarEvolution &SE) {
4909     bool IsPosBECond = false;
4910     Value *BECond = nullptr;
4911     if (BasicBlock *Latch = L->getLoopLatch()) {
4912       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4913       if (BI && BI->isConditional()) {
4914         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4915                "Both outgoing branches should not target same header!");
4916         BECond = BI->getCondition();
4917         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4918       } else {
4919         return S;
4920       }
4921     }
4922     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4923     return Rewriter.visit(S);
4924   }
4925 
4926   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4927     const SCEV *Result = Expr;
4928     bool InvariantF = SE.isLoopInvariant(Expr, L);
4929 
4930     if (!InvariantF) {
4931       Instruction *I = cast<Instruction>(Expr->getValue());
4932       switch (I->getOpcode()) {
4933       case Instruction::Select: {
4934         SelectInst *SI = cast<SelectInst>(I);
4935         std::optional<const SCEV *> Res =
4936             compareWithBackedgeCondition(SI->getCondition());
4937         if (Res) {
4938           bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4939           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4940         }
4941         break;
4942       }
4943       default: {
4944         std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4945         if (Res)
4946           Result = *Res;
4947         break;
4948       }
4949       }
4950     }
4951     return Result;
4952   }
4953 
4954 private:
4955   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4956                                        bool IsPosBECond, ScalarEvolution &SE)
4957       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4958         IsPositiveBECond(IsPosBECond) {}
4959 
4960   std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4961 
4962   const Loop *L;
4963   /// Loop back condition.
4964   Value *BackedgeCond = nullptr;
4965   /// Set to true if loop back is on positive branch condition.
4966   bool IsPositiveBECond;
4967 };
4968 
4969 std::optional<const SCEV *>
4970 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4971 
4972   // If value matches the backedge condition for loop latch,
4973   // then return a constant evolution node based on loopback
4974   // branch taken.
4975   if (BackedgeCond == IC)
4976     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4977                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4978   return std::nullopt;
4979 }
4980 
4981 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4982 public:
4983   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4984                              ScalarEvolution &SE) {
4985     SCEVShiftRewriter Rewriter(L, SE);
4986     const SCEV *Result = Rewriter.visit(S);
4987     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4988   }
4989 
4990   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4991     // Only allow AddRecExprs for this loop.
4992     if (!SE.isLoopInvariant(Expr, L))
4993       Valid = false;
4994     return Expr;
4995   }
4996 
4997   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4998     if (Expr->getLoop() == L && Expr->isAffine())
4999       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5000     Valid = false;
5001     return Expr;
5002   }
5003 
5004   bool isValid() { return Valid; }
5005 
5006 private:
5007   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5008       : SCEVRewriteVisitor(SE), L(L) {}
5009 
5010   const Loop *L;
5011   bool Valid = true;
5012 };
5013 
5014 } // end anonymous namespace
5015 
5016 SCEV::NoWrapFlags
5017 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5018   if (!AR->isAffine())
5019     return SCEV::FlagAnyWrap;
5020 
5021   using OBO = OverflowingBinaryOperator;
5022 
5023   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
5024 
5025   if (!AR->hasNoSelfWrap()) {
5026     const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5027     if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5028       ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5029       const APInt &BECountAP = BECountMax->getAPInt();
5030       unsigned NoOverflowBitWidth =
5031         BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5032       if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5033         Result = ScalarEvolution::setFlags(Result, SCEV::FlagNW);
5034     }
5035   }
5036 
5037   if (!AR->hasNoSignedWrap()) {
5038     ConstantRange AddRecRange = getSignedRange(AR);
5039     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
5040 
5041     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5042         Instruction::Add, IncRange, OBO::NoSignedWrap);
5043     if (NSWRegion.contains(AddRecRange))
5044       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
5045   }
5046 
5047   if (!AR->hasNoUnsignedWrap()) {
5048     ConstantRange AddRecRange = getUnsignedRange(AR);
5049     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
5050 
5051     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5052         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
5053     if (NUWRegion.contains(AddRecRange))
5054       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
5055   }
5056 
5057   return Result;
5058 }
5059 
5060 SCEV::NoWrapFlags
5061 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5062   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5063 
5064   if (AR->hasNoSignedWrap())
5065     return Result;
5066 
5067   if (!AR->isAffine())
5068     return Result;
5069 
5070   // This function can be expensive, only try to prove NSW once per AddRec.
5071   if (!SignedWrapViaInductionTried.insert(AR).second)
5072     return Result;
5073 
5074   const SCEV *Step = AR->getStepRecurrence(*this);
5075   const Loop *L = AR->getLoop();
5076 
5077   // Check whether the backedge-taken count is SCEVCouldNotCompute.
5078   // Note that this serves two purposes: It filters out loops that are
5079   // simply not analyzable, and it covers the case where this code is
5080   // being called from within backedge-taken count analysis, such that
5081   // attempting to ask for the backedge-taken count would likely result
5082   // in infinite recursion. In the later case, the analysis code will
5083   // cope with a conservative value, and it will take care to purge
5084   // that value once it has finished.
5085   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5086 
5087   // Normally, in the cases we can prove no-overflow via a
5088   // backedge guarding condition, we can also compute a backedge
5089   // taken count for the loop.  The exceptions are assumptions and
5090   // guards present in the loop -- SCEV is not great at exploiting
5091   // these to compute max backedge taken counts, but can still use
5092   // these to prove lack of overflow.  Use this fact to avoid
5093   // doing extra work that may not pay off.
5094 
5095   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5096       AC.assumptions().empty())
5097     return Result;
5098 
5099   // If the backedge is guarded by a comparison with the pre-inc  value the
5100   // addrec is safe. Also, if the entry is guarded by a comparison with the
5101   // start value and the backedge is guarded by a comparison with the post-inc
5102   // value, the addrec is safe.
5103   ICmpInst::Predicate Pred;
5104   const SCEV *OverflowLimit =
5105     getSignedOverflowLimitForStep(Step, &Pred, this);
5106   if (OverflowLimit &&
5107       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5108        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5109     Result = setFlags(Result, SCEV::FlagNSW);
5110   }
5111   return Result;
5112 }
5113 SCEV::NoWrapFlags
5114 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5115   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5116 
5117   if (AR->hasNoUnsignedWrap())
5118     return Result;
5119 
5120   if (!AR->isAffine())
5121     return Result;
5122 
5123   // This function can be expensive, only try to prove NUW once per AddRec.
5124   if (!UnsignedWrapViaInductionTried.insert(AR).second)
5125     return Result;
5126 
5127   const SCEV *Step = AR->getStepRecurrence(*this);
5128   unsigned BitWidth = getTypeSizeInBits(AR->getType());
5129   const Loop *L = AR->getLoop();
5130 
5131   // Check whether the backedge-taken count is SCEVCouldNotCompute.
5132   // Note that this serves two purposes: It filters out loops that are
5133   // simply not analyzable, and it covers the case where this code is
5134   // being called from within backedge-taken count analysis, such that
5135   // attempting to ask for the backedge-taken count would likely result
5136   // in infinite recursion. In the later case, the analysis code will
5137   // cope with a conservative value, and it will take care to purge
5138   // that value once it has finished.
5139   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5140 
5141   // Normally, in the cases we can prove no-overflow via a
5142   // backedge guarding condition, we can also compute a backedge
5143   // taken count for the loop.  The exceptions are assumptions and
5144   // guards present in the loop -- SCEV is not great at exploiting
5145   // these to compute max backedge taken counts, but can still use
5146   // these to prove lack of overflow.  Use this fact to avoid
5147   // doing extra work that may not pay off.
5148 
5149   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5150       AC.assumptions().empty())
5151     return Result;
5152 
5153   // If the backedge is guarded by a comparison with the pre-inc  value the
5154   // addrec is safe. Also, if the entry is guarded by a comparison with the
5155   // start value and the backedge is guarded by a comparison with the post-inc
5156   // value, the addrec is safe.
5157   if (isKnownPositive(Step)) {
5158     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5159                                 getUnsignedRangeMax(Step));
5160     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5161         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5162       Result = setFlags(Result, SCEV::FlagNUW);
5163     }
5164   }
5165 
5166   return Result;
5167 }
5168 
5169 namespace {
5170 
5171 /// Represents an abstract binary operation.  This may exist as a
5172 /// normal instruction or constant expression, or may have been
5173 /// derived from an expression tree.
5174 struct BinaryOp {
5175   unsigned Opcode;
5176   Value *LHS;
5177   Value *RHS;
5178   bool IsNSW = false;
5179   bool IsNUW = false;
5180 
5181   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5182   /// constant expression.
5183   Operator *Op = nullptr;
5184 
5185   explicit BinaryOp(Operator *Op)
5186       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5187         Op(Op) {
5188     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5189       IsNSW = OBO->hasNoSignedWrap();
5190       IsNUW = OBO->hasNoUnsignedWrap();
5191     }
5192   }
5193 
5194   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5195                     bool IsNUW = false)
5196       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5197 };
5198 
5199 } // end anonymous namespace
5200 
5201 /// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5202 static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5203                                              AssumptionCache &AC,
5204                                              const DominatorTree &DT,
5205                                              const Instruction *CxtI) {
5206   auto *Op = dyn_cast<Operator>(V);
5207   if (!Op)
5208     return std::nullopt;
5209 
5210   // Implementation detail: all the cleverness here should happen without
5211   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5212   // SCEV expressions when possible, and we should not break that.
5213 
5214   switch (Op->getOpcode()) {
5215   case Instruction::Add:
5216   case Instruction::Sub:
5217   case Instruction::Mul:
5218   case Instruction::UDiv:
5219   case Instruction::URem:
5220   case Instruction::And:
5221   case Instruction::AShr:
5222   case Instruction::Shl:
5223     return BinaryOp(Op);
5224 
5225   case Instruction::Or: {
5226     // Convert or disjoint into add nuw nsw.
5227     if (cast<PossiblyDisjointInst>(Op)->isDisjoint())
5228       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5229                       /*IsNSW=*/true, /*IsNUW=*/true);
5230     return BinaryOp(Op);
5231   }
5232 
5233   case Instruction::Xor:
5234     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5235       // If the RHS of the xor is a signmask, then this is just an add.
5236       // Instcombine turns add of signmask into xor as a strength reduction step.
5237       if (RHSC->getValue().isSignMask())
5238         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5239     // Binary `xor` is a bit-wise `add`.
5240     if (V->getType()->isIntegerTy(1))
5241       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5242     return BinaryOp(Op);
5243 
5244   case Instruction::LShr:
5245     // Turn logical shift right of a constant into a unsigned divide.
5246     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5247       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5248 
5249       // If the shift count is not less than the bitwidth, the result of
5250       // the shift is undefined. Don't try to analyze it, because the
5251       // resolution chosen here may differ from the resolution chosen in
5252       // other parts of the compiler.
5253       if (SA->getValue().ult(BitWidth)) {
5254         Constant *X =
5255             ConstantInt::get(SA->getContext(),
5256                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5257         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5258       }
5259     }
5260     return BinaryOp(Op);
5261 
5262   case Instruction::ExtractValue: {
5263     auto *EVI = cast<ExtractValueInst>(Op);
5264     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5265       break;
5266 
5267     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5268     if (!WO)
5269       break;
5270 
5271     Instruction::BinaryOps BinOp = WO->getBinaryOp();
5272     bool Signed = WO->isSigned();
5273     // TODO: Should add nuw/nsw flags for mul as well.
5274     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5275       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5276 
5277     // Now that we know that all uses of the arithmetic-result component of
5278     // CI are guarded by the overflow check, we can go ahead and pretend
5279     // that the arithmetic is non-overflowing.
5280     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5281                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5282   }
5283 
5284   default:
5285     break;
5286   }
5287 
5288   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5289   // semantics as a Sub, return a binary sub expression.
5290   if (auto *II = dyn_cast<IntrinsicInst>(V))
5291     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5292       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5293 
5294   return std::nullopt;
5295 }
5296 
5297 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5298 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5299 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5300 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5301 /// follows one of the following patterns:
5302 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5303 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5304 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5305 /// we return the type of the truncation operation, and indicate whether the
5306 /// truncated type should be treated as signed/unsigned by setting
5307 /// \p Signed to true/false, respectively.
5308 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5309                                bool &Signed, ScalarEvolution &SE) {
5310   // The case where Op == SymbolicPHI (that is, with no type conversions on
5311   // the way) is handled by the regular add recurrence creating logic and
5312   // would have already been triggered in createAddRecForPHI. Reaching it here
5313   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5314   // because one of the other operands of the SCEVAddExpr updating this PHI is
5315   // not invariant).
5316   //
5317   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5318   // this case predicates that allow us to prove that Op == SymbolicPHI will
5319   // be added.
5320   if (Op == SymbolicPHI)
5321     return nullptr;
5322 
5323   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5324   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5325   if (SourceBits != NewBits)
5326     return nullptr;
5327 
5328   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5329   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5330   if (!SExt && !ZExt)
5331     return nullptr;
5332   const SCEVTruncateExpr *Trunc =
5333       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5334            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5335   if (!Trunc)
5336     return nullptr;
5337   const SCEV *X = Trunc->getOperand();
5338   if (X != SymbolicPHI)
5339     return nullptr;
5340   Signed = SExt != nullptr;
5341   return Trunc->getType();
5342 }
5343 
5344 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5345   if (!PN->getType()->isIntegerTy())
5346     return nullptr;
5347   const Loop *L = LI.getLoopFor(PN->getParent());
5348   if (!L || L->getHeader() != PN->getParent())
5349     return nullptr;
5350   return L;
5351 }
5352 
5353 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5354 // computation that updates the phi follows the following pattern:
5355 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5356 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5357 // If so, try to see if it can be rewritten as an AddRecExpr under some
5358 // Predicates. If successful, return them as a pair. Also cache the results
5359 // of the analysis.
5360 //
5361 // Example usage scenario:
5362 //    Say the Rewriter is called for the following SCEV:
5363 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5364 //    where:
5365 //         %X = phi i64 (%Start, %BEValue)
5366 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5367 //    and call this function with %SymbolicPHI = %X.
5368 //
5369 //    The analysis will find that the value coming around the backedge has
5370 //    the following SCEV:
5371 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5372 //    Upon concluding that this matches the desired pattern, the function
5373 //    will return the pair {NewAddRec, SmallPredsVec} where:
5374 //         NewAddRec = {%Start,+,%Step}
5375 //         SmallPredsVec = {P1, P2, P3} as follows:
5376 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5377 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5378 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5379 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5380 //    under the predicates {P1,P2,P3}.
5381 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5382 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5383 //
5384 // TODO's:
5385 //
5386 // 1) Extend the Induction descriptor to also support inductions that involve
5387 //    casts: When needed (namely, when we are called in the context of the
5388 //    vectorizer induction analysis), a Set of cast instructions will be
5389 //    populated by this method, and provided back to isInductionPHI. This is
5390 //    needed to allow the vectorizer to properly record them to be ignored by
5391 //    the cost model and to avoid vectorizing them (otherwise these casts,
5392 //    which are redundant under the runtime overflow checks, will be
5393 //    vectorized, which can be costly).
5394 //
5395 // 2) Support additional induction/PHISCEV patterns: We also want to support
5396 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5397 //    after the induction update operation (the induction increment):
5398 //
5399 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5400 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5401 //
5402 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5403 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5404 //
5405 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5406 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5407 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5408   SmallVector<const SCEVPredicate *, 3> Predicates;
5409 
5410   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5411   // return an AddRec expression under some predicate.
5412 
5413   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5414   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5415   assert(L && "Expecting an integer loop header phi");
5416 
5417   // The loop may have multiple entrances or multiple exits; we can analyze
5418   // this phi as an addrec if it has a unique entry value and a unique
5419   // backedge value.
5420   Value *BEValueV = nullptr, *StartValueV = nullptr;
5421   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5422     Value *V = PN->getIncomingValue(i);
5423     if (L->contains(PN->getIncomingBlock(i))) {
5424       if (!BEValueV) {
5425         BEValueV = V;
5426       } else if (BEValueV != V) {
5427         BEValueV = nullptr;
5428         break;
5429       }
5430     } else if (!StartValueV) {
5431       StartValueV = V;
5432     } else if (StartValueV != V) {
5433       StartValueV = nullptr;
5434       break;
5435     }
5436   }
5437   if (!BEValueV || !StartValueV)
5438     return std::nullopt;
5439 
5440   const SCEV *BEValue = getSCEV(BEValueV);
5441 
5442   // If the value coming around the backedge is an add with the symbolic
5443   // value we just inserted, possibly with casts that we can ignore under
5444   // an appropriate runtime guard, then we found a simple induction variable!
5445   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5446   if (!Add)
5447     return std::nullopt;
5448 
5449   // If there is a single occurrence of the symbolic value, possibly
5450   // casted, replace it with a recurrence.
5451   unsigned FoundIndex = Add->getNumOperands();
5452   Type *TruncTy = nullptr;
5453   bool Signed;
5454   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5455     if ((TruncTy =
5456              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5457       if (FoundIndex == e) {
5458         FoundIndex = i;
5459         break;
5460       }
5461 
5462   if (FoundIndex == Add->getNumOperands())
5463     return std::nullopt;
5464 
5465   // Create an add with everything but the specified operand.
5466   SmallVector<const SCEV *, 8> Ops;
5467   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5468     if (i != FoundIndex)
5469       Ops.push_back(Add->getOperand(i));
5470   const SCEV *Accum = getAddExpr(Ops);
5471 
5472   // The runtime checks will not be valid if the step amount is
5473   // varying inside the loop.
5474   if (!isLoopInvariant(Accum, L))
5475     return std::nullopt;
5476 
5477   // *** Part2: Create the predicates
5478 
5479   // Analysis was successful: we have a phi-with-cast pattern for which we
5480   // can return an AddRec expression under the following predicates:
5481   //
5482   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5483   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5484   // P2: An Equal predicate that guarantees that
5485   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5486   // P3: An Equal predicate that guarantees that
5487   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5488   //
5489   // As we next prove, the above predicates guarantee that:
5490   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5491   //
5492   //
5493   // More formally, we want to prove that:
5494   //     Expr(i+1) = Start + (i+1) * Accum
5495   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5496   //
5497   // Given that:
5498   // 1) Expr(0) = Start
5499   // 2) Expr(1) = Start + Accum
5500   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5501   // 3) Induction hypothesis (step i):
5502   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5503   //
5504   // Proof:
5505   //  Expr(i+1) =
5506   //   = Start + (i+1)*Accum
5507   //   = (Start + i*Accum) + Accum
5508   //   = Expr(i) + Accum
5509   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5510   //                                                             :: from step i
5511   //
5512   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5513   //
5514   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5515   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5516   //     + Accum                                                     :: from P3
5517   //
5518   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5519   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5520   //
5521   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5522   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5523   //
5524   // By induction, the same applies to all iterations 1<=i<n:
5525   //
5526 
5527   // Create a truncated addrec for which we will add a no overflow check (P1).
5528   const SCEV *StartVal = getSCEV(StartValueV);
5529   const SCEV *PHISCEV =
5530       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5531                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5532 
5533   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5534   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5535   // will be constant.
5536   //
5537   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5538   // add P1.
5539   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5540     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5541         Signed ? SCEVWrapPredicate::IncrementNSSW
5542                : SCEVWrapPredicate::IncrementNUSW;
5543     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5544     Predicates.push_back(AddRecPred);
5545   }
5546 
5547   // Create the Equal Predicates P2,P3:
5548 
5549   // It is possible that the predicates P2 and/or P3 are computable at
5550   // compile time due to StartVal and/or Accum being constants.
5551   // If either one is, then we can check that now and escape if either P2
5552   // or P3 is false.
5553 
5554   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5555   // for each of StartVal and Accum
5556   auto getExtendedExpr = [&](const SCEV *Expr,
5557                              bool CreateSignExtend) -> const SCEV * {
5558     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5559     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5560     const SCEV *ExtendedExpr =
5561         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5562                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5563     return ExtendedExpr;
5564   };
5565 
5566   // Given:
5567   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5568   //               = getExtendedExpr(Expr)
5569   // Determine whether the predicate P: Expr == ExtendedExpr
5570   // is known to be false at compile time
5571   auto PredIsKnownFalse = [&](const SCEV *Expr,
5572                               const SCEV *ExtendedExpr) -> bool {
5573     return Expr != ExtendedExpr &&
5574            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5575   };
5576 
5577   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5578   if (PredIsKnownFalse(StartVal, StartExtended)) {
5579     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5580     return std::nullopt;
5581   }
5582 
5583   // The Step is always Signed (because the overflow checks are either
5584   // NSSW or NUSW)
5585   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5586   if (PredIsKnownFalse(Accum, AccumExtended)) {
5587     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5588     return std::nullopt;
5589   }
5590 
5591   auto AppendPredicate = [&](const SCEV *Expr,
5592                              const SCEV *ExtendedExpr) -> void {
5593     if (Expr != ExtendedExpr &&
5594         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5595       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5596       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5597       Predicates.push_back(Pred);
5598     }
5599   };
5600 
5601   AppendPredicate(StartVal, StartExtended);
5602   AppendPredicate(Accum, AccumExtended);
5603 
5604   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5605   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5606   // into NewAR if it will also add the runtime overflow checks specified in
5607   // Predicates.
5608   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5609 
5610   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5611       std::make_pair(NewAR, Predicates);
5612   // Remember the result of the analysis for this SCEV at this locayyytion.
5613   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5614   return PredRewrite;
5615 }
5616 
5617 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5618 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5619   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5620   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5621   if (!L)
5622     return std::nullopt;
5623 
5624   // Check to see if we already analyzed this PHI.
5625   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5626   if (I != PredicatedSCEVRewrites.end()) {
5627     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5628         I->second;
5629     // Analysis was done before and failed to create an AddRec:
5630     if (Rewrite.first == SymbolicPHI)
5631       return std::nullopt;
5632     // Analysis was done before and succeeded to create an AddRec under
5633     // a predicate:
5634     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5635     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5636     return Rewrite;
5637   }
5638 
5639   std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5640     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5641 
5642   // Record in the cache that the analysis failed
5643   if (!Rewrite) {
5644     SmallVector<const SCEVPredicate *, 3> Predicates;
5645     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5646     return std::nullopt;
5647   }
5648 
5649   return Rewrite;
5650 }
5651 
5652 // FIXME: This utility is currently required because the Rewriter currently
5653 // does not rewrite this expression:
5654 // {0, +, (sext ix (trunc iy to ix) to iy)}
5655 // into {0, +, %step},
5656 // even when the following Equal predicate exists:
5657 // "%step == (sext ix (trunc iy to ix) to iy)".
5658 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5659     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5660   if (AR1 == AR2)
5661     return true;
5662 
5663   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5664     if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5665         !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5666       return false;
5667     return true;
5668   };
5669 
5670   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5671       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5672     return false;
5673   return true;
5674 }
5675 
5676 /// A helper function for createAddRecFromPHI to handle simple cases.
5677 ///
5678 /// This function tries to find an AddRec expression for the simplest (yet most
5679 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5680 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5681 /// technique for finding the AddRec expression.
5682 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5683                                                       Value *BEValueV,
5684                                                       Value *StartValueV) {
5685   const Loop *L = LI.getLoopFor(PN->getParent());
5686   assert(L && L->getHeader() == PN->getParent());
5687   assert(BEValueV && StartValueV);
5688 
5689   auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5690   if (!BO)
5691     return nullptr;
5692 
5693   if (BO->Opcode != Instruction::Add)
5694     return nullptr;
5695 
5696   const SCEV *Accum = nullptr;
5697   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5698     Accum = getSCEV(BO->RHS);
5699   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5700     Accum = getSCEV(BO->LHS);
5701 
5702   if (!Accum)
5703     return nullptr;
5704 
5705   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5706   if (BO->IsNUW)
5707     Flags = setFlags(Flags, SCEV::FlagNUW);
5708   if (BO->IsNSW)
5709     Flags = setFlags(Flags, SCEV::FlagNSW);
5710 
5711   const SCEV *StartVal = getSCEV(StartValueV);
5712   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5713   insertValueToMap(PN, PHISCEV);
5714 
5715   if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5716     setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5717                    (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5718                                        proveNoWrapViaConstantRanges(AR)));
5719   }
5720 
5721   // We can add Flags to the post-inc expression only if we
5722   // know that it is *undefined behavior* for BEValueV to
5723   // overflow.
5724   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5725     assert(isLoopInvariant(Accum, L) &&
5726            "Accum is defined outside L, but is not invariant?");
5727     if (isAddRecNeverPoison(BEInst, L))
5728       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5729   }
5730 
5731   return PHISCEV;
5732 }
5733 
5734 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5735   const Loop *L = LI.getLoopFor(PN->getParent());
5736   if (!L || L->getHeader() != PN->getParent())
5737     return nullptr;
5738 
5739   // The loop may have multiple entrances or multiple exits; we can analyze
5740   // this phi as an addrec if it has a unique entry value and a unique
5741   // backedge value.
5742   Value *BEValueV = nullptr, *StartValueV = nullptr;
5743   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5744     Value *V = PN->getIncomingValue(i);
5745     if (L->contains(PN->getIncomingBlock(i))) {
5746       if (!BEValueV) {
5747         BEValueV = V;
5748       } else if (BEValueV != V) {
5749         BEValueV = nullptr;
5750         break;
5751       }
5752     } else if (!StartValueV) {
5753       StartValueV = V;
5754     } else if (StartValueV != V) {
5755       StartValueV = nullptr;
5756       break;
5757     }
5758   }
5759   if (!BEValueV || !StartValueV)
5760     return nullptr;
5761 
5762   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5763          "PHI node already processed?");
5764 
5765   // First, try to find AddRec expression without creating a fictituos symbolic
5766   // value for PN.
5767   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5768     return S;
5769 
5770   // Handle PHI node value symbolically.
5771   const SCEV *SymbolicName = getUnknown(PN);
5772   insertValueToMap(PN, SymbolicName);
5773 
5774   // Using this symbolic name for the PHI, analyze the value coming around
5775   // the back-edge.
5776   const SCEV *BEValue = getSCEV(BEValueV);
5777 
5778   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5779   // has a special value for the first iteration of the loop.
5780 
5781   // If the value coming around the backedge is an add with the symbolic
5782   // value we just inserted, then we found a simple induction variable!
5783   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5784     // If there is a single occurrence of the symbolic value, replace it
5785     // with a recurrence.
5786     unsigned FoundIndex = Add->getNumOperands();
5787     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5788       if (Add->getOperand(i) == SymbolicName)
5789         if (FoundIndex == e) {
5790           FoundIndex = i;
5791           break;
5792         }
5793 
5794     if (FoundIndex != Add->getNumOperands()) {
5795       // Create an add with everything but the specified operand.
5796       SmallVector<const SCEV *, 8> Ops;
5797       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5798         if (i != FoundIndex)
5799           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5800                                                              L, *this));
5801       const SCEV *Accum = getAddExpr(Ops);
5802 
5803       // This is not a valid addrec if the step amount is varying each
5804       // loop iteration, but is not itself an addrec in this loop.
5805       if (isLoopInvariant(Accum, L) ||
5806           (isa<SCEVAddRecExpr>(Accum) &&
5807            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5808         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5809 
5810         if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5811           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5812             if (BO->IsNUW)
5813               Flags = setFlags(Flags, SCEV::FlagNUW);
5814             if (BO->IsNSW)
5815               Flags = setFlags(Flags, SCEV::FlagNSW);
5816           }
5817         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5818           // If the increment is an inbounds GEP, then we know the address
5819           // space cannot be wrapped around. We cannot make any guarantee
5820           // about signed or unsigned overflow because pointers are
5821           // unsigned but we may have a negative index from the base
5822           // pointer. We can guarantee that no unsigned wrap occurs if the
5823           // indices form a positive value.
5824           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5825             Flags = setFlags(Flags, SCEV::FlagNW);
5826             if (isKnownPositive(Accum))
5827               Flags = setFlags(Flags, SCEV::FlagNUW);
5828           }
5829 
5830           // We cannot transfer nuw and nsw flags from subtraction
5831           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5832           // for instance.
5833         }
5834 
5835         const SCEV *StartVal = getSCEV(StartValueV);
5836         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5837 
5838         // Okay, for the entire analysis of this edge we assumed the PHI
5839         // to be symbolic.  We now need to go back and purge all of the
5840         // entries for the scalars that use the symbolic expression.
5841         forgetMemoizedResults(SymbolicName);
5842         insertValueToMap(PN, PHISCEV);
5843 
5844         if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5845           setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5846                          (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5847                                              proveNoWrapViaConstantRanges(AR)));
5848         }
5849 
5850         // We can add Flags to the post-inc expression only if we
5851         // know that it is *undefined behavior* for BEValueV to
5852         // overflow.
5853         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5854           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5855             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5856 
5857         return PHISCEV;
5858       }
5859     }
5860   } else {
5861     // Otherwise, this could be a loop like this:
5862     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5863     // In this case, j = {1,+,1}  and BEValue is j.
5864     // Because the other in-value of i (0) fits the evolution of BEValue
5865     // i really is an addrec evolution.
5866     //
5867     // We can generalize this saying that i is the shifted value of BEValue
5868     // by one iteration:
5869     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5870     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5871     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5872     if (Shifted != getCouldNotCompute() &&
5873         Start != getCouldNotCompute()) {
5874       const SCEV *StartVal = getSCEV(StartValueV);
5875       if (Start == StartVal) {
5876         // Okay, for the entire analysis of this edge we assumed the PHI
5877         // to be symbolic.  We now need to go back and purge all of the
5878         // entries for the scalars that use the symbolic expression.
5879         forgetMemoizedResults(SymbolicName);
5880         insertValueToMap(PN, Shifted);
5881         return Shifted;
5882       }
5883     }
5884   }
5885 
5886   // Remove the temporary PHI node SCEV that has been inserted while intending
5887   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5888   // as it will prevent later (possibly simpler) SCEV expressions to be added
5889   // to the ValueExprMap.
5890   eraseValueFromMap(PN);
5891 
5892   return nullptr;
5893 }
5894 
5895 // Try to match a control flow sequence that branches out at BI and merges back
5896 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5897 // match.
5898 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5899                           Value *&C, Value *&LHS, Value *&RHS) {
5900   C = BI->getCondition();
5901 
5902   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5903   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5904 
5905   if (!LeftEdge.isSingleEdge())
5906     return false;
5907 
5908   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5909 
5910   Use &LeftUse = Merge->getOperandUse(0);
5911   Use &RightUse = Merge->getOperandUse(1);
5912 
5913   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5914     LHS = LeftUse;
5915     RHS = RightUse;
5916     return true;
5917   }
5918 
5919   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5920     LHS = RightUse;
5921     RHS = LeftUse;
5922     return true;
5923   }
5924 
5925   return false;
5926 }
5927 
5928 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5929   auto IsReachable =
5930       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5931   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5932     // Try to match
5933     //
5934     //  br %cond, label %left, label %right
5935     // left:
5936     //  br label %merge
5937     // right:
5938     //  br label %merge
5939     // merge:
5940     //  V = phi [ %x, %left ], [ %y, %right ]
5941     //
5942     // as "select %cond, %x, %y"
5943 
5944     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5945     assert(IDom && "At least the entry block should dominate PN");
5946 
5947     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5948     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5949 
5950     if (BI && BI->isConditional() &&
5951         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5952         properlyDominates(getSCEV(LHS), PN->getParent()) &&
5953         properlyDominates(getSCEV(RHS), PN->getParent()))
5954       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5955   }
5956 
5957   return nullptr;
5958 }
5959 
5960 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5961   if (const SCEV *S = createAddRecFromPHI(PN))
5962     return S;
5963 
5964   if (Value *V = simplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5965     return getSCEV(V);
5966 
5967   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5968     return S;
5969 
5970   // If it's not a loop phi, we can't handle it yet.
5971   return getUnknown(PN);
5972 }
5973 
5974 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5975                             SCEVTypes RootKind) {
5976   struct FindClosure {
5977     const SCEV *OperandToFind;
5978     const SCEVTypes RootKind; // Must be a sequential min/max expression.
5979     const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5980 
5981     bool Found = false;
5982 
5983     bool canRecurseInto(SCEVTypes Kind) const {
5984       // We can only recurse into the SCEV expression of the same effective type
5985       // as the type of our root SCEV expression, and into zero-extensions.
5986       return RootKind == Kind || NonSequentialRootKind == Kind ||
5987              scZeroExtend == Kind;
5988     };
5989 
5990     FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5991         : OperandToFind(OperandToFind), RootKind(RootKind),
5992           NonSequentialRootKind(
5993               SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5994                   RootKind)) {}
5995 
5996     bool follow(const SCEV *S) {
5997       Found = S == OperandToFind;
5998 
5999       return !isDone() && canRecurseInto(S->getSCEVType());
6000     }
6001 
6002     bool isDone() const { return Found; }
6003   };
6004 
6005   FindClosure FC(OperandToFind, RootKind);
6006   visitAll(Root, FC);
6007   return FC.Found;
6008 }
6009 
6010 std::optional<const SCEV *>
6011 ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6012                                                               ICmpInst *Cond,
6013                                                               Value *TrueVal,
6014                                                               Value *FalseVal) {
6015   // Try to match some simple smax or umax patterns.
6016   auto *ICI = Cond;
6017 
6018   Value *LHS = ICI->getOperand(0);
6019   Value *RHS = ICI->getOperand(1);
6020 
6021   switch (ICI->getPredicate()) {
6022   case ICmpInst::ICMP_SLT:
6023   case ICmpInst::ICMP_SLE:
6024   case ICmpInst::ICMP_ULT:
6025   case ICmpInst::ICMP_ULE:
6026     std::swap(LHS, RHS);
6027     [[fallthrough]];
6028   case ICmpInst::ICMP_SGT:
6029   case ICmpInst::ICMP_SGE:
6030   case ICmpInst::ICMP_UGT:
6031   case ICmpInst::ICMP_UGE:
6032     // a > b ? a+x : b+x  ->  max(a, b)+x
6033     // a > b ? b+x : a+x  ->  min(a, b)+x
6034     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty)) {
6035       bool Signed = ICI->isSigned();
6036       const SCEV *LA = getSCEV(TrueVal);
6037       const SCEV *RA = getSCEV(FalseVal);
6038       const SCEV *LS = getSCEV(LHS);
6039       const SCEV *RS = getSCEV(RHS);
6040       if (LA->getType()->isPointerTy()) {
6041         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6042         // Need to make sure we can't produce weird expressions involving
6043         // negated pointers.
6044         if (LA == LS && RA == RS)
6045           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6046         if (LA == RS && RA == LS)
6047           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6048       }
6049       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6050         if (Op->getType()->isPointerTy()) {
6051           Op = getLosslessPtrToIntExpr(Op);
6052           if (isa<SCEVCouldNotCompute>(Op))
6053             return Op;
6054         }
6055         if (Signed)
6056           Op = getNoopOrSignExtend(Op, Ty);
6057         else
6058           Op = getNoopOrZeroExtend(Op, Ty);
6059         return Op;
6060       };
6061       LS = CoerceOperand(LS);
6062       RS = CoerceOperand(RS);
6063       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6064         break;
6065       const SCEV *LDiff = getMinusSCEV(LA, LS);
6066       const SCEV *RDiff = getMinusSCEV(RA, RS);
6067       if (LDiff == RDiff)
6068         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6069                           LDiff);
6070       LDiff = getMinusSCEV(LA, RS);
6071       RDiff = getMinusSCEV(RA, LS);
6072       if (LDiff == RDiff)
6073         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6074                           LDiff);
6075     }
6076     break;
6077   case ICmpInst::ICMP_NE:
6078     // x != 0 ? x+y : C+y  ->  x == 0 ? C+y : x+y
6079     std::swap(TrueVal, FalseVal);
6080     [[fallthrough]];
6081   case ICmpInst::ICMP_EQ:
6082     // x == 0 ? C+y : x+y  ->  umax(x, C)+y   iff C u<= 1
6083     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty) &&
6084         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6085       const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6086       const SCEV *TrueValExpr = getSCEV(TrueVal);    // C+y
6087       const SCEV *FalseValExpr = getSCEV(FalseVal);  // x+y
6088       const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6089       const SCEV *C = getMinusSCEV(TrueValExpr, Y);  // C = (C+y)-y
6090       if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6091         return getAddExpr(getUMaxExpr(X, C), Y);
6092     }
6093     // x == 0 ? 0 : umin    (..., x, ...)  ->  umin_seq(x, umin    (...))
6094     // x == 0 ? 0 : umin_seq(..., x, ...)  ->  umin_seq(x, umin_seq(...))
6095     // x == 0 ? 0 : umin    (..., umin_seq(..., x, ...), ...)
6096     //                    ->  umin_seq(x, umin (..., umin_seq(...), ...))
6097     if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6098         isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6099       const SCEV *X = getSCEV(LHS);
6100       while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6101         X = ZExt->getOperand();
6102       if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6103         const SCEV *FalseValExpr = getSCEV(FalseVal);
6104         if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6105           return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6106                              /*Sequential=*/true);
6107       }
6108     }
6109     break;
6110   default:
6111     break;
6112   }
6113 
6114   return std::nullopt;
6115 }
6116 
6117 static std::optional<const SCEV *>
6118 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6119                               const SCEV *TrueExpr, const SCEV *FalseExpr) {
6120   assert(CondExpr->getType()->isIntegerTy(1) &&
6121          TrueExpr->getType() == FalseExpr->getType() &&
6122          TrueExpr->getType()->isIntegerTy(1) &&
6123          "Unexpected operands of a select.");
6124 
6125   // i1 cond ? i1 x : i1 C  -->  C + (i1  cond ? (i1 x - i1 C) : i1 0)
6126   //                        -->  C + (umin_seq  cond, x - C)
6127   //
6128   // i1 cond ? i1 C : i1 x  -->  C + (i1  cond ? i1 0 : (i1 x - i1 C))
6129   //                        -->  C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6130   //                        -->  C + (umin_seq ~cond, x - C)
6131 
6132   // FIXME: while we can't legally model the case where both of the hands
6133   // are fully variable, we only require that the *difference* is constant.
6134   if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6135     return std::nullopt;
6136 
6137   const SCEV *X, *C;
6138   if (isa<SCEVConstant>(TrueExpr)) {
6139     CondExpr = SE->getNotSCEV(CondExpr);
6140     X = FalseExpr;
6141     C = TrueExpr;
6142   } else {
6143     X = TrueExpr;
6144     C = FalseExpr;
6145   }
6146   return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6147                                            /*Sequential=*/true));
6148 }
6149 
6150 static std::optional<const SCEV *>
6151 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
6152                               Value *FalseVal) {
6153   if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6154     return std::nullopt;
6155 
6156   const auto *SECond = SE->getSCEV(Cond);
6157   const auto *SETrue = SE->getSCEV(TrueVal);
6158   const auto *SEFalse = SE->getSCEV(FalseVal);
6159   return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6160 }
6161 
6162 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6163     Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6164   assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6165   assert(TrueVal->getType() == FalseVal->getType() &&
6166          V->getType() == TrueVal->getType() &&
6167          "Types of select hands and of the result must match.");
6168 
6169   // For now, only deal with i1-typed `select`s.
6170   if (!V->getType()->isIntegerTy(1))
6171     return getUnknown(V);
6172 
6173   if (std::optional<const SCEV *> S =
6174           createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6175     return *S;
6176 
6177   return getUnknown(V);
6178 }
6179 
6180 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6181                                                       Value *TrueVal,
6182                                                       Value *FalseVal) {
6183   // Handle "constant" branch or select. This can occur for instance when a
6184   // loop pass transforms an inner loop and moves on to process the outer loop.
6185   if (auto *CI = dyn_cast<ConstantInt>(Cond))
6186     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6187 
6188   if (auto *I = dyn_cast<Instruction>(V)) {
6189     if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6190       if (std::optional<const SCEV *> S =
6191               createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6192                                                            TrueVal, FalseVal))
6193         return *S;
6194     }
6195   }
6196 
6197   return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6198 }
6199 
6200 /// Expand GEP instructions into add and multiply operations. This allows them
6201 /// to be analyzed by regular SCEV code.
6202 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6203   assert(GEP->getSourceElementType()->isSized() &&
6204          "GEP source element type must be sized");
6205 
6206   SmallVector<const SCEV *, 4> IndexExprs;
6207   for (Value *Index : GEP->indices())
6208     IndexExprs.push_back(getSCEV(Index));
6209   return getGEPExpr(GEP, IndexExprs);
6210 }
6211 
6212 APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S) {
6213   uint64_t BitWidth = getTypeSizeInBits(S->getType());
6214   auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6215     return TrailingZeros >= BitWidth
6216                ? APInt::getZero(BitWidth)
6217                : APInt::getOneBitSet(BitWidth, TrailingZeros);
6218   };
6219   auto GetGCDMultiple = [this](const SCEVNAryExpr *N) {
6220     // The result is GCD of all operands results.
6221     APInt Res = getConstantMultiple(N->getOperand(0));
6222     for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6223       Res = APIntOps::GreatestCommonDivisor(
6224           Res, getConstantMultiple(N->getOperand(I)));
6225     return Res;
6226   };
6227 
6228   switch (S->getSCEVType()) {
6229   case scConstant:
6230     return cast<SCEVConstant>(S)->getAPInt();
6231   case scPtrToInt:
6232     return getConstantMultiple(cast<SCEVPtrToIntExpr>(S)->getOperand());
6233   case scUDivExpr:
6234   case scVScale:
6235     return APInt(BitWidth, 1);
6236   case scTruncate: {
6237     // Only multiples that are a power of 2 will hold after truncation.
6238     const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6239     uint32_t TZ = getMinTrailingZeros(T->getOperand());
6240     return GetShiftedByZeros(TZ);
6241   }
6242   case scZeroExtend: {
6243     const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6244     return getConstantMultiple(Z->getOperand()).zext(BitWidth);
6245   }
6246   case scSignExtend: {
6247     const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6248     return getConstantMultiple(E->getOperand()).sext(BitWidth);
6249   }
6250   case scMulExpr: {
6251     const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6252     if (M->hasNoUnsignedWrap()) {
6253       // The result is the product of all operand results.
6254       APInt Res = getConstantMultiple(M->getOperand(0));
6255       for (const SCEV *Operand : M->operands().drop_front())
6256         Res = Res * getConstantMultiple(Operand);
6257       return Res;
6258     }
6259 
6260     // If there are no wrap guarentees, find the trailing zeros, which is the
6261     // sum of trailing zeros for all its operands.
6262     uint32_t TZ = 0;
6263     for (const SCEV *Operand : M->operands())
6264       TZ += getMinTrailingZeros(Operand);
6265     return GetShiftedByZeros(TZ);
6266   }
6267   case scAddExpr:
6268   case scAddRecExpr: {
6269     const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6270     if (N->hasNoUnsignedWrap())
6271         return GetGCDMultiple(N);
6272     // Find the trailing bits, which is the minimum of its operands.
6273     uint32_t TZ = getMinTrailingZeros(N->getOperand(0));
6274     for (const SCEV *Operand : N->operands().drop_front())
6275       TZ = std::min(TZ, getMinTrailingZeros(Operand));
6276     return GetShiftedByZeros(TZ);
6277   }
6278   case scUMaxExpr:
6279   case scSMaxExpr:
6280   case scUMinExpr:
6281   case scSMinExpr:
6282   case scSequentialUMinExpr:
6283     return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6284   case scUnknown: {
6285     // ask ValueTracking for known bits
6286     const SCEVUnknown *U = cast<SCEVUnknown>(S);
6287     unsigned Known =
6288         computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT)
6289             .countMinTrailingZeros();
6290     return GetShiftedByZeros(Known);
6291   }
6292   case scCouldNotCompute:
6293     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6294   }
6295   llvm_unreachable("Unknown SCEV kind!");
6296 }
6297 
6298 APInt ScalarEvolution::getConstantMultiple(const SCEV *S) {
6299   auto I = ConstantMultipleCache.find(S);
6300   if (I != ConstantMultipleCache.end())
6301     return I->second;
6302 
6303   APInt Result = getConstantMultipleImpl(S);
6304   auto InsertPair = ConstantMultipleCache.insert({S, Result});
6305   assert(InsertPair.second && "Should insert a new key");
6306   return InsertPair.first->second;
6307 }
6308 
6309 APInt ScalarEvolution::getNonZeroConstantMultiple(const SCEV *S) {
6310   APInt Multiple = getConstantMultiple(S);
6311   return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6312 }
6313 
6314 uint32_t ScalarEvolution::getMinTrailingZeros(const SCEV *S) {
6315   return std::min(getConstantMultiple(S).countTrailingZeros(),
6316                   (unsigned)getTypeSizeInBits(S->getType()));
6317 }
6318 
6319 /// Helper method to assign a range to V from metadata present in the IR.
6320 static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6321   if (Instruction *I = dyn_cast<Instruction>(V))
6322     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6323       return getConstantRangeFromMetadata(*MD);
6324 
6325   return std::nullopt;
6326 }
6327 
6328 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6329                                      SCEV::NoWrapFlags Flags) {
6330   if (AddRec->getNoWrapFlags(Flags) != Flags) {
6331     AddRec->setNoWrapFlags(Flags);
6332     UnsignedRanges.erase(AddRec);
6333     SignedRanges.erase(AddRec);
6334     ConstantMultipleCache.erase(AddRec);
6335   }
6336 }
6337 
6338 ConstantRange ScalarEvolution::
6339 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6340   const DataLayout &DL = getDataLayout();
6341 
6342   unsigned BitWidth = getTypeSizeInBits(U->getType());
6343   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6344 
6345   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6346   // use information about the trip count to improve our available range.  Note
6347   // that the trip count independent cases are already handled by known bits.
6348   // WARNING: The definition of recurrence used here is subtly different than
6349   // the one used by AddRec (and thus most of this file).  Step is allowed to
6350   // be arbitrarily loop varying here, where AddRec allows only loop invariant
6351   // and other addrecs in the same loop (for non-affine addrecs).  The code
6352   // below intentionally handles the case where step is not loop invariant.
6353   auto *P = dyn_cast<PHINode>(U->getValue());
6354   if (!P)
6355     return FullSet;
6356 
6357   // Make sure that no Phi input comes from an unreachable block. Otherwise,
6358   // even the values that are not available in these blocks may come from them,
6359   // and this leads to false-positive recurrence test.
6360   for (auto *Pred : predecessors(P->getParent()))
6361     if (!DT.isReachableFromEntry(Pred))
6362       return FullSet;
6363 
6364   BinaryOperator *BO;
6365   Value *Start, *Step;
6366   if (!matchSimpleRecurrence(P, BO, Start, Step))
6367     return FullSet;
6368 
6369   // If we found a recurrence in reachable code, we must be in a loop. Note
6370   // that BO might be in some subloop of L, and that's completely okay.
6371   auto *L = LI.getLoopFor(P->getParent());
6372   assert(L && L->getHeader() == P->getParent());
6373   if (!L->contains(BO->getParent()))
6374     // NOTE: This bailout should be an assert instead.  However, asserting
6375     // the condition here exposes a case where LoopFusion is querying SCEV
6376     // with malformed loop information during the midst of the transform.
6377     // There doesn't appear to be an obvious fix, so for the moment bailout
6378     // until the caller issue can be fixed.  PR49566 tracks the bug.
6379     return FullSet;
6380 
6381   // TODO: Extend to other opcodes such as mul, and div
6382   switch (BO->getOpcode()) {
6383   default:
6384     return FullSet;
6385   case Instruction::AShr:
6386   case Instruction::LShr:
6387   case Instruction::Shl:
6388     break;
6389   };
6390 
6391   if (BO->getOperand(0) != P)
6392     // TODO: Handle the power function forms some day.
6393     return FullSet;
6394 
6395   unsigned TC = getSmallConstantMaxTripCount(L);
6396   if (!TC || TC >= BitWidth)
6397     return FullSet;
6398 
6399   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6400   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6401   assert(KnownStart.getBitWidth() == BitWidth &&
6402          KnownStep.getBitWidth() == BitWidth);
6403 
6404   // Compute total shift amount, being careful of overflow and bitwidths.
6405   auto MaxShiftAmt = KnownStep.getMaxValue();
6406   APInt TCAP(BitWidth, TC-1);
6407   bool Overflow = false;
6408   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6409   if (Overflow)
6410     return FullSet;
6411 
6412   switch (BO->getOpcode()) {
6413   default:
6414     llvm_unreachable("filtered out above");
6415   case Instruction::AShr: {
6416     // For each ashr, three cases:
6417     //   shift = 0 => unchanged value
6418     //   saturation => 0 or -1
6419     //   other => a value closer to zero (of the same sign)
6420     // Thus, the end value is closer to zero than the start.
6421     auto KnownEnd = KnownBits::ashr(KnownStart,
6422                                     KnownBits::makeConstant(TotalShift));
6423     if (KnownStart.isNonNegative())
6424       // Analogous to lshr (simply not yet canonicalized)
6425       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6426                                         KnownStart.getMaxValue() + 1);
6427     if (KnownStart.isNegative())
6428       // End >=u Start && End <=s Start
6429       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6430                                         KnownEnd.getMaxValue() + 1);
6431     break;
6432   }
6433   case Instruction::LShr: {
6434     // For each lshr, three cases:
6435     //   shift = 0 => unchanged value
6436     //   saturation => 0
6437     //   other => a smaller positive number
6438     // Thus, the low end of the unsigned range is the last value produced.
6439     auto KnownEnd = KnownBits::lshr(KnownStart,
6440                                     KnownBits::makeConstant(TotalShift));
6441     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6442                                       KnownStart.getMaxValue() + 1);
6443   }
6444   case Instruction::Shl: {
6445     // Iff no bits are shifted out, value increases on every shift.
6446     auto KnownEnd = KnownBits::shl(KnownStart,
6447                                    KnownBits::makeConstant(TotalShift));
6448     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6449       return ConstantRange(KnownStart.getMinValue(),
6450                            KnownEnd.getMaxValue() + 1);
6451     break;
6452   }
6453   };
6454   return FullSet;
6455 }
6456 
6457 const ConstantRange &
6458 ScalarEvolution::getRangeRefIter(const SCEV *S,
6459                                  ScalarEvolution::RangeSignHint SignHint) {
6460   DenseMap<const SCEV *, ConstantRange> &Cache =
6461       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6462                                                        : SignedRanges;
6463   SmallVector<const SCEV *> WorkList;
6464   SmallPtrSet<const SCEV *, 8> Seen;
6465 
6466   // Add Expr to the worklist, if Expr is either an N-ary expression or a
6467   // SCEVUnknown PHI node.
6468   auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6469     if (!Seen.insert(Expr).second)
6470       return;
6471     if (Cache.contains(Expr))
6472       return;
6473     switch (Expr->getSCEVType()) {
6474     case scUnknown:
6475       if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
6476         break;
6477       [[fallthrough]];
6478     case scConstant:
6479     case scVScale:
6480     case scTruncate:
6481     case scZeroExtend:
6482     case scSignExtend:
6483     case scPtrToInt:
6484     case scAddExpr:
6485     case scMulExpr:
6486     case scUDivExpr:
6487     case scAddRecExpr:
6488     case scUMaxExpr:
6489     case scSMaxExpr:
6490     case scUMinExpr:
6491     case scSMinExpr:
6492     case scSequentialUMinExpr:
6493       WorkList.push_back(Expr);
6494       break;
6495     case scCouldNotCompute:
6496       llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6497     }
6498   };
6499   AddToWorklist(S);
6500 
6501   // Build worklist by queuing operands of N-ary expressions and phi nodes.
6502   for (unsigned I = 0; I != WorkList.size(); ++I) {
6503     const SCEV *P = WorkList[I];
6504     auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6505     // If it is not a `SCEVUnknown`, just recurse into operands.
6506     if (!UnknownS) {
6507       for (const SCEV *Op : P->operands())
6508         AddToWorklist(Op);
6509       continue;
6510     }
6511     // `SCEVUnknown`'s require special treatment.
6512     if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6513       if (!PendingPhiRangesIter.insert(P).second)
6514         continue;
6515       for (auto &Op : reverse(P->operands()))
6516         AddToWorklist(getSCEV(Op));
6517     }
6518   }
6519 
6520   if (!WorkList.empty()) {
6521     // Use getRangeRef to compute ranges for items in the worklist in reverse
6522     // order. This will force ranges for earlier operands to be computed before
6523     // their users in most cases.
6524     for (const SCEV *P : reverse(drop_begin(WorkList))) {
6525       getRangeRef(P, SignHint);
6526 
6527       if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
6528         if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
6529           PendingPhiRangesIter.erase(P);
6530     }
6531   }
6532 
6533   return getRangeRef(S, SignHint, 0);
6534 }
6535 
6536 /// Determine the range for a particular SCEV.  If SignHint is
6537 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6538 /// with a "cleaner" unsigned (resp. signed) representation.
6539 const ConstantRange &ScalarEvolution::getRangeRef(
6540     const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6541   DenseMap<const SCEV *, ConstantRange> &Cache =
6542       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6543                                                        : SignedRanges;
6544   ConstantRange::PreferredRangeType RangeType =
6545       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6546                                                        : ConstantRange::Signed;
6547 
6548   // See if we've computed this range already.
6549   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6550   if (I != Cache.end())
6551     return I->second;
6552 
6553   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6554     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6555 
6556   // Switch to iteratively computing the range for S, if it is part of a deeply
6557   // nested expression.
6558   if (Depth > RangeIterThreshold)
6559     return getRangeRefIter(S, SignHint);
6560 
6561   unsigned BitWidth = getTypeSizeInBits(S->getType());
6562   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6563   using OBO = OverflowingBinaryOperator;
6564 
6565   // If the value has known zeros, the maximum value will have those known zeros
6566   // as well.
6567   if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6568     APInt Multiple = getNonZeroConstantMultiple(S);
6569     APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6570     if (!Remainder.isZero())
6571       ConservativeResult =
6572           ConstantRange(APInt::getMinValue(BitWidth),
6573                         APInt::getMaxValue(BitWidth) - Remainder + 1);
6574   }
6575   else {
6576     uint32_t TZ = getMinTrailingZeros(S);
6577     if (TZ != 0) {
6578       ConservativeResult = ConstantRange(
6579           APInt::getSignedMinValue(BitWidth),
6580           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6581     }
6582   }
6583 
6584   switch (S->getSCEVType()) {
6585   case scConstant:
6586     llvm_unreachable("Already handled above.");
6587   case scVScale:
6588     return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6589   case scTruncate: {
6590     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6591     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6592     return setRange(
6593         Trunc, SignHint,
6594         ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6595   }
6596   case scZeroExtend: {
6597     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6598     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6599     return setRange(
6600         ZExt, SignHint,
6601         ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6602   }
6603   case scSignExtend: {
6604     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6605     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6606     return setRange(
6607         SExt, SignHint,
6608         ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6609   }
6610   case scPtrToInt: {
6611     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(S);
6612     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
6613     return setRange(PtrToInt, SignHint, X);
6614   }
6615   case scAddExpr: {
6616     const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6617     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6618     unsigned WrapType = OBO::AnyWrap;
6619     if (Add->hasNoSignedWrap())
6620       WrapType |= OBO::NoSignedWrap;
6621     if (Add->hasNoUnsignedWrap())
6622       WrapType |= OBO::NoUnsignedWrap;
6623     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6624       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
6625                           WrapType, RangeType);
6626     return setRange(Add, SignHint,
6627                     ConservativeResult.intersectWith(X, RangeType));
6628   }
6629   case scMulExpr: {
6630     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6631     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6632     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6633       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
6634     return setRange(Mul, SignHint,
6635                     ConservativeResult.intersectWith(X, RangeType));
6636   }
6637   case scUDivExpr: {
6638     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6639     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6640     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6641     return setRange(UDiv, SignHint,
6642                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6643   }
6644   case scAddRecExpr: {
6645     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6646     // If there's no unsigned wrap, the value will never be less than its
6647     // initial value.
6648     if (AddRec->hasNoUnsignedWrap()) {
6649       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6650       if (!UnsignedMinValue.isZero())
6651         ConservativeResult = ConservativeResult.intersectWith(
6652             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6653     }
6654 
6655     // If there's no signed wrap, and all the operands except initial value have
6656     // the same sign or zero, the value won't ever be:
6657     // 1: smaller than initial value if operands are non negative,
6658     // 2: bigger than initial value if operands are non positive.
6659     // For both cases, value can not cross signed min/max boundary.
6660     if (AddRec->hasNoSignedWrap()) {
6661       bool AllNonNeg = true;
6662       bool AllNonPos = true;
6663       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6664         if (!isKnownNonNegative(AddRec->getOperand(i)))
6665           AllNonNeg = false;
6666         if (!isKnownNonPositive(AddRec->getOperand(i)))
6667           AllNonPos = false;
6668       }
6669       if (AllNonNeg)
6670         ConservativeResult = ConservativeResult.intersectWith(
6671             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6672                                        APInt::getSignedMinValue(BitWidth)),
6673             RangeType);
6674       else if (AllNonPos)
6675         ConservativeResult = ConservativeResult.intersectWith(
6676             ConstantRange::getNonEmpty(APInt::getSignedMinValue(BitWidth),
6677                                        getSignedRangeMax(AddRec->getStart()) +
6678                                            1),
6679             RangeType);
6680     }
6681 
6682     // TODO: non-affine addrec
6683     if (AddRec->isAffine()) {
6684       const SCEV *MaxBEScev =
6685           getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6686       if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6687         APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6688 
6689         // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6690         // MaxBECount's active bits are all <= AddRec's bit width.
6691         if (MaxBECount.getBitWidth() > BitWidth &&
6692             MaxBECount.getActiveBits() <= BitWidth)
6693           MaxBECount = MaxBECount.trunc(BitWidth);
6694         else if (MaxBECount.getBitWidth() < BitWidth)
6695           MaxBECount = MaxBECount.zext(BitWidth);
6696 
6697         if (MaxBECount.getBitWidth() == BitWidth) {
6698           auto RangeFromAffine = getRangeForAffineAR(
6699               AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6700           ConservativeResult =
6701               ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6702 
6703           auto RangeFromFactoring = getRangeViaFactoring(
6704               AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6705           ConservativeResult =
6706               ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6707         }
6708       }
6709 
6710       // Now try symbolic BE count and more powerful methods.
6711       if (UseExpensiveRangeSharpening) {
6712         const SCEV *SymbolicMaxBECount =
6713             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6714         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6715             getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6716             AddRec->hasNoSelfWrap()) {
6717           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6718               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6719           ConservativeResult =
6720               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6721         }
6722       }
6723     }
6724 
6725     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6726   }
6727   case scUMaxExpr:
6728   case scSMaxExpr:
6729   case scUMinExpr:
6730   case scSMinExpr:
6731   case scSequentialUMinExpr: {
6732     Intrinsic::ID ID;
6733     switch (S->getSCEVType()) {
6734     case scUMaxExpr:
6735       ID = Intrinsic::umax;
6736       break;
6737     case scSMaxExpr:
6738       ID = Intrinsic::smax;
6739       break;
6740     case scUMinExpr:
6741     case scSequentialUMinExpr:
6742       ID = Intrinsic::umin;
6743       break;
6744     case scSMinExpr:
6745       ID = Intrinsic::smin;
6746       break;
6747     default:
6748       llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6749     }
6750 
6751     const auto *NAry = cast<SCEVNAryExpr>(S);
6752     ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6753     for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6754       X = X.intrinsic(
6755           ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6756     return setRange(S, SignHint,
6757                     ConservativeResult.intersectWith(X, RangeType));
6758   }
6759   case scUnknown: {
6760     const SCEVUnknown *U = cast<SCEVUnknown>(S);
6761     Value *V = U->getValue();
6762 
6763     // Check if the IR explicitly contains !range metadata.
6764     std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6765     if (MDRange)
6766       ConservativeResult =
6767           ConservativeResult.intersectWith(*MDRange, RangeType);
6768 
6769     // Use facts about recurrences in the underlying IR.  Note that add
6770     // recurrences are AddRecExprs and thus don't hit this path.  This
6771     // primarily handles shift recurrences.
6772     auto CR = getRangeForUnknownRecurrence(U);
6773     ConservativeResult = ConservativeResult.intersectWith(CR);
6774 
6775     // See if ValueTracking can give us a useful range.
6776     const DataLayout &DL = getDataLayout();
6777     KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, &DT);
6778     if (Known.getBitWidth() != BitWidth)
6779       Known = Known.zextOrTrunc(BitWidth);
6780 
6781     // ValueTracking may be able to compute a tighter result for the number of
6782     // sign bits than for the value of those sign bits.
6783     unsigned NS = ComputeNumSignBits(V, DL, 0, &AC, nullptr, &DT);
6784     if (U->getType()->isPointerTy()) {
6785       // If the pointer size is larger than the index size type, this can cause
6786       // NS to be larger than BitWidth. So compensate for this.
6787       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6788       int ptrIdxDiff = ptrSize - BitWidth;
6789       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6790         NS -= ptrIdxDiff;
6791     }
6792 
6793     if (NS > 1) {
6794       // If we know any of the sign bits, we know all of the sign bits.
6795       if (!Known.Zero.getHiBits(NS).isZero())
6796         Known.Zero.setHighBits(NS);
6797       if (!Known.One.getHiBits(NS).isZero())
6798         Known.One.setHighBits(NS);
6799     }
6800 
6801     if (Known.getMinValue() != Known.getMaxValue() + 1)
6802       ConservativeResult = ConservativeResult.intersectWith(
6803           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6804           RangeType);
6805     if (NS > 1)
6806       ConservativeResult = ConservativeResult.intersectWith(
6807           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6808                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6809           RangeType);
6810 
6811     if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6812       // Strengthen the range if the underlying IR value is a
6813       // global/alloca/heap allocation using the size of the object.
6814       ObjectSizeOpts Opts;
6815       Opts.RoundToAlign = false;
6816       Opts.NullIsUnknownSize = true;
6817       uint64_t ObjSize;
6818       if ((isa<GlobalVariable>(V) || isa<AllocaInst>(V) ||
6819            isAllocationFn(V, &TLI)) &&
6820           getObjectSize(V, ObjSize, DL, &TLI, Opts) && ObjSize > 1) {
6821         // The highest address the object can start is ObjSize bytes before the
6822         // end (unsigned max value). If this value is not a multiple of the
6823         // alignment, the last possible start value is the next lowest multiple
6824         // of the alignment. Note: The computations below cannot overflow,
6825         // because if they would there's no possible start address for the
6826         // object.
6827         APInt MaxVal = APInt::getMaxValue(BitWidth) - APInt(BitWidth, ObjSize);
6828         uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6829         uint64_t Rem = MaxVal.urem(Align);
6830         MaxVal -= APInt(BitWidth, Rem);
6831         APInt MinVal = APInt::getZero(BitWidth);
6832         if (llvm::isKnownNonZero(V, DL))
6833           MinVal = Align;
6834         ConservativeResult = ConservativeResult.intersectWith(
6835             ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6836       }
6837     }
6838 
6839     // A range of Phi is a subset of union of all ranges of its input.
6840     if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6841       // Make sure that we do not run over cycled Phis.
6842       if (PendingPhiRanges.insert(Phi).second) {
6843         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6844 
6845         for (const auto &Op : Phi->operands()) {
6846           auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6847           RangeFromOps = RangeFromOps.unionWith(OpRange);
6848           // No point to continue if we already have a full set.
6849           if (RangeFromOps.isFullSet())
6850             break;
6851         }
6852         ConservativeResult =
6853             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6854         bool Erased = PendingPhiRanges.erase(Phi);
6855         assert(Erased && "Failed to erase Phi properly?");
6856         (void)Erased;
6857       }
6858     }
6859 
6860     // vscale can't be equal to zero
6861     if (const auto *II = dyn_cast<IntrinsicInst>(V))
6862       if (II->getIntrinsicID() == Intrinsic::vscale) {
6863         ConstantRange Disallowed = APInt::getZero(BitWidth);
6864         ConservativeResult = ConservativeResult.difference(Disallowed);
6865       }
6866 
6867     return setRange(U, SignHint, std::move(ConservativeResult));
6868   }
6869   case scCouldNotCompute:
6870     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6871   }
6872 
6873   return setRange(S, SignHint, std::move(ConservativeResult));
6874 }
6875 
6876 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6877 // values that the expression can take. Initially, the expression has a value
6878 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6879 // argument defines if we treat Step as signed or unsigned.
6880 static ConstantRange getRangeForAffineARHelper(APInt Step,
6881                                                const ConstantRange &StartRange,
6882                                                const APInt &MaxBECount,
6883                                                bool Signed) {
6884   unsigned BitWidth = Step.getBitWidth();
6885   assert(BitWidth == StartRange.getBitWidth() &&
6886          BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6887   // If either Step or MaxBECount is 0, then the expression won't change, and we
6888   // just need to return the initial range.
6889   if (Step == 0 || MaxBECount == 0)
6890     return StartRange;
6891 
6892   // If we don't know anything about the initial value (i.e. StartRange is
6893   // FullRange), then we don't know anything about the final range either.
6894   // Return FullRange.
6895   if (StartRange.isFullSet())
6896     return ConstantRange::getFull(BitWidth);
6897 
6898   // If Step is signed and negative, then we use its absolute value, but we also
6899   // note that we're moving in the opposite direction.
6900   bool Descending = Signed && Step.isNegative();
6901 
6902   if (Signed)
6903     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6904     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6905     // This equations hold true due to the well-defined wrap-around behavior of
6906     // APInt.
6907     Step = Step.abs();
6908 
6909   // Check if Offset is more than full span of BitWidth. If it is, the
6910   // expression is guaranteed to overflow.
6911   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6912     return ConstantRange::getFull(BitWidth);
6913 
6914   // Offset is by how much the expression can change. Checks above guarantee no
6915   // overflow here.
6916   APInt Offset = Step * MaxBECount;
6917 
6918   // Minimum value of the final range will match the minimal value of StartRange
6919   // if the expression is increasing and will be decreased by Offset otherwise.
6920   // Maximum value of the final range will match the maximal value of StartRange
6921   // if the expression is decreasing and will be increased by Offset otherwise.
6922   APInt StartLower = StartRange.getLower();
6923   APInt StartUpper = StartRange.getUpper() - 1;
6924   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6925                                    : (StartUpper + std::move(Offset));
6926 
6927   // It's possible that the new minimum/maximum value will fall into the initial
6928   // range (due to wrap around). This means that the expression can take any
6929   // value in this bitwidth, and we have to return full range.
6930   if (StartRange.contains(MovedBoundary))
6931     return ConstantRange::getFull(BitWidth);
6932 
6933   APInt NewLower =
6934       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6935   APInt NewUpper =
6936       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6937   NewUpper += 1;
6938 
6939   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6940   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6941 }
6942 
6943 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6944                                                    const SCEV *Step,
6945                                                    const APInt &MaxBECount) {
6946   assert(getTypeSizeInBits(Start->getType()) ==
6947              getTypeSizeInBits(Step->getType()) &&
6948          getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
6949          "mismatched bit widths");
6950 
6951   // First, consider step signed.
6952   ConstantRange StartSRange = getSignedRange(Start);
6953   ConstantRange StepSRange = getSignedRange(Step);
6954 
6955   // If Step can be both positive and negative, we need to find ranges for the
6956   // maximum absolute step values in both directions and union them.
6957   ConstantRange SR = getRangeForAffineARHelper(
6958       StepSRange.getSignedMin(), StartSRange, MaxBECount, /* Signed = */ true);
6959   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6960                                               StartSRange, MaxBECount,
6961                                               /* Signed = */ true));
6962 
6963   // Next, consider step unsigned.
6964   ConstantRange UR = getRangeForAffineARHelper(
6965       getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
6966       /* Signed = */ false);
6967 
6968   // Finally, intersect signed and unsigned ranges.
6969   return SR.intersectWith(UR, ConstantRange::Smallest);
6970 }
6971 
6972 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6973     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6974     ScalarEvolution::RangeSignHint SignHint) {
6975   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6976   assert(AddRec->hasNoSelfWrap() &&
6977          "This only works for non-self-wrapping AddRecs!");
6978   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6979   const SCEV *Step = AddRec->getStepRecurrence(*this);
6980   // Only deal with constant step to save compile time.
6981   if (!isa<SCEVConstant>(Step))
6982     return ConstantRange::getFull(BitWidth);
6983   // Let's make sure that we can prove that we do not self-wrap during
6984   // MaxBECount iterations. We need this because MaxBECount is a maximum
6985   // iteration count estimate, and we might infer nw from some exit for which we
6986   // do not know max exit count (or any other side reasoning).
6987   // TODO: Turn into assert at some point.
6988   if (getTypeSizeInBits(MaxBECount->getType()) >
6989       getTypeSizeInBits(AddRec->getType()))
6990     return ConstantRange::getFull(BitWidth);
6991   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6992   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6993   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6994   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6995   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6996                                          MaxItersWithoutWrap))
6997     return ConstantRange::getFull(BitWidth);
6998 
6999   ICmpInst::Predicate LEPred =
7000       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
7001   ICmpInst::Predicate GEPred =
7002       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
7003   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7004 
7005   // We know that there is no self-wrap. Let's take Start and End values and
7006   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7007   // the iteration. They either lie inside the range [Min(Start, End),
7008   // Max(Start, End)] or outside it:
7009   //
7010   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
7011   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
7012   //
7013   // No self wrap flag guarantees that the intermediate values cannot be BOTH
7014   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7015   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7016   // Start <= End and step is positive, or Start >= End and step is negative.
7017   const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7018   ConstantRange StartRange = getRangeRef(Start, SignHint);
7019   ConstantRange EndRange = getRangeRef(End, SignHint);
7020   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7021   // If they already cover full iteration space, we will know nothing useful
7022   // even if we prove what we want to prove.
7023   if (RangeBetween.isFullSet())
7024     return RangeBetween;
7025   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7026   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7027                                : RangeBetween.isWrappedSet();
7028   if (IsWrappedSet)
7029     return ConstantRange::getFull(BitWidth);
7030 
7031   if (isKnownPositive(Step) &&
7032       isKnownPredicateViaConstantRanges(LEPred, Start, End))
7033     return RangeBetween;
7034   if (isKnownNegative(Step) &&
7035            isKnownPredicateViaConstantRanges(GEPred, Start, End))
7036     return RangeBetween;
7037   return ConstantRange::getFull(BitWidth);
7038 }
7039 
7040 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7041                                                     const SCEV *Step,
7042                                                     const APInt &MaxBECount) {
7043   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7044   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7045 
7046   unsigned BitWidth = MaxBECount.getBitWidth();
7047   assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7048          getTypeSizeInBits(Step->getType()) == BitWidth &&
7049          "mismatched bit widths");
7050 
7051   struct SelectPattern {
7052     Value *Condition = nullptr;
7053     APInt TrueValue;
7054     APInt FalseValue;
7055 
7056     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7057                            const SCEV *S) {
7058       std::optional<unsigned> CastOp;
7059       APInt Offset(BitWidth, 0);
7060 
7061       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
7062              "Should be!");
7063 
7064       // Peel off a constant offset:
7065       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
7066         // In the future we could consider being smarter here and handle
7067         // {Start+Step,+,Step} too.
7068         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
7069           return;
7070 
7071         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
7072         S = SA->getOperand(1);
7073       }
7074 
7075       // Peel off a cast operation
7076       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7077         CastOp = SCast->getSCEVType();
7078         S = SCast->getOperand();
7079       }
7080 
7081       using namespace llvm::PatternMatch;
7082 
7083       auto *SU = dyn_cast<SCEVUnknown>(S);
7084       const APInt *TrueVal, *FalseVal;
7085       if (!SU ||
7086           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7087                                           m_APInt(FalseVal)))) {
7088         Condition = nullptr;
7089         return;
7090       }
7091 
7092       TrueValue = *TrueVal;
7093       FalseValue = *FalseVal;
7094 
7095       // Re-apply the cast we peeled off earlier
7096       if (CastOp)
7097         switch (*CastOp) {
7098         default:
7099           llvm_unreachable("Unknown SCEV cast type!");
7100 
7101         case scTruncate:
7102           TrueValue = TrueValue.trunc(BitWidth);
7103           FalseValue = FalseValue.trunc(BitWidth);
7104           break;
7105         case scZeroExtend:
7106           TrueValue = TrueValue.zext(BitWidth);
7107           FalseValue = FalseValue.zext(BitWidth);
7108           break;
7109         case scSignExtend:
7110           TrueValue = TrueValue.sext(BitWidth);
7111           FalseValue = FalseValue.sext(BitWidth);
7112           break;
7113         }
7114 
7115       // Re-apply the constant offset we peeled off earlier
7116       TrueValue += Offset;
7117       FalseValue += Offset;
7118     }
7119 
7120     bool isRecognized() { return Condition != nullptr; }
7121   };
7122 
7123   SelectPattern StartPattern(*this, BitWidth, Start);
7124   if (!StartPattern.isRecognized())
7125     return ConstantRange::getFull(BitWidth);
7126 
7127   SelectPattern StepPattern(*this, BitWidth, Step);
7128   if (!StepPattern.isRecognized())
7129     return ConstantRange::getFull(BitWidth);
7130 
7131   if (StartPattern.Condition != StepPattern.Condition) {
7132     // We don't handle this case today; but we could, by considering four
7133     // possibilities below instead of two. I'm not sure if there are cases where
7134     // that will help over what getRange already does, though.
7135     return ConstantRange::getFull(BitWidth);
7136   }
7137 
7138   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7139   // construct arbitrary general SCEV expressions here.  This function is called
7140   // from deep in the call stack, and calling getSCEV (on a sext instruction,
7141   // say) can end up caching a suboptimal value.
7142 
7143   // FIXME: without the explicit `this` receiver below, MSVC errors out with
7144   // C2352 and C2512 (otherwise it isn't needed).
7145 
7146   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7147   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7148   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7149   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7150 
7151   ConstantRange TrueRange =
7152       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount);
7153   ConstantRange FalseRange =
7154       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount);
7155 
7156   return TrueRange.unionWith(FalseRange);
7157 }
7158 
7159 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7160   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7161   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7162 
7163   // Return early if there are no flags to propagate to the SCEV.
7164   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7165   if (BinOp->hasNoUnsignedWrap())
7166     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
7167   if (BinOp->hasNoSignedWrap())
7168     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
7169   if (Flags == SCEV::FlagAnyWrap)
7170     return SCEV::FlagAnyWrap;
7171 
7172   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7173 }
7174 
7175 const Instruction *
7176 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7177   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7178     return &*AddRec->getLoop()->getHeader()->begin();
7179   if (auto *U = dyn_cast<SCEVUnknown>(S))
7180     if (auto *I = dyn_cast<Instruction>(U->getValue()))
7181       return I;
7182   return nullptr;
7183 }
7184 
7185 const Instruction *
7186 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
7187                                        bool &Precise) {
7188   Precise = true;
7189   // Do a bounded search of the def relation of the requested SCEVs.
7190   SmallSet<const SCEV *, 16> Visited;
7191   SmallVector<const SCEV *> Worklist;
7192   auto pushOp = [&](const SCEV *S) {
7193     if (!Visited.insert(S).second)
7194       return;
7195     // Threshold of 30 here is arbitrary.
7196     if (Visited.size() > 30) {
7197       Precise = false;
7198       return;
7199     }
7200     Worklist.push_back(S);
7201   };
7202 
7203   for (const auto *S : Ops)
7204     pushOp(S);
7205 
7206   const Instruction *Bound = nullptr;
7207   while (!Worklist.empty()) {
7208     auto *S = Worklist.pop_back_val();
7209     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7210       if (!Bound || DT.dominates(Bound, DefI))
7211         Bound = DefI;
7212     } else {
7213       for (const auto *Op : S->operands())
7214         pushOp(Op);
7215     }
7216   }
7217   return Bound ? Bound : &*F.getEntryBlock().begin();
7218 }
7219 
7220 const Instruction *
7221 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7222   bool Discard;
7223   return getDefiningScopeBound(Ops, Discard);
7224 }
7225 
7226 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7227                                                         const Instruction *B) {
7228   if (A->getParent() == B->getParent() &&
7229       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7230                                                  B->getIterator()))
7231     return true;
7232 
7233   auto *BLoop = LI.getLoopFor(B->getParent());
7234   if (BLoop && BLoop->getHeader() == B->getParent() &&
7235       BLoop->getLoopPreheader() == A->getParent() &&
7236       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7237                                                  A->getParent()->end()) &&
7238       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7239                                                  B->getIterator()))
7240     return true;
7241   return false;
7242 }
7243 
7244 
7245 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7246   // Only proceed if we can prove that I does not yield poison.
7247   if (!programUndefinedIfPoison(I))
7248     return false;
7249 
7250   // At this point we know that if I is executed, then it does not wrap
7251   // according to at least one of NSW or NUW. If I is not executed, then we do
7252   // not know if the calculation that I represents would wrap. Multiple
7253   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7254   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7255   // derived from other instructions that map to the same SCEV. We cannot make
7256   // that guarantee for cases where I is not executed. So we need to find a
7257   // upper bound on the defining scope for the SCEV, and prove that I is
7258   // executed every time we enter that scope.  When the bounding scope is a
7259   // loop (the common case), this is equivalent to proving I executes on every
7260   // iteration of that loop.
7261   SmallVector<const SCEV *> SCEVOps;
7262   for (const Use &Op : I->operands()) {
7263     // I could be an extractvalue from a call to an overflow intrinsic.
7264     // TODO: We can do better here in some cases.
7265     if (isSCEVable(Op->getType()))
7266       SCEVOps.push_back(getSCEV(Op));
7267   }
7268   auto *DefI = getDefiningScopeBound(SCEVOps);
7269   return isGuaranteedToTransferExecutionTo(DefI, I);
7270 }
7271 
7272 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7273   // If we know that \c I can never be poison period, then that's enough.
7274   if (isSCEVExprNeverPoison(I))
7275     return true;
7276 
7277   // If the loop only has one exit, then we know that, if the loop is entered,
7278   // any instruction dominating that exit will be executed. If any such
7279   // instruction would result in UB, the addrec cannot be poison.
7280   //
7281   // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7282   // also handles uses outside the loop header (they just need to dominate the
7283   // single exit).
7284 
7285   auto *ExitingBB = L->getExitingBlock();
7286   if (!ExitingBB || !loopHasNoAbnormalExits(L))
7287     return false;
7288 
7289   SmallPtrSet<const Value *, 16> KnownPoison;
7290   SmallVector<const Instruction *, 8> Worklist;
7291 
7292   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
7293   // things that are known to be poison under that assumption go on the
7294   // Worklist.
7295   KnownPoison.insert(I);
7296   Worklist.push_back(I);
7297 
7298   while (!Worklist.empty()) {
7299     const Instruction *Poison = Worklist.pop_back_val();
7300 
7301     for (const Use &U : Poison->uses()) {
7302       const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7303       if (mustTriggerUB(PoisonUser, KnownPoison) &&
7304           DT.dominates(PoisonUser->getParent(), ExitingBB))
7305         return true;
7306 
7307       if (propagatesPoison(U) && L->contains(PoisonUser))
7308         if (KnownPoison.insert(PoisonUser).second)
7309           Worklist.push_back(PoisonUser);
7310     }
7311   }
7312 
7313   return false;
7314 }
7315 
7316 ScalarEvolution::LoopProperties
7317 ScalarEvolution::getLoopProperties(const Loop *L) {
7318   using LoopProperties = ScalarEvolution::LoopProperties;
7319 
7320   auto Itr = LoopPropertiesCache.find(L);
7321   if (Itr == LoopPropertiesCache.end()) {
7322     auto HasSideEffects = [](Instruction *I) {
7323       if (auto *SI = dyn_cast<StoreInst>(I))
7324         return !SI->isSimple();
7325 
7326       return I->mayThrow() || I->mayWriteToMemory();
7327     };
7328 
7329     LoopProperties LP = {/* HasNoAbnormalExits */ true,
7330                          /*HasNoSideEffects*/ true};
7331 
7332     for (auto *BB : L->getBlocks())
7333       for (auto &I : *BB) {
7334         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7335           LP.HasNoAbnormalExits = false;
7336         if (HasSideEffects(&I))
7337           LP.HasNoSideEffects = false;
7338         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7339           break; // We're already as pessimistic as we can get.
7340       }
7341 
7342     auto InsertPair = LoopPropertiesCache.insert({L, LP});
7343     assert(InsertPair.second && "We just checked!");
7344     Itr = InsertPair.first;
7345   }
7346 
7347   return Itr->second;
7348 }
7349 
7350 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7351   // A mustprogress loop without side effects must be finite.
7352   // TODO: The check used here is very conservative.  It's only *specific*
7353   // side effects which are well defined in infinite loops.
7354   return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7355 }
7356 
7357 const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7358   // Worklist item with a Value and a bool indicating whether all operands have
7359   // been visited already.
7360   using PointerTy = PointerIntPair<Value *, 1, bool>;
7361   SmallVector<PointerTy> Stack;
7362 
7363   Stack.emplace_back(V, true);
7364   Stack.emplace_back(V, false);
7365   while (!Stack.empty()) {
7366     auto E = Stack.pop_back_val();
7367     Value *CurV = E.getPointer();
7368 
7369     if (getExistingSCEV(CurV))
7370       continue;
7371 
7372     SmallVector<Value *> Ops;
7373     const SCEV *CreatedSCEV = nullptr;
7374     // If all operands have been visited already, create the SCEV.
7375     if (E.getInt()) {
7376       CreatedSCEV = createSCEV(CurV);
7377     } else {
7378       // Otherwise get the operands we need to create SCEV's for before creating
7379       // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7380       // just use it.
7381       CreatedSCEV = getOperandsToCreate(CurV, Ops);
7382     }
7383 
7384     if (CreatedSCEV) {
7385       insertValueToMap(CurV, CreatedSCEV);
7386     } else {
7387       // Queue CurV for SCEV creation, followed by its's operands which need to
7388       // be constructed first.
7389       Stack.emplace_back(CurV, true);
7390       for (Value *Op : Ops)
7391         Stack.emplace_back(Op, false);
7392     }
7393   }
7394 
7395   return getExistingSCEV(V);
7396 }
7397 
7398 const SCEV *
7399 ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7400   if (!isSCEVable(V->getType()))
7401     return getUnknown(V);
7402 
7403   if (Instruction *I = dyn_cast<Instruction>(V)) {
7404     // Don't attempt to analyze instructions in blocks that aren't
7405     // reachable. Such instructions don't matter, and they aren't required
7406     // to obey basic rules for definitions dominating uses which this
7407     // analysis depends on.
7408     if (!DT.isReachableFromEntry(I->getParent()))
7409       return getUnknown(PoisonValue::get(V->getType()));
7410   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7411     return getConstant(CI);
7412   else if (isa<GlobalAlias>(V))
7413     return getUnknown(V);
7414   else if (!isa<ConstantExpr>(V))
7415     return getUnknown(V);
7416 
7417   Operator *U = cast<Operator>(V);
7418   if (auto BO =
7419           MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7420     bool IsConstArg = isa<ConstantInt>(BO->RHS);
7421     switch (BO->Opcode) {
7422     case Instruction::Add:
7423     case Instruction::Mul: {
7424       // For additions and multiplications, traverse add/mul chains for which we
7425       // can potentially create a single SCEV, to reduce the number of
7426       // get{Add,Mul}Expr calls.
7427       do {
7428         if (BO->Op) {
7429           if (BO->Op != V && getExistingSCEV(BO->Op)) {
7430             Ops.push_back(BO->Op);
7431             break;
7432           }
7433         }
7434         Ops.push_back(BO->RHS);
7435         auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7436                                    dyn_cast<Instruction>(V));
7437         if (!NewBO ||
7438             (BO->Opcode == Instruction::Add &&
7439              (NewBO->Opcode != Instruction::Add &&
7440               NewBO->Opcode != Instruction::Sub)) ||
7441             (BO->Opcode == Instruction::Mul &&
7442              NewBO->Opcode != Instruction::Mul)) {
7443           Ops.push_back(BO->LHS);
7444           break;
7445         }
7446         // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7447         // requires a SCEV for the LHS.
7448         if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7449           auto *I = dyn_cast<Instruction>(BO->Op);
7450           if (I && programUndefinedIfPoison(I)) {
7451             Ops.push_back(BO->LHS);
7452             break;
7453           }
7454         }
7455         BO = NewBO;
7456       } while (true);
7457       return nullptr;
7458     }
7459     case Instruction::Sub:
7460     case Instruction::UDiv:
7461     case Instruction::URem:
7462       break;
7463     case Instruction::AShr:
7464     case Instruction::Shl:
7465     case Instruction::Xor:
7466       if (!IsConstArg)
7467         return nullptr;
7468       break;
7469     case Instruction::And:
7470     case Instruction::Or:
7471       if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7472         return nullptr;
7473       break;
7474     case Instruction::LShr:
7475       return getUnknown(V);
7476     default:
7477       llvm_unreachable("Unhandled binop");
7478       break;
7479     }
7480 
7481     Ops.push_back(BO->LHS);
7482     Ops.push_back(BO->RHS);
7483     return nullptr;
7484   }
7485 
7486   switch (U->getOpcode()) {
7487   case Instruction::Trunc:
7488   case Instruction::ZExt:
7489   case Instruction::SExt:
7490   case Instruction::PtrToInt:
7491     Ops.push_back(U->getOperand(0));
7492     return nullptr;
7493 
7494   case Instruction::BitCast:
7495     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7496       Ops.push_back(U->getOperand(0));
7497       return nullptr;
7498     }
7499     return getUnknown(V);
7500 
7501   case Instruction::SDiv:
7502   case Instruction::SRem:
7503     Ops.push_back(U->getOperand(0));
7504     Ops.push_back(U->getOperand(1));
7505     return nullptr;
7506 
7507   case Instruction::GetElementPtr:
7508     assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7509            "GEP source element type must be sized");
7510     for (Value *Index : U->operands())
7511       Ops.push_back(Index);
7512     return nullptr;
7513 
7514   case Instruction::IntToPtr:
7515     return getUnknown(V);
7516 
7517   case Instruction::PHI:
7518     // Keep constructing SCEVs' for phis recursively for now.
7519     return nullptr;
7520 
7521   case Instruction::Select: {
7522     // Check if U is a select that can be simplified to a SCEVUnknown.
7523     auto CanSimplifyToUnknown = [this, U]() {
7524       if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7525         return false;
7526 
7527       auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7528       if (!ICI)
7529         return false;
7530       Value *LHS = ICI->getOperand(0);
7531       Value *RHS = ICI->getOperand(1);
7532       if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7533           ICI->getPredicate() == CmpInst::ICMP_NE) {
7534         if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()))
7535           return true;
7536       } else if (getTypeSizeInBits(LHS->getType()) >
7537                  getTypeSizeInBits(U->getType()))
7538         return true;
7539       return false;
7540     };
7541     if (CanSimplifyToUnknown())
7542       return getUnknown(U);
7543 
7544     for (Value *Inc : U->operands())
7545       Ops.push_back(Inc);
7546     return nullptr;
7547     break;
7548   }
7549   case Instruction::Call:
7550   case Instruction::Invoke:
7551     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7552       Ops.push_back(RV);
7553       return nullptr;
7554     }
7555 
7556     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7557       switch (II->getIntrinsicID()) {
7558       case Intrinsic::abs:
7559         Ops.push_back(II->getArgOperand(0));
7560         return nullptr;
7561       case Intrinsic::umax:
7562       case Intrinsic::umin:
7563       case Intrinsic::smax:
7564       case Intrinsic::smin:
7565       case Intrinsic::usub_sat:
7566       case Intrinsic::uadd_sat:
7567         Ops.push_back(II->getArgOperand(0));
7568         Ops.push_back(II->getArgOperand(1));
7569         return nullptr;
7570       case Intrinsic::start_loop_iterations:
7571       case Intrinsic::annotation:
7572       case Intrinsic::ptr_annotation:
7573         Ops.push_back(II->getArgOperand(0));
7574         return nullptr;
7575       default:
7576         break;
7577       }
7578     }
7579     break;
7580   }
7581 
7582   return nullptr;
7583 }
7584 
7585 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7586   if (!isSCEVable(V->getType()))
7587     return getUnknown(V);
7588 
7589   if (Instruction *I = dyn_cast<Instruction>(V)) {
7590     // Don't attempt to analyze instructions in blocks that aren't
7591     // reachable. Such instructions don't matter, and they aren't required
7592     // to obey basic rules for definitions dominating uses which this
7593     // analysis depends on.
7594     if (!DT.isReachableFromEntry(I->getParent()))
7595       return getUnknown(PoisonValue::get(V->getType()));
7596   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7597     return getConstant(CI);
7598   else if (isa<GlobalAlias>(V))
7599     return getUnknown(V);
7600   else if (!isa<ConstantExpr>(V))
7601     return getUnknown(V);
7602 
7603   const SCEV *LHS;
7604   const SCEV *RHS;
7605 
7606   Operator *U = cast<Operator>(V);
7607   if (auto BO =
7608           MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7609     switch (BO->Opcode) {
7610     case Instruction::Add: {
7611       // The simple thing to do would be to just call getSCEV on both operands
7612       // and call getAddExpr with the result. However if we're looking at a
7613       // bunch of things all added together, this can be quite inefficient,
7614       // because it leads to N-1 getAddExpr calls for N ultimate operands.
7615       // Instead, gather up all the operands and make a single getAddExpr call.
7616       // LLVM IR canonical form means we need only traverse the left operands.
7617       SmallVector<const SCEV *, 4> AddOps;
7618       do {
7619         if (BO->Op) {
7620           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7621             AddOps.push_back(OpSCEV);
7622             break;
7623           }
7624 
7625           // If a NUW or NSW flag can be applied to the SCEV for this
7626           // addition, then compute the SCEV for this addition by itself
7627           // with a separate call to getAddExpr. We need to do that
7628           // instead of pushing the operands of the addition onto AddOps,
7629           // since the flags are only known to apply to this particular
7630           // addition - they may not apply to other additions that can be
7631           // formed with operands from AddOps.
7632           const SCEV *RHS = getSCEV(BO->RHS);
7633           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7634           if (Flags != SCEV::FlagAnyWrap) {
7635             const SCEV *LHS = getSCEV(BO->LHS);
7636             if (BO->Opcode == Instruction::Sub)
7637               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7638             else
7639               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7640             break;
7641           }
7642         }
7643 
7644         if (BO->Opcode == Instruction::Sub)
7645           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7646         else
7647           AddOps.push_back(getSCEV(BO->RHS));
7648 
7649         auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7650                                    dyn_cast<Instruction>(V));
7651         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7652                        NewBO->Opcode != Instruction::Sub)) {
7653           AddOps.push_back(getSCEV(BO->LHS));
7654           break;
7655         }
7656         BO = NewBO;
7657       } while (true);
7658 
7659       return getAddExpr(AddOps);
7660     }
7661 
7662     case Instruction::Mul: {
7663       SmallVector<const SCEV *, 4> MulOps;
7664       do {
7665         if (BO->Op) {
7666           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7667             MulOps.push_back(OpSCEV);
7668             break;
7669           }
7670 
7671           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7672           if (Flags != SCEV::FlagAnyWrap) {
7673             LHS = getSCEV(BO->LHS);
7674             RHS = getSCEV(BO->RHS);
7675             MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7676             break;
7677           }
7678         }
7679 
7680         MulOps.push_back(getSCEV(BO->RHS));
7681         auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7682                                    dyn_cast<Instruction>(V));
7683         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7684           MulOps.push_back(getSCEV(BO->LHS));
7685           break;
7686         }
7687         BO = NewBO;
7688       } while (true);
7689 
7690       return getMulExpr(MulOps);
7691     }
7692     case Instruction::UDiv:
7693       LHS = getSCEV(BO->LHS);
7694       RHS = getSCEV(BO->RHS);
7695       return getUDivExpr(LHS, RHS);
7696     case Instruction::URem:
7697       LHS = getSCEV(BO->LHS);
7698       RHS = getSCEV(BO->RHS);
7699       return getURemExpr(LHS, RHS);
7700     case Instruction::Sub: {
7701       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7702       if (BO->Op)
7703         Flags = getNoWrapFlagsFromUB(BO->Op);
7704       LHS = getSCEV(BO->LHS);
7705       RHS = getSCEV(BO->RHS);
7706       return getMinusSCEV(LHS, RHS, Flags);
7707     }
7708     case Instruction::And:
7709       // For an expression like x&255 that merely masks off the high bits,
7710       // use zext(trunc(x)) as the SCEV expression.
7711       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7712         if (CI->isZero())
7713           return getSCEV(BO->RHS);
7714         if (CI->isMinusOne())
7715           return getSCEV(BO->LHS);
7716         const APInt &A = CI->getValue();
7717 
7718         // Instcombine's ShrinkDemandedConstant may strip bits out of
7719         // constants, obscuring what would otherwise be a low-bits mask.
7720         // Use computeKnownBits to compute what ShrinkDemandedConstant
7721         // knew about to reconstruct a low-bits mask value.
7722         unsigned LZ = A.countl_zero();
7723         unsigned TZ = A.countr_zero();
7724         unsigned BitWidth = A.getBitWidth();
7725         KnownBits Known(BitWidth);
7726         computeKnownBits(BO->LHS, Known, getDataLayout(),
7727                          0, &AC, nullptr, &DT);
7728 
7729         APInt EffectiveMask =
7730             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7731         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7732           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7733           const SCEV *LHS = getSCEV(BO->LHS);
7734           const SCEV *ShiftedLHS = nullptr;
7735           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7736             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7737               // For an expression like (x * 8) & 8, simplify the multiply.
7738               unsigned MulZeros = OpC->getAPInt().countr_zero();
7739               unsigned GCD = std::min(MulZeros, TZ);
7740               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7741               SmallVector<const SCEV*, 4> MulOps;
7742               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7743               append_range(MulOps, LHSMul->operands().drop_front());
7744               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7745               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7746             }
7747           }
7748           if (!ShiftedLHS)
7749             ShiftedLHS = getUDivExpr(LHS, MulCount);
7750           return getMulExpr(
7751               getZeroExtendExpr(
7752                   getTruncateExpr(ShiftedLHS,
7753                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7754                   BO->LHS->getType()),
7755               MulCount);
7756         }
7757       }
7758       // Binary `and` is a bit-wise `umin`.
7759       if (BO->LHS->getType()->isIntegerTy(1)) {
7760         LHS = getSCEV(BO->LHS);
7761         RHS = getSCEV(BO->RHS);
7762         return getUMinExpr(LHS, RHS);
7763       }
7764       break;
7765 
7766     case Instruction::Or:
7767       // Binary `or` is a bit-wise `umax`.
7768       if (BO->LHS->getType()->isIntegerTy(1)) {
7769         LHS = getSCEV(BO->LHS);
7770         RHS = getSCEV(BO->RHS);
7771         return getUMaxExpr(LHS, RHS);
7772       }
7773       break;
7774 
7775     case Instruction::Xor:
7776       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7777         // If the RHS of xor is -1, then this is a not operation.
7778         if (CI->isMinusOne())
7779           return getNotSCEV(getSCEV(BO->LHS));
7780 
7781         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7782         // This is a variant of the check for xor with -1, and it handles
7783         // the case where instcombine has trimmed non-demanded bits out
7784         // of an xor with -1.
7785         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7786           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7787             if (LBO->getOpcode() == Instruction::And &&
7788                 LCI->getValue() == CI->getValue())
7789               if (const SCEVZeroExtendExpr *Z =
7790                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7791                 Type *UTy = BO->LHS->getType();
7792                 const SCEV *Z0 = Z->getOperand();
7793                 Type *Z0Ty = Z0->getType();
7794                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7795 
7796                 // If C is a low-bits mask, the zero extend is serving to
7797                 // mask off the high bits. Complement the operand and
7798                 // re-apply the zext.
7799                 if (CI->getValue().isMask(Z0TySize))
7800                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7801 
7802                 // If C is a single bit, it may be in the sign-bit position
7803                 // before the zero-extend. In this case, represent the xor
7804                 // using an add, which is equivalent, and re-apply the zext.
7805                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7806                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7807                     Trunc.isSignMask())
7808                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7809                                            UTy);
7810               }
7811       }
7812       break;
7813 
7814     case Instruction::Shl:
7815       // Turn shift left of a constant amount into a multiply.
7816       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7817         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7818 
7819         // If the shift count is not less than the bitwidth, the result of
7820         // the shift is undefined. Don't try to analyze it, because the
7821         // resolution chosen here may differ from the resolution chosen in
7822         // other parts of the compiler.
7823         if (SA->getValue().uge(BitWidth))
7824           break;
7825 
7826         // We can safely preserve the nuw flag in all cases. It's also safe to
7827         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7828         // requires special handling. It can be preserved as long as we're not
7829         // left shifting by bitwidth - 1.
7830         auto Flags = SCEV::FlagAnyWrap;
7831         if (BO->Op) {
7832           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7833           if ((MulFlags & SCEV::FlagNSW) &&
7834               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7835             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7836           if (MulFlags & SCEV::FlagNUW)
7837             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7838         }
7839 
7840         ConstantInt *X = ConstantInt::get(
7841             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7842         return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7843       }
7844       break;
7845 
7846     case Instruction::AShr:
7847       // AShr X, C, where C is a constant.
7848       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7849       if (!CI)
7850         break;
7851 
7852       Type *OuterTy = BO->LHS->getType();
7853       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7854       // If the shift count is not less than the bitwidth, the result of
7855       // the shift is undefined. Don't try to analyze it, because the
7856       // resolution chosen here may differ from the resolution chosen in
7857       // other parts of the compiler.
7858       if (CI->getValue().uge(BitWidth))
7859         break;
7860 
7861       if (CI->isZero())
7862         return getSCEV(BO->LHS); // shift by zero --> noop
7863 
7864       uint64_t AShrAmt = CI->getZExtValue();
7865       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7866 
7867       Operator *L = dyn_cast<Operator>(BO->LHS);
7868       const SCEV *AddTruncateExpr = nullptr;
7869       ConstantInt *ShlAmtCI = nullptr;
7870       const SCEV *AddConstant = nullptr;
7871 
7872       if (L && L->getOpcode() == Instruction::Add) {
7873         // X = Shl A, n
7874         // Y = Add X, c
7875         // Z = AShr Y, m
7876         // n, c and m are constants.
7877 
7878         Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
7879         ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
7880         if (LShift && LShift->getOpcode() == Instruction::Shl) {
7881           if (AddOperandCI) {
7882             const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
7883             ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
7884             // since we truncate to TruncTy, the AddConstant should be of the
7885             // same type, so create a new Constant with type same as TruncTy.
7886             // Also, the Add constant should be shifted right by AShr amount.
7887             APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
7888             AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
7889             // we model the expression as sext(add(trunc(A), c << n)), since the
7890             // sext(trunc) part is already handled below, we create a
7891             // AddExpr(TruncExp) which will be used later.
7892             AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7893           }
7894         }
7895       } else if (L && L->getOpcode() == Instruction::Shl) {
7896         // X = Shl A, n
7897         // Y = AShr X, m
7898         // Both n and m are constant.
7899 
7900         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7901         ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7902         AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7903       }
7904 
7905       if (AddTruncateExpr && ShlAmtCI) {
7906         // We can merge the two given cases into a single SCEV statement,
7907         // incase n = m, the mul expression will be 2^0, so it gets resolved to
7908         // a simpler case. The following code handles the two cases:
7909         //
7910         // 1) For a two-shift sext-inreg, i.e. n = m,
7911         //    use sext(trunc(x)) as the SCEV expression.
7912         //
7913         // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7914         //    expression. We already checked that ShlAmt < BitWidth, so
7915         //    the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7916         //    ShlAmt - AShrAmt < Amt.
7917         const APInt &ShlAmt = ShlAmtCI->getValue();
7918         if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
7919           APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7920                                           ShlAmtCI->getZExtValue() - AShrAmt);
7921           const SCEV *CompositeExpr =
7922               getMulExpr(AddTruncateExpr, getConstant(Mul));
7923           if (L->getOpcode() != Instruction::Shl)
7924             CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
7925 
7926           return getSignExtendExpr(CompositeExpr, OuterTy);
7927         }
7928       }
7929       break;
7930     }
7931   }
7932 
7933   switch (U->getOpcode()) {
7934   case Instruction::Trunc:
7935     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7936 
7937   case Instruction::ZExt:
7938     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7939 
7940   case Instruction::SExt:
7941     if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
7942                                 dyn_cast<Instruction>(V))) {
7943       // The NSW flag of a subtract does not always survive the conversion to
7944       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7945       // more likely to preserve NSW and allow later AddRec optimisations.
7946       //
7947       // NOTE: This is effectively duplicating this logic from getSignExtend:
7948       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7949       // but by that point the NSW information has potentially been lost.
7950       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7951         Type *Ty = U->getType();
7952         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7953         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7954         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7955       }
7956     }
7957     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7958 
7959   case Instruction::BitCast:
7960     // BitCasts are no-op casts so we just eliminate the cast.
7961     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7962       return getSCEV(U->getOperand(0));
7963     break;
7964 
7965   case Instruction::PtrToInt: {
7966     // Pointer to integer cast is straight-forward, so do model it.
7967     const SCEV *Op = getSCEV(U->getOperand(0));
7968     Type *DstIntTy = U->getType();
7969     // But only if effective SCEV (integer) type is wide enough to represent
7970     // all possible pointer values.
7971     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7972     if (isa<SCEVCouldNotCompute>(IntOp))
7973       return getUnknown(V);
7974     return IntOp;
7975   }
7976   case Instruction::IntToPtr:
7977     // Just don't deal with inttoptr casts.
7978     return getUnknown(V);
7979 
7980   case Instruction::SDiv:
7981     // If both operands are non-negative, this is just an udiv.
7982     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7983         isKnownNonNegative(getSCEV(U->getOperand(1))))
7984       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7985     break;
7986 
7987   case Instruction::SRem:
7988     // If both operands are non-negative, this is just an urem.
7989     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7990         isKnownNonNegative(getSCEV(U->getOperand(1))))
7991       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7992     break;
7993 
7994   case Instruction::GetElementPtr:
7995     return createNodeForGEP(cast<GEPOperator>(U));
7996 
7997   case Instruction::PHI:
7998     return createNodeForPHI(cast<PHINode>(U));
7999 
8000   case Instruction::Select:
8001     return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8002                                     U->getOperand(2));
8003 
8004   case Instruction::Call:
8005   case Instruction::Invoke:
8006     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8007       return getSCEV(RV);
8008 
8009     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8010       switch (II->getIntrinsicID()) {
8011       case Intrinsic::abs:
8012         return getAbsExpr(
8013             getSCEV(II->getArgOperand(0)),
8014             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8015       case Intrinsic::umax:
8016         LHS = getSCEV(II->getArgOperand(0));
8017         RHS = getSCEV(II->getArgOperand(1));
8018         return getUMaxExpr(LHS, RHS);
8019       case Intrinsic::umin:
8020         LHS = getSCEV(II->getArgOperand(0));
8021         RHS = getSCEV(II->getArgOperand(1));
8022         return getUMinExpr(LHS, RHS);
8023       case Intrinsic::smax:
8024         LHS = getSCEV(II->getArgOperand(0));
8025         RHS = getSCEV(II->getArgOperand(1));
8026         return getSMaxExpr(LHS, RHS);
8027       case Intrinsic::smin:
8028         LHS = getSCEV(II->getArgOperand(0));
8029         RHS = getSCEV(II->getArgOperand(1));
8030         return getSMinExpr(LHS, RHS);
8031       case Intrinsic::usub_sat: {
8032         const SCEV *X = getSCEV(II->getArgOperand(0));
8033         const SCEV *Y = getSCEV(II->getArgOperand(1));
8034         const SCEV *ClampedY = getUMinExpr(X, Y);
8035         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8036       }
8037       case Intrinsic::uadd_sat: {
8038         const SCEV *X = getSCEV(II->getArgOperand(0));
8039         const SCEV *Y = getSCEV(II->getArgOperand(1));
8040         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8041         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8042       }
8043       case Intrinsic::start_loop_iterations:
8044       case Intrinsic::annotation:
8045       case Intrinsic::ptr_annotation:
8046         // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8047         // just eqivalent to the first operand for SCEV purposes.
8048         return getSCEV(II->getArgOperand(0));
8049       case Intrinsic::vscale:
8050         return getVScale(II->getType());
8051       default:
8052         break;
8053       }
8054     }
8055     break;
8056   }
8057 
8058   return getUnknown(V);
8059 }
8060 
8061 //===----------------------------------------------------------------------===//
8062 //                   Iteration Count Computation Code
8063 //
8064 
8065 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
8066   if (isa<SCEVCouldNotCompute>(ExitCount))
8067     return getCouldNotCompute();
8068 
8069   auto *ExitCountType = ExitCount->getType();
8070   assert(ExitCountType->isIntegerTy());
8071   auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8072                                  1 + ExitCountType->getScalarSizeInBits());
8073   return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8074 }
8075 
8076 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
8077                                                        Type *EvalTy,
8078                                                        const Loop *L) {
8079   if (isa<SCEVCouldNotCompute>(ExitCount))
8080     return getCouldNotCompute();
8081 
8082   unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8083   unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8084 
8085   auto CanAddOneWithoutOverflow = [&]() {
8086     ConstantRange ExitCountRange =
8087       getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8088     if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8089       return true;
8090 
8091     return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8092                                          getMinusOne(ExitCount->getType()));
8093   };
8094 
8095   // If we need to zero extend the backedge count, check if we can add one to
8096   // it prior to zero extending without overflow. Provided this is safe, it
8097   // allows better simplification of the +1.
8098   if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8099     return getZeroExtendExpr(
8100         getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8101 
8102   // Get the total trip count from the count by adding 1.  This may wrap.
8103   return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8104 }
8105 
8106 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8107   if (!ExitCount)
8108     return 0;
8109 
8110   ConstantInt *ExitConst = ExitCount->getValue();
8111 
8112   // Guard against huge trip counts.
8113   if (ExitConst->getValue().getActiveBits() > 32)
8114     return 0;
8115 
8116   // In case of integer overflow, this returns 0, which is correct.
8117   return ((unsigned)ExitConst->getZExtValue()) + 1;
8118 }
8119 
8120 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
8121   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8122   return getConstantTripCount(ExitCount);
8123 }
8124 
8125 unsigned
8126 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
8127                                            const BasicBlock *ExitingBlock) {
8128   assert(ExitingBlock && "Must pass a non-null exiting block!");
8129   assert(L->isLoopExiting(ExitingBlock) &&
8130          "Exiting block must actually branch out of the loop!");
8131   const SCEVConstant *ExitCount =
8132       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8133   return getConstantTripCount(ExitCount);
8134 }
8135 
8136 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
8137   const auto *MaxExitCount =
8138       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
8139   return getConstantTripCount(MaxExitCount);
8140 }
8141 
8142 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
8143   SmallVector<BasicBlock *, 8> ExitingBlocks;
8144   L->getExitingBlocks(ExitingBlocks);
8145 
8146   std::optional<unsigned> Res;
8147   for (auto *ExitingBB : ExitingBlocks) {
8148     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8149     if (!Res)
8150       Res = Multiple;
8151     Res = (unsigned)std::gcd(*Res, Multiple);
8152   }
8153   return Res.value_or(1);
8154 }
8155 
8156 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8157                                                        const SCEV *ExitCount) {
8158   if (ExitCount == getCouldNotCompute())
8159     return 1;
8160 
8161   // Get the trip count
8162   const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8163 
8164   APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8165   // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8166   // the greatest power of 2 divisor less than 2^32.
8167   return Multiple.getActiveBits() > 32
8168              ? 1U << std::min((unsigned)31, Multiple.countTrailingZeros())
8169              : (unsigned)Multiple.zextOrTrunc(32).getZExtValue();
8170 }
8171 
8172 /// Returns the largest constant divisor of the trip count of this loop as a
8173 /// normal unsigned value, if possible. This means that the actual trip count is
8174 /// always a multiple of the returned value (don't forget the trip count could
8175 /// very well be zero as well!).
8176 ///
8177 /// Returns 1 if the trip count is unknown or not guaranteed to be the
8178 /// multiple of a constant (which is also the case if the trip count is simply
8179 /// constant, use getSmallConstantTripCount for that case), Will also return 1
8180 /// if the trip count is very large (>= 2^32).
8181 ///
8182 /// As explained in the comments for getSmallConstantTripCount, this assumes
8183 /// that control exits the loop via ExitingBlock.
8184 unsigned
8185 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8186                                               const BasicBlock *ExitingBlock) {
8187   assert(ExitingBlock && "Must pass a non-null exiting block!");
8188   assert(L->isLoopExiting(ExitingBlock) &&
8189          "Exiting block must actually branch out of the loop!");
8190   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8191   return getSmallConstantTripMultiple(L, ExitCount);
8192 }
8193 
8194 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
8195                                           const BasicBlock *ExitingBlock,
8196                                           ExitCountKind Kind) {
8197   switch (Kind) {
8198   case Exact:
8199     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8200   case SymbolicMaximum:
8201     return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8202   case ConstantMaximum:
8203     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8204   };
8205   llvm_unreachable("Invalid ExitCountKind!");
8206 }
8207 
8208 const SCEV *
8209 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
8210                                                  SmallVector<const SCEVPredicate *, 4> &Preds) {
8211   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8212 }
8213 
8214 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
8215                                                    ExitCountKind Kind) {
8216   switch (Kind) {
8217   case Exact:
8218     return getBackedgeTakenInfo(L).getExact(L, this);
8219   case ConstantMaximum:
8220     return getBackedgeTakenInfo(L).getConstantMax(this);
8221   case SymbolicMaximum:
8222     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8223   };
8224   llvm_unreachable("Invalid ExitCountKind!");
8225 }
8226 
8227 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
8228   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8229 }
8230 
8231 /// Push PHI nodes in the header of the given loop onto the given Worklist.
8232 static void PushLoopPHIs(const Loop *L,
8233                          SmallVectorImpl<Instruction *> &Worklist,
8234                          SmallPtrSetImpl<Instruction *> &Visited) {
8235   BasicBlock *Header = L->getHeader();
8236 
8237   // Push all Loop-header PHIs onto the Worklist stack.
8238   for (PHINode &PN : Header->phis())
8239     if (Visited.insert(&PN).second)
8240       Worklist.push_back(&PN);
8241 }
8242 
8243 const ScalarEvolution::BackedgeTakenInfo &
8244 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8245   auto &BTI = getBackedgeTakenInfo(L);
8246   if (BTI.hasFullInfo())
8247     return BTI;
8248 
8249   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8250 
8251   if (!Pair.second)
8252     return Pair.first->second;
8253 
8254   BackedgeTakenInfo Result =
8255       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8256 
8257   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8258 }
8259 
8260 ScalarEvolution::BackedgeTakenInfo &
8261 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8262   // Initially insert an invalid entry for this loop. If the insertion
8263   // succeeds, proceed to actually compute a backedge-taken count and
8264   // update the value. The temporary CouldNotCompute value tells SCEV
8265   // code elsewhere that it shouldn't attempt to request a new
8266   // backedge-taken count, which could result in infinite recursion.
8267   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8268       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8269   if (!Pair.second)
8270     return Pair.first->second;
8271 
8272   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8273   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8274   // must be cleared in this scope.
8275   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8276 
8277   // Now that we know more about the trip count for this loop, forget any
8278   // existing SCEV values for PHI nodes in this loop since they are only
8279   // conservative estimates made without the benefit of trip count
8280   // information. This invalidation is not necessary for correctness, and is
8281   // only done to produce more precise results.
8282   if (Result.hasAnyInfo()) {
8283     // Invalidate any expression using an addrec in this loop.
8284     SmallVector<const SCEV *, 8> ToForget;
8285     auto LoopUsersIt = LoopUsers.find(L);
8286     if (LoopUsersIt != LoopUsers.end())
8287       append_range(ToForget, LoopUsersIt->second);
8288     forgetMemoizedResults(ToForget);
8289 
8290     // Invalidate constant-evolved loop header phis.
8291     for (PHINode &PN : L->getHeader()->phis())
8292       ConstantEvolutionLoopExitValue.erase(&PN);
8293   }
8294 
8295   // Re-lookup the insert position, since the call to
8296   // computeBackedgeTakenCount above could result in a
8297   // recusive call to getBackedgeTakenInfo (on a different
8298   // loop), which would invalidate the iterator computed
8299   // earlier.
8300   return BackedgeTakenCounts.find(L)->second = std::move(Result);
8301 }
8302 
8303 void ScalarEvolution::forgetAllLoops() {
8304   // This method is intended to forget all info about loops. It should
8305   // invalidate caches as if the following happened:
8306   // - The trip counts of all loops have changed arbitrarily
8307   // - Every llvm::Value has been updated in place to produce a different
8308   // result.
8309   BackedgeTakenCounts.clear();
8310   PredicatedBackedgeTakenCounts.clear();
8311   BECountUsers.clear();
8312   LoopPropertiesCache.clear();
8313   ConstantEvolutionLoopExitValue.clear();
8314   ValueExprMap.clear();
8315   ValuesAtScopes.clear();
8316   ValuesAtScopesUsers.clear();
8317   LoopDispositions.clear();
8318   BlockDispositions.clear();
8319   UnsignedRanges.clear();
8320   SignedRanges.clear();
8321   ExprValueMap.clear();
8322   HasRecMap.clear();
8323   ConstantMultipleCache.clear();
8324   PredicatedSCEVRewrites.clear();
8325   FoldCache.clear();
8326   FoldCacheUser.clear();
8327 }
8328 void ScalarEvolution::visitAndClearUsers(
8329     SmallVectorImpl<Instruction *> &Worklist,
8330     SmallPtrSetImpl<Instruction *> &Visited,
8331     SmallVectorImpl<const SCEV *> &ToForget) {
8332   while (!Worklist.empty()) {
8333     Instruction *I = Worklist.pop_back_val();
8334     if (!isSCEVable(I->getType()))
8335       continue;
8336 
8337     ValueExprMapType::iterator It =
8338         ValueExprMap.find_as(static_cast<Value *>(I));
8339     if (It != ValueExprMap.end()) {
8340       eraseValueFromMap(It->first);
8341       ToForget.push_back(It->second);
8342       if (PHINode *PN = dyn_cast<PHINode>(I))
8343         ConstantEvolutionLoopExitValue.erase(PN);
8344     }
8345 
8346     PushDefUseChildren(I, Worklist, Visited);
8347   }
8348 }
8349 
8350 void ScalarEvolution::forgetLoop(const Loop *L) {
8351   SmallVector<const Loop *, 16> LoopWorklist(1, L);
8352   SmallVector<Instruction *, 32> Worklist;
8353   SmallPtrSet<Instruction *, 16> Visited;
8354   SmallVector<const SCEV *, 16> ToForget;
8355 
8356   // Iterate over all the loops and sub-loops to drop SCEV information.
8357   while (!LoopWorklist.empty()) {
8358     auto *CurrL = LoopWorklist.pop_back_val();
8359 
8360     // Drop any stored trip count value.
8361     forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8362     forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8363 
8364     // Drop information about predicated SCEV rewrites for this loop.
8365     for (auto I = PredicatedSCEVRewrites.begin();
8366          I != PredicatedSCEVRewrites.end();) {
8367       std::pair<const SCEV *, const Loop *> Entry = I->first;
8368       if (Entry.second == CurrL)
8369         PredicatedSCEVRewrites.erase(I++);
8370       else
8371         ++I;
8372     }
8373 
8374     auto LoopUsersItr = LoopUsers.find(CurrL);
8375     if (LoopUsersItr != LoopUsers.end()) {
8376       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8377                 LoopUsersItr->second.end());
8378     }
8379 
8380     // Drop information about expressions based on loop-header PHIs.
8381     PushLoopPHIs(CurrL, Worklist, Visited);
8382     visitAndClearUsers(Worklist, Visited, ToForget);
8383 
8384     LoopPropertiesCache.erase(CurrL);
8385     // Forget all contained loops too, to avoid dangling entries in the
8386     // ValuesAtScopes map.
8387     LoopWorklist.append(CurrL->begin(), CurrL->end());
8388   }
8389   forgetMemoizedResults(ToForget);
8390 }
8391 
8392 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8393   forgetLoop(L->getOutermostLoop());
8394 }
8395 
8396 void ScalarEvolution::forgetValue(Value *V) {
8397   Instruction *I = dyn_cast<Instruction>(V);
8398   if (!I) return;
8399 
8400   // Drop information about expressions based on loop-header PHIs.
8401   SmallVector<Instruction *, 16> Worklist;
8402   SmallPtrSet<Instruction *, 8> Visited;
8403   SmallVector<const SCEV *, 8> ToForget;
8404   Worklist.push_back(I);
8405   Visited.insert(I);
8406   visitAndClearUsers(Worklist, Visited, ToForget);
8407 
8408   forgetMemoizedResults(ToForget);
8409 }
8410 
8411 void ScalarEvolution::forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V) {
8412   if (!isSCEVable(V->getType()))
8413     return;
8414 
8415   // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8416   // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8417   // extra predecessor is added, this is no longer valid. Find all Unknowns and
8418   // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8419   if (const SCEV *S = getExistingSCEV(V)) {
8420     struct InvalidationRootCollector {
8421       Loop *L;
8422       SmallVector<const SCEV *, 8> Roots;
8423 
8424       InvalidationRootCollector(Loop *L) : L(L) {}
8425 
8426       bool follow(const SCEV *S) {
8427         if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8428           if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8429             if (L->contains(I))
8430               Roots.push_back(S);
8431         } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8432           if (L->contains(AddRec->getLoop()))
8433             Roots.push_back(S);
8434         }
8435         return true;
8436       }
8437       bool isDone() const { return false; }
8438     };
8439 
8440     InvalidationRootCollector C(L);
8441     visitAll(S, C);
8442     forgetMemoizedResults(C.Roots);
8443   }
8444 
8445   // Also perform the normal invalidation.
8446   forgetValue(V);
8447 }
8448 
8449 void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8450 
8451 void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
8452   // Unless a specific value is passed to invalidation, completely clear both
8453   // caches.
8454   if (!V) {
8455     BlockDispositions.clear();
8456     LoopDispositions.clear();
8457     return;
8458   }
8459 
8460   if (!isSCEVable(V->getType()))
8461     return;
8462 
8463   const SCEV *S = getExistingSCEV(V);
8464   if (!S)
8465     return;
8466 
8467   // Invalidate the block and loop dispositions cached for S. Dispositions of
8468   // S's users may change if S's disposition changes (i.e. a user may change to
8469   // loop-invariant, if S changes to loop invariant), so also invalidate
8470   // dispositions of S's users recursively.
8471   SmallVector<const SCEV *, 8> Worklist = {S};
8472   SmallPtrSet<const SCEV *, 8> Seen = {S};
8473   while (!Worklist.empty()) {
8474     const SCEV *Curr = Worklist.pop_back_val();
8475     bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8476     bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8477     if (!LoopDispoRemoved && !BlockDispoRemoved)
8478       continue;
8479     auto Users = SCEVUsers.find(Curr);
8480     if (Users != SCEVUsers.end())
8481       for (const auto *User : Users->second)
8482         if (Seen.insert(User).second)
8483           Worklist.push_back(User);
8484   }
8485 }
8486 
8487 /// Get the exact loop backedge taken count considering all loop exits. A
8488 /// computable result can only be returned for loops with all exiting blocks
8489 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8490 /// is never skipped. This is a valid assumption as long as the loop exits via
8491 /// that test. For precise results, it is the caller's responsibility to specify
8492 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8493 const SCEV *
8494 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8495                                              SmallVector<const SCEVPredicate *, 4> *Preds) const {
8496   // If any exits were not computable, the loop is not computable.
8497   if (!isComplete() || ExitNotTaken.empty())
8498     return SE->getCouldNotCompute();
8499 
8500   const BasicBlock *Latch = L->getLoopLatch();
8501   // All exiting blocks we have collected must dominate the only backedge.
8502   if (!Latch)
8503     return SE->getCouldNotCompute();
8504 
8505   // All exiting blocks we have gathered dominate loop's latch, so exact trip
8506   // count is simply a minimum out of all these calculated exit counts.
8507   SmallVector<const SCEV *, 2> Ops;
8508   for (const auto &ENT : ExitNotTaken) {
8509     const SCEV *BECount = ENT.ExactNotTaken;
8510     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8511     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8512            "We should only have known counts for exiting blocks that dominate "
8513            "latch!");
8514 
8515     Ops.push_back(BECount);
8516 
8517     if (Preds)
8518       for (const auto *P : ENT.Predicates)
8519         Preds->push_back(P);
8520 
8521     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8522            "Predicate should be always true!");
8523   }
8524 
8525   // If an earlier exit exits on the first iteration (exit count zero), then
8526   // a later poison exit count should not propagate into the result. This are
8527   // exactly the semantics provided by umin_seq.
8528   return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8529 }
8530 
8531 /// Get the exact not taken count for this loop exit.
8532 const SCEV *
8533 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8534                                              ScalarEvolution *SE) const {
8535   for (const auto &ENT : ExitNotTaken)
8536     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8537       return ENT.ExactNotTaken;
8538 
8539   return SE->getCouldNotCompute();
8540 }
8541 
8542 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8543     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8544   for (const auto &ENT : ExitNotTaken)
8545     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8546       return ENT.ConstantMaxNotTaken;
8547 
8548   return SE->getCouldNotCompute();
8549 }
8550 
8551 const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8552     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8553   for (const auto &ENT : ExitNotTaken)
8554     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8555       return ENT.SymbolicMaxNotTaken;
8556 
8557   return SE->getCouldNotCompute();
8558 }
8559 
8560 /// getConstantMax - Get the constant max backedge taken count for the loop.
8561 const SCEV *
8562 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8563   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8564     return !ENT.hasAlwaysTruePredicate();
8565   };
8566 
8567   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8568     return SE->getCouldNotCompute();
8569 
8570   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8571           isa<SCEVConstant>(getConstantMax())) &&
8572          "No point in having a non-constant max backedge taken count!");
8573   return getConstantMax();
8574 }
8575 
8576 const SCEV *
8577 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8578                                                    ScalarEvolution *SE) {
8579   if (!SymbolicMax)
8580     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8581   return SymbolicMax;
8582 }
8583 
8584 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8585     ScalarEvolution *SE) const {
8586   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8587     return !ENT.hasAlwaysTruePredicate();
8588   };
8589   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8590 }
8591 
8592 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8593     : ExitLimit(E, E, E, false, std::nullopt) {}
8594 
8595 ScalarEvolution::ExitLimit::ExitLimit(
8596     const SCEV *E, const SCEV *ConstantMaxNotTaken,
8597     const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8598     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8599     : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8600       SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8601   // If we prove the max count is zero, so is the symbolic bound.  This happens
8602   // in practice due to differences in a) how context sensitive we've chosen
8603   // to be and b) how we reason about bounds implied by UB.
8604   if (ConstantMaxNotTaken->isZero()) {
8605     this->ExactNotTaken = E = ConstantMaxNotTaken;
8606     this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8607   }
8608 
8609   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8610           !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8611          "Exact is not allowed to be less precise than Constant Max");
8612   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8613           !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
8614          "Exact is not allowed to be less precise than Symbolic Max");
8615   assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||
8616           !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8617          "Symbolic Max is not allowed to be less precise than Constant Max");
8618   assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8619           isa<SCEVConstant>(ConstantMaxNotTaken)) &&
8620          "No point in having a non-constant max backedge taken count!");
8621   for (const auto *PredSet : PredSetList)
8622     for (const auto *P : *PredSet)
8623       addPredicate(P);
8624   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8625          "Backedge count should be int");
8626   assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8627           !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8628          "Max backedge count should be int");
8629 }
8630 
8631 ScalarEvolution::ExitLimit::ExitLimit(
8632     const SCEV *E, const SCEV *ConstantMaxNotTaken,
8633     const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8634     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8635     : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8636                 { &PredSet }) {}
8637 
8638 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8639 /// computable exit into a persistent ExitNotTakenInfo array.
8640 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8641     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8642     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8643     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8644   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8645 
8646   ExitNotTaken.reserve(ExitCounts.size());
8647   std::transform(ExitCounts.begin(), ExitCounts.end(),
8648                  std::back_inserter(ExitNotTaken),
8649                  [&](const EdgeExitInfo &EEI) {
8650         BasicBlock *ExitBB = EEI.first;
8651         const ExitLimit &EL = EEI.second;
8652         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8653                                 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8654                                 EL.Predicates);
8655   });
8656   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8657           isa<SCEVConstant>(ConstantMax)) &&
8658          "No point in having a non-constant max backedge taken count!");
8659 }
8660 
8661 /// Compute the number of times the backedge of the specified loop will execute.
8662 ScalarEvolution::BackedgeTakenInfo
8663 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8664                                            bool AllowPredicates) {
8665   SmallVector<BasicBlock *, 8> ExitingBlocks;
8666   L->getExitingBlocks(ExitingBlocks);
8667 
8668   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8669 
8670   SmallVector<EdgeExitInfo, 4> ExitCounts;
8671   bool CouldComputeBECount = true;
8672   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8673   const SCEV *MustExitMaxBECount = nullptr;
8674   const SCEV *MayExitMaxBECount = nullptr;
8675   bool MustExitMaxOrZero = false;
8676 
8677   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8678   // and compute maxBECount.
8679   // Do a union of all the predicates here.
8680   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8681     BasicBlock *ExitBB = ExitingBlocks[i];
8682 
8683     // We canonicalize untaken exits to br (constant), ignore them so that
8684     // proving an exit untaken doesn't negatively impact our ability to reason
8685     // about the loop as whole.
8686     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8687       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8688         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8689         if (ExitIfTrue == CI->isZero())
8690           continue;
8691       }
8692 
8693     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8694 
8695     assert((AllowPredicates || EL.Predicates.empty()) &&
8696            "Predicated exit limit when predicates are not allowed!");
8697 
8698     // 1. For each exit that can be computed, add an entry to ExitCounts.
8699     // CouldComputeBECount is true only if all exits can be computed.
8700     if (EL.ExactNotTaken != getCouldNotCompute())
8701       ++NumExitCountsComputed;
8702     else
8703       // We couldn't compute an exact value for this exit, so
8704       // we won't be able to compute an exact value for the loop.
8705       CouldComputeBECount = false;
8706     // Remember exit count if either exact or symbolic is known. Because
8707     // Exact always implies symbolic, only check symbolic.
8708     if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8709       ExitCounts.emplace_back(ExitBB, EL);
8710     else {
8711       assert(EL.ExactNotTaken == getCouldNotCompute() &&
8712              "Exact is known but symbolic isn't?");
8713       ++NumExitCountsNotComputed;
8714     }
8715 
8716     // 2. Derive the loop's MaxBECount from each exit's max number of
8717     // non-exiting iterations. Partition the loop exits into two kinds:
8718     // LoopMustExits and LoopMayExits.
8719     //
8720     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8721     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8722     // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8723     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8724     // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8725     // any
8726     // computable EL.ConstantMaxNotTaken.
8727     if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8728         DT.dominates(ExitBB, Latch)) {
8729       if (!MustExitMaxBECount) {
8730         MustExitMaxBECount = EL.ConstantMaxNotTaken;
8731         MustExitMaxOrZero = EL.MaxOrZero;
8732       } else {
8733         MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8734                                                         EL.ConstantMaxNotTaken);
8735       }
8736     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8737       if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8738         MayExitMaxBECount = EL.ConstantMaxNotTaken;
8739       else {
8740         MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8741                                                        EL.ConstantMaxNotTaken);
8742       }
8743     }
8744   }
8745   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8746     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8747   // The loop backedge will be taken the maximum or zero times if there's
8748   // a single exit that must be taken the maximum or zero times.
8749   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8750 
8751   // Remember which SCEVs are used in exit limits for invalidation purposes.
8752   // We only care about non-constant SCEVs here, so we can ignore
8753   // EL.ConstantMaxNotTaken
8754   // and MaxBECount, which must be SCEVConstant.
8755   for (const auto &Pair : ExitCounts) {
8756     if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8757       BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8758     if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8759       BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8760           {L, AllowPredicates});
8761   }
8762   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8763                            MaxBECount, MaxOrZero);
8764 }
8765 
8766 ScalarEvolution::ExitLimit
8767 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8768                                       bool AllowPredicates) {
8769   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8770   // If our exiting block does not dominate the latch, then its connection with
8771   // loop's exit limit may be far from trivial.
8772   const BasicBlock *Latch = L->getLoopLatch();
8773   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8774     return getCouldNotCompute();
8775 
8776   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8777   Instruction *Term = ExitingBlock->getTerminator();
8778   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8779     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8780     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8781     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8782            "It should have one successor in loop and one exit block!");
8783     // Proceed to the next level to examine the exit condition expression.
8784     return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
8785                                     /*ControlsOnlyExit=*/IsOnlyExit,
8786                                     AllowPredicates);
8787   }
8788 
8789   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8790     // For switch, make sure that there is a single exit from the loop.
8791     BasicBlock *Exit = nullptr;
8792     for (auto *SBB : successors(ExitingBlock))
8793       if (!L->contains(SBB)) {
8794         if (Exit) // Multiple exit successors.
8795           return getCouldNotCompute();
8796         Exit = SBB;
8797       }
8798     assert(Exit && "Exiting block must have at least one exit");
8799     return computeExitLimitFromSingleExitSwitch(
8800         L, SI, Exit,
8801         /*ControlsOnlyExit=*/IsOnlyExit);
8802   }
8803 
8804   return getCouldNotCompute();
8805 }
8806 
8807 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8808     const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
8809     bool AllowPredicates) {
8810   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8811   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8812                                         ControlsOnlyExit, AllowPredicates);
8813 }
8814 
8815 std::optional<ScalarEvolution::ExitLimit>
8816 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8817                                       bool ExitIfTrue, bool ControlsOnlyExit,
8818                                       bool AllowPredicates) {
8819   (void)this->L;
8820   (void)this->ExitIfTrue;
8821   (void)this->AllowPredicates;
8822 
8823   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8824          this->AllowPredicates == AllowPredicates &&
8825          "Variance in assumed invariant key components!");
8826   auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
8827   if (Itr == TripCountMap.end())
8828     return std::nullopt;
8829   return Itr->second;
8830 }
8831 
8832 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8833                                              bool ExitIfTrue,
8834                                              bool ControlsOnlyExit,
8835                                              bool AllowPredicates,
8836                                              const ExitLimit &EL) {
8837   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8838          this->AllowPredicates == AllowPredicates &&
8839          "Variance in assumed invariant key components!");
8840 
8841   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
8842   assert(InsertResult.second && "Expected successful insertion!");
8843   (void)InsertResult;
8844   (void)ExitIfTrue;
8845 }
8846 
8847 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8848     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8849     bool ControlsOnlyExit, bool AllowPredicates) {
8850 
8851   if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
8852                                 AllowPredicates))
8853     return *MaybeEL;
8854 
8855   ExitLimit EL = computeExitLimitFromCondImpl(
8856       Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
8857   Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
8858   return EL;
8859 }
8860 
8861 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8862     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8863     bool ControlsOnlyExit, bool AllowPredicates) {
8864   // Handle BinOp conditions (And, Or).
8865   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8866           Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates))
8867     return *LimitFromBinOp;
8868 
8869   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8870   // Proceed to the next level to examine the icmp.
8871   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8872     ExitLimit EL =
8873         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
8874     if (EL.hasFullInfo() || !AllowPredicates)
8875       return EL;
8876 
8877     // Try again, but use SCEV predicates this time.
8878     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
8879                                     ControlsOnlyExit,
8880                                     /*AllowPredicates=*/true);
8881   }
8882 
8883   // Check for a constant condition. These are normally stripped out by
8884   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8885   // preserve the CFG and is temporarily leaving constant conditions
8886   // in place.
8887   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8888     if (ExitIfTrue == !CI->getZExtValue())
8889       // The backedge is always taken.
8890       return getCouldNotCompute();
8891     // The backedge is never taken.
8892     return getZero(CI->getType());
8893   }
8894 
8895   // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8896   // with a constant step, we can form an equivalent icmp predicate and figure
8897   // out how many iterations will be taken before we exit.
8898   const WithOverflowInst *WO;
8899   const APInt *C;
8900   if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8901       match(WO->getRHS(), m_APInt(C))) {
8902     ConstantRange NWR =
8903       ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8904                                            WO->getNoWrapKind());
8905     CmpInst::Predicate Pred;
8906     APInt NewRHSC, Offset;
8907     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8908     if (!ExitIfTrue)
8909       Pred = ICmpInst::getInversePredicate(Pred);
8910     auto *LHS = getSCEV(WO->getLHS());
8911     if (Offset != 0)
8912       LHS = getAddExpr(LHS, getConstant(Offset));
8913     auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8914                                        ControlsOnlyExit, AllowPredicates);
8915     if (EL.hasAnyInfo())
8916       return EL;
8917   }
8918 
8919   // If it's not an integer or pointer comparison then compute it the hard way.
8920   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8921 }
8922 
8923 std::optional<ScalarEvolution::ExitLimit>
8924 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8925     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8926     bool ControlsOnlyExit, bool AllowPredicates) {
8927   // Check if the controlling expression for this loop is an And or Or.
8928   Value *Op0, *Op1;
8929   bool IsAnd = false;
8930   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8931     IsAnd = true;
8932   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8933     IsAnd = false;
8934   else
8935     return std::nullopt;
8936 
8937   // EitherMayExit is true in these two cases:
8938   //   br (and Op0 Op1), loop, exit
8939   //   br (or  Op0 Op1), exit, loop
8940   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8941   ExitLimit EL0 = computeExitLimitFromCondCached(
8942       Cache, L, Op0, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
8943       AllowPredicates);
8944   ExitLimit EL1 = computeExitLimitFromCondCached(
8945       Cache, L, Op1, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
8946       AllowPredicates);
8947 
8948   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8949   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8950   if (isa<ConstantInt>(Op1))
8951     return Op1 == NeutralElement ? EL0 : EL1;
8952   if (isa<ConstantInt>(Op0))
8953     return Op0 == NeutralElement ? EL1 : EL0;
8954 
8955   const SCEV *BECount = getCouldNotCompute();
8956   const SCEV *ConstantMaxBECount = getCouldNotCompute();
8957   const SCEV *SymbolicMaxBECount = getCouldNotCompute();
8958   if (EitherMayExit) {
8959     bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
8960     // Both conditions must be same for the loop to continue executing.
8961     // Choose the less conservative count.
8962     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8963         EL1.ExactNotTaken != getCouldNotCompute()) {
8964       BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
8965                                            UseSequentialUMin);
8966     }
8967     if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
8968       ConstantMaxBECount = EL1.ConstantMaxNotTaken;
8969     else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
8970       ConstantMaxBECount = EL0.ConstantMaxNotTaken;
8971     else
8972       ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
8973                                                       EL1.ConstantMaxNotTaken);
8974     if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
8975       SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
8976     else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
8977       SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
8978     else
8979       SymbolicMaxBECount = getUMinFromMismatchedTypes(
8980           EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
8981   } else {
8982     // Both conditions must be same at the same time for the loop to exit.
8983     // For now, be conservative.
8984     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8985       BECount = EL0.ExactNotTaken;
8986   }
8987 
8988   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8989   // to be more aggressive when computing BECount than when computing
8990   // ConstantMaxBECount.  In these cases it is possible for EL0.ExactNotTaken
8991   // and
8992   // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
8993   // EL1.ConstantMaxNotTaken to not.
8994   if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
8995       !isa<SCEVCouldNotCompute>(BECount))
8996     ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
8997   if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
8998     SymbolicMaxBECount =
8999         isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9000   return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9001                    { &EL0.Predicates, &EL1.Predicates });
9002 }
9003 
9004 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9005     const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9006     bool AllowPredicates) {
9007   // If the condition was exit on true, convert the condition to exit on false
9008   ICmpInst::Predicate Pred;
9009   if (!ExitIfTrue)
9010     Pred = ExitCond->getPredicate();
9011   else
9012     Pred = ExitCond->getInversePredicate();
9013   const ICmpInst::Predicate OriginalPred = Pred;
9014 
9015   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9016   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9017 
9018   ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9019                                           AllowPredicates);
9020   if (EL.hasAnyInfo())
9021     return EL;
9022 
9023   auto *ExhaustiveCount =
9024       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9025 
9026   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9027     return ExhaustiveCount;
9028 
9029   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9030                                       ExitCond->getOperand(1), L, OriginalPred);
9031 }
9032 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9033     const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9034     bool ControlsOnlyExit, bool AllowPredicates) {
9035 
9036   // Try to evaluate any dependencies out of the loop.
9037   LHS = getSCEVAtScope(LHS, L);
9038   RHS = getSCEVAtScope(RHS, L);
9039 
9040   // At this point, we would like to compute how many iterations of the
9041   // loop the predicate will return true for these inputs.
9042   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9043     // If there is a loop-invariant, force it into the RHS.
9044     std::swap(LHS, RHS);
9045     Pred = ICmpInst::getSwappedPredicate(Pred);
9046   }
9047 
9048   bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9049                                loopIsFiniteByAssumption(L);
9050   // Simplify the operands before analyzing them.
9051   (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9052 
9053   // If we have a comparison of a chrec against a constant, try to use value
9054   // ranges to answer this query.
9055   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9056     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9057       if (AddRec->getLoop() == L) {
9058         // Form the constant range.
9059         ConstantRange CompRange =
9060             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9061 
9062         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9063         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9064       }
9065 
9066   // If this loop must exit based on this condition (or execute undefined
9067   // behaviour), and we can prove the test sequence produced must repeat
9068   // the same values on self-wrap of the IV, then we can infer that IV
9069   // doesn't self wrap because if it did, we'd have an infinite (undefined)
9070   // loop.
9071   if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9072     // TODO: We can peel off any functions which are invertible *in L*.  Loop
9073     // invariant terms are effectively constants for our purposes here.
9074     auto *InnerLHS = LHS;
9075     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9076       InnerLHS = ZExt->getOperand();
9077     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
9078       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
9079       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9080           StrideC && StrideC->getAPInt().isPowerOf2()) {
9081         auto Flags = AR->getNoWrapFlags();
9082         Flags = setFlags(Flags, SCEV::FlagNW);
9083         SmallVector<const SCEV*> Operands{AR->operands()};
9084         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9085         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9086       }
9087     }
9088   }
9089 
9090   switch (Pred) {
9091   case ICmpInst::ICMP_NE: {                     // while (X != Y)
9092     // Convert to: while (X-Y != 0)
9093     if (LHS->getType()->isPointerTy()) {
9094       LHS = getLosslessPtrToIntExpr(LHS);
9095       if (isa<SCEVCouldNotCompute>(LHS))
9096         return LHS;
9097     }
9098     if (RHS->getType()->isPointerTy()) {
9099       RHS = getLosslessPtrToIntExpr(RHS);
9100       if (isa<SCEVCouldNotCompute>(RHS))
9101         return RHS;
9102     }
9103     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9104                                 AllowPredicates);
9105     if (EL.hasAnyInfo())
9106       return EL;
9107     break;
9108   }
9109   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
9110     // Convert to: while (X-Y == 0)
9111     if (LHS->getType()->isPointerTy()) {
9112       LHS = getLosslessPtrToIntExpr(LHS);
9113       if (isa<SCEVCouldNotCompute>(LHS))
9114         return LHS;
9115     }
9116     if (RHS->getType()->isPointerTy()) {
9117       RHS = getLosslessPtrToIntExpr(RHS);
9118       if (isa<SCEVCouldNotCompute>(RHS))
9119         return RHS;
9120     }
9121     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9122     if (EL.hasAnyInfo()) return EL;
9123     break;
9124   }
9125   case ICmpInst::ICMP_SLE:
9126   case ICmpInst::ICMP_ULE:
9127     // Since the loop is finite, an invariant RHS cannot include the boundary
9128     // value, otherwise it would loop forever.
9129     if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9130         !isLoopInvariant(RHS, L))
9131       break;
9132     RHS = getAddExpr(getOne(RHS->getType()), RHS);
9133     [[fallthrough]];
9134   case ICmpInst::ICMP_SLT:
9135   case ICmpInst::ICMP_ULT: { // while (X < Y)
9136     bool IsSigned = ICmpInst::isSigned(Pred);
9137     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9138                                     AllowPredicates);
9139     if (EL.hasAnyInfo())
9140       return EL;
9141     break;
9142   }
9143   case ICmpInst::ICMP_SGE:
9144   case ICmpInst::ICMP_UGE:
9145     // Since the loop is finite, an invariant RHS cannot include the boundary
9146     // value, otherwise it would loop forever.
9147     if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9148         !isLoopInvariant(RHS, L))
9149       break;
9150     RHS = getAddExpr(getMinusOne(RHS->getType()), RHS);
9151     [[fallthrough]];
9152   case ICmpInst::ICMP_SGT:
9153   case ICmpInst::ICMP_UGT: { // while (X > Y)
9154     bool IsSigned = ICmpInst::isSigned(Pred);
9155     ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9156                                        AllowPredicates);
9157     if (EL.hasAnyInfo())
9158       return EL;
9159     break;
9160   }
9161   default:
9162     break;
9163   }
9164 
9165   return getCouldNotCompute();
9166 }
9167 
9168 ScalarEvolution::ExitLimit
9169 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9170                                                       SwitchInst *Switch,
9171                                                       BasicBlock *ExitingBlock,
9172                                                       bool ControlsOnlyExit) {
9173   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9174 
9175   // Give up if the exit is the default dest of a switch.
9176   if (Switch->getDefaultDest() == ExitingBlock)
9177     return getCouldNotCompute();
9178 
9179   assert(L->contains(Switch->getDefaultDest()) &&
9180          "Default case must not exit the loop!");
9181   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9182   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9183 
9184   // while (X != Y) --> while (X-Y != 0)
9185   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9186   if (EL.hasAnyInfo())
9187     return EL;
9188 
9189   return getCouldNotCompute();
9190 }
9191 
9192 static ConstantInt *
9193 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
9194                                 ScalarEvolution &SE) {
9195   const SCEV *InVal = SE.getConstant(C);
9196   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9197   assert(isa<SCEVConstant>(Val) &&
9198          "Evaluation of SCEV at constant didn't fold correctly?");
9199   return cast<SCEVConstant>(Val)->getValue();
9200 }
9201 
9202 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9203     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9204   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9205   if (!RHS)
9206     return getCouldNotCompute();
9207 
9208   const BasicBlock *Latch = L->getLoopLatch();
9209   if (!Latch)
9210     return getCouldNotCompute();
9211 
9212   const BasicBlock *Predecessor = L->getLoopPredecessor();
9213   if (!Predecessor)
9214     return getCouldNotCompute();
9215 
9216   // Return true if V is of the form "LHS `shift_op` <positive constant>".
9217   // Return LHS in OutLHS and shift_opt in OutOpCode.
9218   auto MatchPositiveShift =
9219       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
9220 
9221     using namespace PatternMatch;
9222 
9223     ConstantInt *ShiftAmt;
9224     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9225       OutOpCode = Instruction::LShr;
9226     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9227       OutOpCode = Instruction::AShr;
9228     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9229       OutOpCode = Instruction::Shl;
9230     else
9231       return false;
9232 
9233     return ShiftAmt->getValue().isStrictlyPositive();
9234   };
9235 
9236   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9237   //
9238   // loop:
9239   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9240   //   %iv.shifted = lshr i32 %iv, <positive constant>
9241   //
9242   // Return true on a successful match.  Return the corresponding PHI node (%iv
9243   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
9244   auto MatchShiftRecurrence =
9245       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
9246     std::optional<Instruction::BinaryOps> PostShiftOpCode;
9247 
9248     {
9249       Instruction::BinaryOps OpC;
9250       Value *V;
9251 
9252       // If we encounter a shift instruction, "peel off" the shift operation,
9253       // and remember that we did so.  Later when we inspect %iv's backedge
9254       // value, we will make sure that the backedge value uses the same
9255       // operation.
9256       //
9257       // Note: the peeled shift operation does not have to be the same
9258       // instruction as the one feeding into the PHI's backedge value.  We only
9259       // really care about it being the same *kind* of shift instruction --
9260       // that's all that is required for our later inferences to hold.
9261       if (MatchPositiveShift(LHS, V, OpC)) {
9262         PostShiftOpCode = OpC;
9263         LHS = V;
9264       }
9265     }
9266 
9267     PNOut = dyn_cast<PHINode>(LHS);
9268     if (!PNOut || PNOut->getParent() != L->getHeader())
9269       return false;
9270 
9271     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9272     Value *OpLHS;
9273 
9274     return
9275         // The backedge value for the PHI node must be a shift by a positive
9276         // amount
9277         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
9278 
9279         // of the PHI node itself
9280         OpLHS == PNOut &&
9281 
9282         // and the kind of shift should be match the kind of shift we peeled
9283         // off, if any.
9284         (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9285   };
9286 
9287   PHINode *PN;
9288   Instruction::BinaryOps OpCode;
9289   if (!MatchShiftRecurrence(LHS, PN, OpCode))
9290     return getCouldNotCompute();
9291 
9292   const DataLayout &DL = getDataLayout();
9293 
9294   // The key rationale for this optimization is that for some kinds of shift
9295   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9296   // within a finite number of iterations.  If the condition guarding the
9297   // backedge (in the sense that the backedge is taken if the condition is true)
9298   // is false for the value the shift recurrence stabilizes to, then we know
9299   // that the backedge is taken only a finite number of times.
9300 
9301   ConstantInt *StableValue = nullptr;
9302   switch (OpCode) {
9303   default:
9304     llvm_unreachable("Impossible case!");
9305 
9306   case Instruction::AShr: {
9307     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9308     // bitwidth(K) iterations.
9309     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9310     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
9311                                        Predecessor->getTerminator(), &DT);
9312     auto *Ty = cast<IntegerType>(RHS->getType());
9313     if (Known.isNonNegative())
9314       StableValue = ConstantInt::get(Ty, 0);
9315     else if (Known.isNegative())
9316       StableValue = ConstantInt::get(Ty, -1, true);
9317     else
9318       return getCouldNotCompute();
9319 
9320     break;
9321   }
9322   case Instruction::LShr:
9323   case Instruction::Shl:
9324     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9325     // stabilize to 0 in at most bitwidth(K) iterations.
9326     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9327     break;
9328   }
9329 
9330   auto *Result =
9331       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9332   assert(Result->getType()->isIntegerTy(1) &&
9333          "Otherwise cannot be an operand to a branch instruction");
9334 
9335   if (Result->isZeroValue()) {
9336     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9337     const SCEV *UpperBound =
9338         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
9339     return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9340   }
9341 
9342   return getCouldNotCompute();
9343 }
9344 
9345 /// Return true if we can constant fold an instruction of the specified type,
9346 /// assuming that all operands were constants.
9347 static bool CanConstantFold(const Instruction *I) {
9348   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
9349       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9350       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
9351     return true;
9352 
9353   if (const CallInst *CI = dyn_cast<CallInst>(I))
9354     if (const Function *F = CI->getCalledFunction())
9355       return canConstantFoldCallTo(CI, F);
9356   return false;
9357 }
9358 
9359 /// Determine whether this instruction can constant evolve within this loop
9360 /// assuming its operands can all constant evolve.
9361 static bool canConstantEvolve(Instruction *I, const Loop *L) {
9362   // An instruction outside of the loop can't be derived from a loop PHI.
9363   if (!L->contains(I)) return false;
9364 
9365   if (isa<PHINode>(I)) {
9366     // We don't currently keep track of the control flow needed to evaluate
9367     // PHIs, so we cannot handle PHIs inside of loops.
9368     return L->getHeader() == I->getParent();
9369   }
9370 
9371   // If we won't be able to constant fold this expression even if the operands
9372   // are constants, bail early.
9373   return CanConstantFold(I);
9374 }
9375 
9376 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9377 /// recursing through each instruction operand until reaching a loop header phi.
9378 static PHINode *
9379 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
9380                                DenseMap<Instruction *, PHINode *> &PHIMap,
9381                                unsigned Depth) {
9382   if (Depth > MaxConstantEvolvingDepth)
9383     return nullptr;
9384 
9385   // Otherwise, we can evaluate this instruction if all of its operands are
9386   // constant or derived from a PHI node themselves.
9387   PHINode *PHI = nullptr;
9388   for (Value *Op : UseInst->operands()) {
9389     if (isa<Constant>(Op)) continue;
9390 
9391     Instruction *OpInst = dyn_cast<Instruction>(Op);
9392     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9393 
9394     PHINode *P = dyn_cast<PHINode>(OpInst);
9395     if (!P)
9396       // If this operand is already visited, reuse the prior result.
9397       // We may have P != PHI if this is the deepest point at which the
9398       // inconsistent paths meet.
9399       P = PHIMap.lookup(OpInst);
9400     if (!P) {
9401       // Recurse and memoize the results, whether a phi is found or not.
9402       // This recursive call invalidates pointers into PHIMap.
9403       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9404       PHIMap[OpInst] = P;
9405     }
9406     if (!P)
9407       return nullptr;  // Not evolving from PHI
9408     if (PHI && PHI != P)
9409       return nullptr;  // Evolving from multiple different PHIs.
9410     PHI = P;
9411   }
9412   // This is a expression evolving from a constant PHI!
9413   return PHI;
9414 }
9415 
9416 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9417 /// in the loop that V is derived from.  We allow arbitrary operations along the
9418 /// way, but the operands of an operation must either be constants or a value
9419 /// derived from a constant PHI.  If this expression does not fit with these
9420 /// constraints, return null.
9421 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
9422   Instruction *I = dyn_cast<Instruction>(V);
9423   if (!I || !canConstantEvolve(I, L)) return nullptr;
9424 
9425   if (PHINode *PN = dyn_cast<PHINode>(I))
9426     return PN;
9427 
9428   // Record non-constant instructions contained by the loop.
9429   DenseMap<Instruction *, PHINode *> PHIMap;
9430   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9431 }
9432 
9433 /// EvaluateExpression - Given an expression that passes the
9434 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9435 /// in the loop has the value PHIVal.  If we can't fold this expression for some
9436 /// reason, return null.
9437 static Constant *EvaluateExpression(Value *V, const Loop *L,
9438                                     DenseMap<Instruction *, Constant *> &Vals,
9439                                     const DataLayout &DL,
9440                                     const TargetLibraryInfo *TLI) {
9441   // Convenient constant check, but redundant for recursive calls.
9442   if (Constant *C = dyn_cast<Constant>(V)) return C;
9443   Instruction *I = dyn_cast<Instruction>(V);
9444   if (!I) return nullptr;
9445 
9446   if (Constant *C = Vals.lookup(I)) return C;
9447 
9448   // An instruction inside the loop depends on a value outside the loop that we
9449   // weren't given a mapping for, or a value such as a call inside the loop.
9450   if (!canConstantEvolve(I, L)) return nullptr;
9451 
9452   // An unmapped PHI can be due to a branch or another loop inside this loop,
9453   // or due to this not being the initial iteration through a loop where we
9454   // couldn't compute the evolution of this particular PHI last time.
9455   if (isa<PHINode>(I)) return nullptr;
9456 
9457   std::vector<Constant*> Operands(I->getNumOperands());
9458 
9459   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9460     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9461     if (!Operand) {
9462       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9463       if (!Operands[i]) return nullptr;
9464       continue;
9465     }
9466     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9467     Vals[Operand] = C;
9468     if (!C) return nullptr;
9469     Operands[i] = C;
9470   }
9471 
9472   return ConstantFoldInstOperands(I, Operands, DL, TLI);
9473 }
9474 
9475 
9476 // If every incoming value to PN except the one for BB is a specific Constant,
9477 // return that, else return nullptr.
9478 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9479   Constant *IncomingVal = nullptr;
9480 
9481   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9482     if (PN->getIncomingBlock(i) == BB)
9483       continue;
9484 
9485     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9486     if (!CurrentVal)
9487       return nullptr;
9488 
9489     if (IncomingVal != CurrentVal) {
9490       if (IncomingVal)
9491         return nullptr;
9492       IncomingVal = CurrentVal;
9493     }
9494   }
9495 
9496   return IncomingVal;
9497 }
9498 
9499 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9500 /// in the header of its containing loop, we know the loop executes a
9501 /// constant number of times, and the PHI node is just a recurrence
9502 /// involving constants, fold it.
9503 Constant *
9504 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9505                                                    const APInt &BEs,
9506                                                    const Loop *L) {
9507   auto I = ConstantEvolutionLoopExitValue.find(PN);
9508   if (I != ConstantEvolutionLoopExitValue.end())
9509     return I->second;
9510 
9511   if (BEs.ugt(MaxBruteForceIterations))
9512     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
9513 
9514   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9515 
9516   DenseMap<Instruction *, Constant *> CurrentIterVals;
9517   BasicBlock *Header = L->getHeader();
9518   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9519 
9520   BasicBlock *Latch = L->getLoopLatch();
9521   if (!Latch)
9522     return nullptr;
9523 
9524   for (PHINode &PHI : Header->phis()) {
9525     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9526       CurrentIterVals[&PHI] = StartCST;
9527   }
9528   if (!CurrentIterVals.count(PN))
9529     return RetVal = nullptr;
9530 
9531   Value *BEValue = PN->getIncomingValueForBlock(Latch);
9532 
9533   // Execute the loop symbolically to determine the exit value.
9534   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9535          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9536 
9537   unsigned NumIterations = BEs.getZExtValue(); // must be in range
9538   unsigned IterationNum = 0;
9539   const DataLayout &DL = getDataLayout();
9540   for (; ; ++IterationNum) {
9541     if (IterationNum == NumIterations)
9542       return RetVal = CurrentIterVals[PN];  // Got exit value!
9543 
9544     // Compute the value of the PHIs for the next iteration.
9545     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9546     DenseMap<Instruction *, Constant *> NextIterVals;
9547     Constant *NextPHI =
9548         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9549     if (!NextPHI)
9550       return nullptr;        // Couldn't evaluate!
9551     NextIterVals[PN] = NextPHI;
9552 
9553     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9554 
9555     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
9556     // cease to be able to evaluate one of them or if they stop evolving,
9557     // because that doesn't necessarily prevent us from computing PN.
9558     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9559     for (const auto &I : CurrentIterVals) {
9560       PHINode *PHI = dyn_cast<PHINode>(I.first);
9561       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9562       PHIsToCompute.emplace_back(PHI, I.second);
9563     }
9564     // We use two distinct loops because EvaluateExpression may invalidate any
9565     // iterators into CurrentIterVals.
9566     for (const auto &I : PHIsToCompute) {
9567       PHINode *PHI = I.first;
9568       Constant *&NextPHI = NextIterVals[PHI];
9569       if (!NextPHI) {   // Not already computed.
9570         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9571         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9572       }
9573       if (NextPHI != I.second)
9574         StoppedEvolving = false;
9575     }
9576 
9577     // If all entries in CurrentIterVals == NextIterVals then we can stop
9578     // iterating, the loop can't continue to change.
9579     if (StoppedEvolving)
9580       return RetVal = CurrentIterVals[PN];
9581 
9582     CurrentIterVals.swap(NextIterVals);
9583   }
9584 }
9585 
9586 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9587                                                           Value *Cond,
9588                                                           bool ExitWhen) {
9589   PHINode *PN = getConstantEvolvingPHI(Cond, L);
9590   if (!PN) return getCouldNotCompute();
9591 
9592   // If the loop is canonicalized, the PHI will have exactly two entries.
9593   // That's the only form we support here.
9594   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9595 
9596   DenseMap<Instruction *, Constant *> CurrentIterVals;
9597   BasicBlock *Header = L->getHeader();
9598   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9599 
9600   BasicBlock *Latch = L->getLoopLatch();
9601   assert(Latch && "Should follow from NumIncomingValues == 2!");
9602 
9603   for (PHINode &PHI : Header->phis()) {
9604     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9605       CurrentIterVals[&PHI] = StartCST;
9606   }
9607   if (!CurrentIterVals.count(PN))
9608     return getCouldNotCompute();
9609 
9610   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
9611   // the loop symbolically to determine when the condition gets a value of
9612   // "ExitWhen".
9613   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
9614   const DataLayout &DL = getDataLayout();
9615   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9616     auto *CondVal = dyn_cast_or_null<ConstantInt>(
9617         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9618 
9619     // Couldn't symbolically evaluate.
9620     if (!CondVal) return getCouldNotCompute();
9621 
9622     if (CondVal->getValue() == uint64_t(ExitWhen)) {
9623       ++NumBruteForceTripCountsComputed;
9624       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9625     }
9626 
9627     // Update all the PHI nodes for the next iteration.
9628     DenseMap<Instruction *, Constant *> NextIterVals;
9629 
9630     // Create a list of which PHIs we need to compute. We want to do this before
9631     // calling EvaluateExpression on them because that may invalidate iterators
9632     // into CurrentIterVals.
9633     SmallVector<PHINode *, 8> PHIsToCompute;
9634     for (const auto &I : CurrentIterVals) {
9635       PHINode *PHI = dyn_cast<PHINode>(I.first);
9636       if (!PHI || PHI->getParent() != Header) continue;
9637       PHIsToCompute.push_back(PHI);
9638     }
9639     for (PHINode *PHI : PHIsToCompute) {
9640       Constant *&NextPHI = NextIterVals[PHI];
9641       if (NextPHI) continue;    // Already computed!
9642 
9643       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9644       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9645     }
9646     CurrentIterVals.swap(NextIterVals);
9647   }
9648 
9649   // Too many iterations were needed to evaluate.
9650   return getCouldNotCompute();
9651 }
9652 
9653 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9654   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9655       ValuesAtScopes[V];
9656   // Check to see if we've folded this expression at this loop before.
9657   for (auto &LS : Values)
9658     if (LS.first == L)
9659       return LS.second ? LS.second : V;
9660 
9661   Values.emplace_back(L, nullptr);
9662 
9663   // Otherwise compute it.
9664   const SCEV *C = computeSCEVAtScope(V, L);
9665   for (auto &LS : reverse(ValuesAtScopes[V]))
9666     if (LS.first == L) {
9667       LS.second = C;
9668       if (!isa<SCEVConstant>(C))
9669         ValuesAtScopesUsers[C].push_back({L, V});
9670       break;
9671     }
9672   return C;
9673 }
9674 
9675 /// This builds up a Constant using the ConstantExpr interface.  That way, we
9676 /// will return Constants for objects which aren't represented by a
9677 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9678 /// Returns NULL if the SCEV isn't representable as a Constant.
9679 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9680   switch (V->getSCEVType()) {
9681   case scCouldNotCompute:
9682   case scAddRecExpr:
9683   case scVScale:
9684     return nullptr;
9685   case scConstant:
9686     return cast<SCEVConstant>(V)->getValue();
9687   case scUnknown:
9688     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9689   case scPtrToInt: {
9690     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9691     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9692       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9693 
9694     return nullptr;
9695   }
9696   case scTruncate: {
9697     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9698     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9699       return ConstantExpr::getTrunc(CastOp, ST->getType());
9700     return nullptr;
9701   }
9702   case scAddExpr: {
9703     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9704     Constant *C = nullptr;
9705     for (const SCEV *Op : SA->operands()) {
9706       Constant *OpC = BuildConstantFromSCEV(Op);
9707       if (!OpC)
9708         return nullptr;
9709       if (!C) {
9710         C = OpC;
9711         continue;
9712       }
9713       assert(!C->getType()->isPointerTy() &&
9714              "Can only have one pointer, and it must be last");
9715       if (OpC->getType()->isPointerTy()) {
9716         // The offsets have been converted to bytes.  We can add bytes using
9717         // an i8 GEP.
9718         C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9719                                            OpC, C);
9720       } else {
9721         C = ConstantExpr::getAdd(C, OpC);
9722       }
9723     }
9724     return C;
9725   }
9726   case scMulExpr:
9727   case scSignExtend:
9728   case scZeroExtend:
9729   case scUDivExpr:
9730   case scSMaxExpr:
9731   case scUMaxExpr:
9732   case scSMinExpr:
9733   case scUMinExpr:
9734   case scSequentialUMinExpr:
9735     return nullptr;
9736   }
9737   llvm_unreachable("Unknown SCEV kind!");
9738 }
9739 
9740 const SCEV *
9741 ScalarEvolution::getWithOperands(const SCEV *S,
9742                                  SmallVectorImpl<const SCEV *> &NewOps) {
9743   switch (S->getSCEVType()) {
9744   case scTruncate:
9745   case scZeroExtend:
9746   case scSignExtend:
9747   case scPtrToInt:
9748     return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
9749   case scAddRecExpr: {
9750     auto *AddRec = cast<SCEVAddRecExpr>(S);
9751     return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
9752   }
9753   case scAddExpr:
9754     return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
9755   case scMulExpr:
9756     return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
9757   case scUDivExpr:
9758     return getUDivExpr(NewOps[0], NewOps[1]);
9759   case scUMaxExpr:
9760   case scSMaxExpr:
9761   case scUMinExpr:
9762   case scSMinExpr:
9763     return getMinMaxExpr(S->getSCEVType(), NewOps);
9764   case scSequentialUMinExpr:
9765     return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
9766   case scConstant:
9767   case scVScale:
9768   case scUnknown:
9769     return S;
9770   case scCouldNotCompute:
9771     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9772   }
9773   llvm_unreachable("Unknown SCEV kind!");
9774 }
9775 
9776 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9777   switch (V->getSCEVType()) {
9778   case scConstant:
9779   case scVScale:
9780     return V;
9781   case scAddRecExpr: {
9782     // If this is a loop recurrence for a loop that does not contain L, then we
9783     // are dealing with the final value computed by the loop.
9784     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
9785     // First, attempt to evaluate each operand.
9786     // Avoid performing the look-up in the common case where the specified
9787     // expression has no loop-variant portions.
9788     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9789       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9790       if (OpAtScope == AddRec->getOperand(i))
9791         continue;
9792 
9793       // Okay, at least one of these operands is loop variant but might be
9794       // foldable.  Build a new instance of the folded commutative expression.
9795       SmallVector<const SCEV *, 8> NewOps;
9796       NewOps.reserve(AddRec->getNumOperands());
9797       append_range(NewOps, AddRec->operands().take_front(i));
9798       NewOps.push_back(OpAtScope);
9799       for (++i; i != e; ++i)
9800         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9801 
9802       const SCEV *FoldedRec = getAddRecExpr(
9803           NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
9804       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9805       // The addrec may be folded to a nonrecurrence, for example, if the
9806       // induction variable is multiplied by zero after constant folding. Go
9807       // ahead and return the folded value.
9808       if (!AddRec)
9809         return FoldedRec;
9810       break;
9811     }
9812 
9813     // If the scope is outside the addrec's loop, evaluate it by using the
9814     // loop exit value of the addrec.
9815     if (!AddRec->getLoop()->contains(L)) {
9816       // To evaluate this recurrence, we need to know how many times the AddRec
9817       // loop iterates.  Compute this now.
9818       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9819       if (BackedgeTakenCount == getCouldNotCompute())
9820         return AddRec;
9821 
9822       // Then, evaluate the AddRec.
9823       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9824     }
9825 
9826     return AddRec;
9827   }
9828   case scTruncate:
9829   case scZeroExtend:
9830   case scSignExtend:
9831   case scPtrToInt:
9832   case scAddExpr:
9833   case scMulExpr:
9834   case scUDivExpr:
9835   case scUMaxExpr:
9836   case scSMaxExpr:
9837   case scUMinExpr:
9838   case scSMinExpr:
9839   case scSequentialUMinExpr: {
9840     ArrayRef<const SCEV *> Ops = V->operands();
9841     // Avoid performing the look-up in the common case where the specified
9842     // expression has no loop-variant portions.
9843     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
9844       const SCEV *OpAtScope = getSCEVAtScope(Ops[i], L);
9845       if (OpAtScope != Ops[i]) {
9846         // Okay, at least one of these operands is loop variant but might be
9847         // foldable.  Build a new instance of the folded commutative expression.
9848         SmallVector<const SCEV *, 8> NewOps;
9849         NewOps.reserve(Ops.size());
9850         append_range(NewOps, Ops.take_front(i));
9851         NewOps.push_back(OpAtScope);
9852 
9853         for (++i; i != e; ++i) {
9854           OpAtScope = getSCEVAtScope(Ops[i], L);
9855           NewOps.push_back(OpAtScope);
9856         }
9857 
9858         return getWithOperands(V, NewOps);
9859       }
9860     }
9861     // If we got here, all operands are loop invariant.
9862     return V;
9863   }
9864   case scUnknown: {
9865     // If this instruction is evolved from a constant-evolving PHI, compute the
9866     // exit value from the loop without using SCEVs.
9867     const SCEVUnknown *SU = cast<SCEVUnknown>(V);
9868     Instruction *I = dyn_cast<Instruction>(SU->getValue());
9869     if (!I)
9870       return V; // This is some other type of SCEVUnknown, just return it.
9871 
9872     if (PHINode *PN = dyn_cast<PHINode>(I)) {
9873       const Loop *CurrLoop = this->LI[I->getParent()];
9874       // Looking for loop exit value.
9875       if (CurrLoop && CurrLoop->getParentLoop() == L &&
9876           PN->getParent() == CurrLoop->getHeader()) {
9877         // Okay, there is no closed form solution for the PHI node.  Check
9878         // to see if the loop that contains it has a known backedge-taken
9879         // count.  If so, we may be able to force computation of the exit
9880         // value.
9881         const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9882         // This trivial case can show up in some degenerate cases where
9883         // the incoming IR has not yet been fully simplified.
9884         if (BackedgeTakenCount->isZero()) {
9885           Value *InitValue = nullptr;
9886           bool MultipleInitValues = false;
9887           for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9888             if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9889               if (!InitValue)
9890                 InitValue = PN->getIncomingValue(i);
9891               else if (InitValue != PN->getIncomingValue(i)) {
9892                 MultipleInitValues = true;
9893                 break;
9894               }
9895             }
9896           }
9897           if (!MultipleInitValues && InitValue)
9898             return getSCEV(InitValue);
9899         }
9900         // Do we have a loop invariant value flowing around the backedge
9901         // for a loop which must execute the backedge?
9902         if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9903             isKnownNonZero(BackedgeTakenCount) &&
9904             PN->getNumIncomingValues() == 2) {
9905 
9906           unsigned InLoopPred =
9907               CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9908           Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9909           if (CurrLoop->isLoopInvariant(BackedgeVal))
9910             return getSCEV(BackedgeVal);
9911         }
9912         if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9913           // Okay, we know how many times the containing loop executes.  If
9914           // this is a constant evolving PHI node, get the final value at
9915           // the specified iteration number.
9916           Constant *RV =
9917               getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
9918           if (RV)
9919             return getSCEV(RV);
9920         }
9921       }
9922     }
9923 
9924     // Okay, this is an expression that we cannot symbolically evaluate
9925     // into a SCEV.  Check to see if it's possible to symbolically evaluate
9926     // the arguments into constants, and if so, try to constant propagate the
9927     // result.  This is particularly useful for computing loop exit values.
9928     if (!CanConstantFold(I))
9929       return V; // This is some other type of SCEVUnknown, just return it.
9930 
9931     SmallVector<Constant *, 4> Operands;
9932     Operands.reserve(I->getNumOperands());
9933     bool MadeImprovement = false;
9934     for (Value *Op : I->operands()) {
9935       if (Constant *C = dyn_cast<Constant>(Op)) {
9936         Operands.push_back(C);
9937         continue;
9938       }
9939 
9940       // If any of the operands is non-constant and if they are
9941       // non-integer and non-pointer, don't even try to analyze them
9942       // with scev techniques.
9943       if (!isSCEVable(Op->getType()))
9944         return V;
9945 
9946       const SCEV *OrigV = getSCEV(Op);
9947       const SCEV *OpV = getSCEVAtScope(OrigV, L);
9948       MadeImprovement |= OrigV != OpV;
9949 
9950       Constant *C = BuildConstantFromSCEV(OpV);
9951       if (!C)
9952         return V;
9953       assert(C->getType() == Op->getType() && "Type mismatch");
9954       Operands.push_back(C);
9955     }
9956 
9957     // Check to see if getSCEVAtScope actually made an improvement.
9958     if (!MadeImprovement)
9959       return V; // This is some other type of SCEVUnknown, just return it.
9960 
9961     Constant *C = nullptr;
9962     const DataLayout &DL = getDataLayout();
9963     C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9964     if (!C)
9965       return V;
9966     return getSCEV(C);
9967   }
9968   case scCouldNotCompute:
9969     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9970   }
9971   llvm_unreachable("Unknown SCEV type!");
9972 }
9973 
9974 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9975   return getSCEVAtScope(getSCEV(V), L);
9976 }
9977 
9978 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9979   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9980     return stripInjectiveFunctions(ZExt->getOperand());
9981   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9982     return stripInjectiveFunctions(SExt->getOperand());
9983   return S;
9984 }
9985 
9986 /// Finds the minimum unsigned root of the following equation:
9987 ///
9988 ///     A * X = B (mod N)
9989 ///
9990 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9991 /// A and B isn't important.
9992 ///
9993 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9994 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9995                                                ScalarEvolution &SE) {
9996   uint32_t BW = A.getBitWidth();
9997   assert(BW == SE.getTypeSizeInBits(B->getType()));
9998   assert(A != 0 && "A must be non-zero.");
9999 
10000   // 1. D = gcd(A, N)
10001   //
10002   // The gcd of A and N may have only one prime factor: 2. The number of
10003   // trailing zeros in A is its multiplicity
10004   uint32_t Mult2 = A.countr_zero();
10005   // D = 2^Mult2
10006 
10007   // 2. Check if B is divisible by D.
10008   //
10009   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10010   // is not less than multiplicity of this prime factor for D.
10011   if (SE.getMinTrailingZeros(B) < Mult2)
10012     return SE.getCouldNotCompute();
10013 
10014   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10015   // modulo (N / D).
10016   //
10017   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10018   // (N / D) in general. The inverse itself always fits into BW bits, though,
10019   // so we immediately truncate it.
10020   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
10021   APInt Mod(BW + 1, 0);
10022   Mod.setBit(BW - Mult2);  // Mod = N / D
10023   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
10024 
10025   // 4. Compute the minimum unsigned root of the equation:
10026   // I * (B / D) mod (N / D)
10027   // To simplify the computation, we factor out the divide by D:
10028   // (I * B mod N) / D
10029   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10030   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10031 }
10032 
10033 /// For a given quadratic addrec, generate coefficients of the corresponding
10034 /// quadratic equation, multiplied by a common value to ensure that they are
10035 /// integers.
10036 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
10037 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10038 /// were multiplied by, and BitWidth is the bit width of the original addrec
10039 /// coefficients.
10040 /// This function returns std::nullopt if the addrec coefficients are not
10041 /// compile- time constants.
10042 static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10043 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
10044   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10045   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10046   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10047   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10048   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10049                     << *AddRec << '\n');
10050 
10051   // We currently can only solve this if the coefficients are constants.
10052   if (!LC || !MC || !NC) {
10053     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10054     return std::nullopt;
10055   }
10056 
10057   APInt L = LC->getAPInt();
10058   APInt M = MC->getAPInt();
10059   APInt N = NC->getAPInt();
10060   assert(!N.isZero() && "This is not a quadratic addrec");
10061 
10062   unsigned BitWidth = LC->getAPInt().getBitWidth();
10063   unsigned NewWidth = BitWidth + 1;
10064   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10065                     << BitWidth << '\n');
10066   // The sign-extension (as opposed to a zero-extension) here matches the
10067   // extension used in SolveQuadraticEquationWrap (with the same motivation).
10068   N = N.sext(NewWidth);
10069   M = M.sext(NewWidth);
10070   L = L.sext(NewWidth);
10071 
10072   // The increments are M, M+N, M+2N, ..., so the accumulated values are
10073   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10074   //   L+M, L+2M+N, L+3M+3N, ...
10075   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10076   //
10077   // The equation Acc = 0 is then
10078   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
10079   // In a quadratic form it becomes:
10080   //   N n^2 + (2M-N) n + 2L = 0.
10081 
10082   APInt A = N;
10083   APInt B = 2 * M - A;
10084   APInt C = 2 * L;
10085   APInt T = APInt(NewWidth, 2);
10086   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10087                     << "x + " << C << ", coeff bw: " << NewWidth
10088                     << ", multiplied by " << T << '\n');
10089   return std::make_tuple(A, B, C, T, BitWidth);
10090 }
10091 
10092 /// Helper function to compare optional APInts:
10093 /// (a) if X and Y both exist, return min(X, Y),
10094 /// (b) if neither X nor Y exist, return std::nullopt,
10095 /// (c) if exactly one of X and Y exists, return that value.
10096 static std::optional<APInt> MinOptional(std::optional<APInt> X,
10097                                         std::optional<APInt> Y) {
10098   if (X && Y) {
10099     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10100     APInt XW = X->sext(W);
10101     APInt YW = Y->sext(W);
10102     return XW.slt(YW) ? *X : *Y;
10103   }
10104   if (!X && !Y)
10105     return std::nullopt;
10106   return X ? *X : *Y;
10107 }
10108 
10109 /// Helper function to truncate an optional APInt to a given BitWidth.
10110 /// When solving addrec-related equations, it is preferable to return a value
10111 /// that has the same bit width as the original addrec's coefficients. If the
10112 /// solution fits in the original bit width, truncate it (except for i1).
10113 /// Returning a value of a different bit width may inhibit some optimizations.
10114 ///
10115 /// In general, a solution to a quadratic equation generated from an addrec
10116 /// may require BW+1 bits, where BW is the bit width of the addrec's
10117 /// coefficients. The reason is that the coefficients of the quadratic
10118 /// equation are BW+1 bits wide (to avoid truncation when converting from
10119 /// the addrec to the equation).
10120 static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10121                                             unsigned BitWidth) {
10122   if (!X)
10123     return std::nullopt;
10124   unsigned W = X->getBitWidth();
10125   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
10126     return X->trunc(BitWidth);
10127   return X;
10128 }
10129 
10130 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10131 /// iterations. The values L, M, N are assumed to be signed, and they
10132 /// should all have the same bit widths.
10133 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10134 /// where BW is the bit width of the addrec's coefficients.
10135 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
10136 /// returned as such, otherwise the bit width of the returned value may
10137 /// be greater than BW.
10138 ///
10139 /// This function returns std::nullopt if
10140 /// (a) the addrec coefficients are not constant, or
10141 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10142 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
10143 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10144 static std::optional<APInt>
10145 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
10146   APInt A, B, C, M;
10147   unsigned BitWidth;
10148   auto T = GetQuadraticEquation(AddRec);
10149   if (!T)
10150     return std::nullopt;
10151 
10152   std::tie(A, B, C, M, BitWidth) = *T;
10153   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10154   std::optional<APInt> X =
10155       APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth + 1);
10156   if (!X)
10157     return std::nullopt;
10158 
10159   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10160   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10161   if (!V->isZero())
10162     return std::nullopt;
10163 
10164   return TruncIfPossible(X, BitWidth);
10165 }
10166 
10167 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10168 /// iterations. The values M, N are assumed to be signed, and they
10169 /// should all have the same bit widths.
10170 /// Find the least n such that c(n) does not belong to the given range,
10171 /// while c(n-1) does.
10172 ///
10173 /// This function returns std::nullopt if
10174 /// (a) the addrec coefficients are not constant, or
10175 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10176 ///     bounds of the range.
10177 static std::optional<APInt>
10178 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
10179                           const ConstantRange &Range, ScalarEvolution &SE) {
10180   assert(AddRec->getOperand(0)->isZero() &&
10181          "Starting value of addrec should be 0");
10182   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10183                     << Range << ", addrec " << *AddRec << '\n');
10184   // This case is handled in getNumIterationsInRange. Here we can assume that
10185   // we start in the range.
10186   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10187          "Addrec's initial value should be in range");
10188 
10189   APInt A, B, C, M;
10190   unsigned BitWidth;
10191   auto T = GetQuadraticEquation(AddRec);
10192   if (!T)
10193     return std::nullopt;
10194 
10195   // Be careful about the return value: there can be two reasons for not
10196   // returning an actual number. First, if no solutions to the equations
10197   // were found, and second, if the solutions don't leave the given range.
10198   // The first case means that the actual solution is "unknown", the second
10199   // means that it's known, but not valid. If the solution is unknown, we
10200   // cannot make any conclusions.
10201   // Return a pair: the optional solution and a flag indicating if the
10202   // solution was found.
10203   auto SolveForBoundary =
10204       [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10205     // Solve for signed overflow and unsigned overflow, pick the lower
10206     // solution.
10207     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10208                       << Bound << " (before multiplying by " << M << ")\n");
10209     Bound *= M; // The quadratic equation multiplier.
10210 
10211     std::optional<APInt> SO;
10212     if (BitWidth > 1) {
10213       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10214                            "signed overflow\n");
10215       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
10216     }
10217     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10218                          "unsigned overflow\n");
10219     std::optional<APInt> UO =
10220         APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth + 1);
10221 
10222     auto LeavesRange = [&] (const APInt &X) {
10223       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10224       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10225       if (Range.contains(V0->getValue()))
10226         return false;
10227       // X should be at least 1, so X-1 is non-negative.
10228       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10229       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
10230       if (Range.contains(V1->getValue()))
10231         return true;
10232       return false;
10233     };
10234 
10235     // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10236     // can be a solution, but the function failed to find it. We cannot treat it
10237     // as "no solution".
10238     if (!SO || !UO)
10239       return {std::nullopt, false};
10240 
10241     // Check the smaller value first to see if it leaves the range.
10242     // At this point, both SO and UO must have values.
10243     std::optional<APInt> Min = MinOptional(SO, UO);
10244     if (LeavesRange(*Min))
10245       return { Min, true };
10246     std::optional<APInt> Max = Min == SO ? UO : SO;
10247     if (LeavesRange(*Max))
10248       return { Max, true };
10249 
10250     // Solutions were found, but were eliminated, hence the "true".
10251     return {std::nullopt, true};
10252   };
10253 
10254   std::tie(A, B, C, M, BitWidth) = *T;
10255   // Lower bound is inclusive, subtract 1 to represent the exiting value.
10256   APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10257   APInt Upper = Range.getUpper().sext(A.getBitWidth());
10258   auto SL = SolveForBoundary(Lower);
10259   auto SU = SolveForBoundary(Upper);
10260   // If any of the solutions was unknown, no meaninigful conclusions can
10261   // be made.
10262   if (!SL.second || !SU.second)
10263     return std::nullopt;
10264 
10265   // Claim: The correct solution is not some value between Min and Max.
10266   //
10267   // Justification: Assuming that Min and Max are different values, one of
10268   // them is when the first signed overflow happens, the other is when the
10269   // first unsigned overflow happens. Crossing the range boundary is only
10270   // possible via an overflow (treating 0 as a special case of it, modeling
10271   // an overflow as crossing k*2^W for some k).
10272   //
10273   // The interesting case here is when Min was eliminated as an invalid
10274   // solution, but Max was not. The argument is that if there was another
10275   // overflow between Min and Max, it would also have been eliminated if
10276   // it was considered.
10277   //
10278   // For a given boundary, it is possible to have two overflows of the same
10279   // type (signed/unsigned) without having the other type in between: this
10280   // can happen when the vertex of the parabola is between the iterations
10281   // corresponding to the overflows. This is only possible when the two
10282   // overflows cross k*2^W for the same k. In such case, if the second one
10283   // left the range (and was the first one to do so), the first overflow
10284   // would have to enter the range, which would mean that either we had left
10285   // the range before or that we started outside of it. Both of these cases
10286   // are contradictions.
10287   //
10288   // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10289   // solution is not some value between the Max for this boundary and the
10290   // Min of the other boundary.
10291   //
10292   // Justification: Assume that we had such Max_A and Min_B corresponding
10293   // to range boundaries A and B and such that Max_A < Min_B. If there was
10294   // a solution between Max_A and Min_B, it would have to be caused by an
10295   // overflow corresponding to either A or B. It cannot correspond to B,
10296   // since Min_B is the first occurrence of such an overflow. If it
10297   // corresponded to A, it would have to be either a signed or an unsigned
10298   // overflow that is larger than both eliminated overflows for A. But
10299   // between the eliminated overflows and this overflow, the values would
10300   // cover the entire value space, thus crossing the other boundary, which
10301   // is a contradiction.
10302 
10303   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10304 }
10305 
10306 ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10307                                                          const Loop *L,
10308                                                          bool ControlsOnlyExit,
10309                                                          bool AllowPredicates) {
10310 
10311   // This is only used for loops with a "x != y" exit test. The exit condition
10312   // is now expressed as a single expression, V = x-y. So the exit test is
10313   // effectively V != 0.  We know and take advantage of the fact that this
10314   // expression only being used in a comparison by zero context.
10315 
10316   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10317   // If the value is a constant
10318   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10319     // If the value is already zero, the branch will execute zero times.
10320     if (C->getValue()->isZero()) return C;
10321     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10322   }
10323 
10324   const SCEVAddRecExpr *AddRec =
10325       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10326 
10327   if (!AddRec && AllowPredicates)
10328     // Try to make this an AddRec using runtime tests, in the first X
10329     // iterations of this loop, where X is the SCEV expression found by the
10330     // algorithm below.
10331     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10332 
10333   if (!AddRec || AddRec->getLoop() != L)
10334     return getCouldNotCompute();
10335 
10336   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10337   // the quadratic equation to solve it.
10338   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10339     // We can only use this value if the chrec ends up with an exact zero
10340     // value at this index.  When solving for "X*X != 5", for example, we
10341     // should not accept a root of 2.
10342     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10343       const auto *R = cast<SCEVConstant>(getConstant(*S));
10344       return ExitLimit(R, R, R, false, Predicates);
10345     }
10346     return getCouldNotCompute();
10347   }
10348 
10349   // Otherwise we can only handle this if it is affine.
10350   if (!AddRec->isAffine())
10351     return getCouldNotCompute();
10352 
10353   // If this is an affine expression, the execution count of this branch is
10354   // the minimum unsigned root of the following equation:
10355   //
10356   //     Start + Step*N = 0 (mod 2^BW)
10357   //
10358   // equivalent to:
10359   //
10360   //             Step*N = -Start (mod 2^BW)
10361   //
10362   // where BW is the common bit width of Start and Step.
10363 
10364   // Get the initial value for the loop.
10365   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10366   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10367 
10368   // For now we handle only constant steps.
10369   //
10370   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
10371   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
10372   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
10373   // We have not yet seen any such cases.
10374   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10375   if (!StepC || StepC->getValue()->isZero())
10376     return getCouldNotCompute();
10377 
10378   // For positive steps (counting up until unsigned overflow):
10379   //   N = -Start/Step (as unsigned)
10380   // For negative steps (counting down to zero):
10381   //   N = Start/-Step
10382   // First compute the unsigned distance from zero in the direction of Step.
10383   bool CountDown = StepC->getAPInt().isNegative();
10384   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10385 
10386   // Handle unitary steps, which cannot wraparound.
10387   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10388   //   N = Distance (as unsigned)
10389   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
10390     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
10391     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10392 
10393     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10394     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
10395     // case, and see if we can improve the bound.
10396     //
10397     // Explicitly handling this here is necessary because getUnsignedRange
10398     // isn't context-sensitive; it doesn't know that we only care about the
10399     // range inside the loop.
10400     const SCEV *Zero = getZero(Distance->getType());
10401     const SCEV *One = getOne(Distance->getType());
10402     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10403     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10404       // If Distance + 1 doesn't overflow, we can compute the maximum distance
10405       // as "unsigned_max(Distance + 1) - 1".
10406       ConstantRange CR = getUnsignedRange(DistancePlusOne);
10407       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10408     }
10409     return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10410                      Predicates);
10411   }
10412 
10413   // If the condition controls loop exit (the loop exits only if the expression
10414   // is true) and the addition is no-wrap we can use unsigned divide to
10415   // compute the backedge count.  In this case, the step may not divide the
10416   // distance, but we don't care because if the condition is "missed" the loop
10417   // will have undefined behavior due to wrapping.
10418   if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10419       loopHasNoAbnormalExits(AddRec->getLoop())) {
10420     const SCEV *Exact =
10421         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10422     const SCEV *ConstantMax = getCouldNotCompute();
10423     if (Exact != getCouldNotCompute()) {
10424       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10425       ConstantMax =
10426           getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10427     }
10428     const SCEV *SymbolicMax =
10429         isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10430     return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10431   }
10432 
10433   // Solve the general equation.
10434   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10435                                                getNegativeSCEV(Start), *this);
10436 
10437   const SCEV *M = E;
10438   if (E != getCouldNotCompute()) {
10439     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10440     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10441   }
10442   auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10443   return ExitLimit(E, M, S, false, Predicates);
10444 }
10445 
10446 ScalarEvolution::ExitLimit
10447 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10448   // Loops that look like: while (X == 0) are very strange indeed.  We don't
10449   // handle them yet except for the trivial case.  This could be expanded in the
10450   // future as needed.
10451 
10452   // If the value is a constant, check to see if it is known to be non-zero
10453   // already.  If so, the backedge will execute zero times.
10454   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10455     if (!C->getValue()->isZero())
10456       return getZero(C->getType());
10457     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10458   }
10459 
10460   // We could implement others, but I really doubt anyone writes loops like
10461   // this, and if they did, they would already be constant folded.
10462   return getCouldNotCompute();
10463 }
10464 
10465 std::pair<const BasicBlock *, const BasicBlock *>
10466 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10467     const {
10468   // If the block has a unique predecessor, then there is no path from the
10469   // predecessor to the block that does not go through the direct edge
10470   // from the predecessor to the block.
10471   if (const BasicBlock *Pred = BB->getSinglePredecessor())
10472     return {Pred, BB};
10473 
10474   // A loop's header is defined to be a block that dominates the loop.
10475   // If the header has a unique predecessor outside the loop, it must be
10476   // a block that has exactly one successor that can reach the loop.
10477   if (const Loop *L = LI.getLoopFor(BB))
10478     return {L->getLoopPredecessor(), L->getHeader()};
10479 
10480   return {nullptr, nullptr};
10481 }
10482 
10483 /// SCEV structural equivalence is usually sufficient for testing whether two
10484 /// expressions are equal, however for the purposes of looking for a condition
10485 /// guarding a loop, it can be useful to be a little more general, since a
10486 /// front-end may have replicated the controlling expression.
10487 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10488   // Quick check to see if they are the same SCEV.
10489   if (A == B) return true;
10490 
10491   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10492     // Not all instructions that are "identical" compute the same value.  For
10493     // instance, two distinct alloca instructions allocating the same type are
10494     // identical and do not read memory; but compute distinct values.
10495     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10496   };
10497 
10498   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10499   // two different instructions with the same value. Check for this case.
10500   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10501     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10502       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10503         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10504           if (ComputesEqualValues(AI, BI))
10505             return true;
10506 
10507   // Otherwise assume they may have a different value.
10508   return false;
10509 }
10510 
10511 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10512                                            const SCEV *&LHS, const SCEV *&RHS,
10513                                            unsigned Depth) {
10514   bool Changed = false;
10515   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10516   // '0 != 0'.
10517   auto TrivialCase = [&](bool TriviallyTrue) {
10518     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10519     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10520     return true;
10521   };
10522   // If we hit the max recursion limit bail out.
10523   if (Depth >= 3)
10524     return false;
10525 
10526   // Canonicalize a constant to the right side.
10527   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10528     // Check for both operands constant.
10529     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10530       if (ConstantExpr::getICmp(Pred,
10531                                 LHSC->getValue(),
10532                                 RHSC->getValue())->isNullValue())
10533         return TrivialCase(false);
10534       return TrivialCase(true);
10535     }
10536     // Otherwise swap the operands to put the constant on the right.
10537     std::swap(LHS, RHS);
10538     Pred = ICmpInst::getSwappedPredicate(Pred);
10539     Changed = true;
10540   }
10541 
10542   // If we're comparing an addrec with a value which is loop-invariant in the
10543   // addrec's loop, put the addrec on the left. Also make a dominance check,
10544   // as both operands could be addrecs loop-invariant in each other's loop.
10545   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10546     const Loop *L = AR->getLoop();
10547     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10548       std::swap(LHS, RHS);
10549       Pred = ICmpInst::getSwappedPredicate(Pred);
10550       Changed = true;
10551     }
10552   }
10553 
10554   // If there's a constant operand, canonicalize comparisons with boundary
10555   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10556   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10557     const APInt &RA = RC->getAPInt();
10558 
10559     bool SimplifiedByConstantRange = false;
10560 
10561     if (!ICmpInst::isEquality(Pred)) {
10562       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10563       if (ExactCR.isFullSet())
10564         return TrivialCase(true);
10565       if (ExactCR.isEmptySet())
10566         return TrivialCase(false);
10567 
10568       APInt NewRHS;
10569       CmpInst::Predicate NewPred;
10570       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10571           ICmpInst::isEquality(NewPred)) {
10572         // We were able to convert an inequality to an equality.
10573         Pred = NewPred;
10574         RHS = getConstant(NewRHS);
10575         Changed = SimplifiedByConstantRange = true;
10576       }
10577     }
10578 
10579     if (!SimplifiedByConstantRange) {
10580       switch (Pred) {
10581       default:
10582         break;
10583       case ICmpInst::ICMP_EQ:
10584       case ICmpInst::ICMP_NE:
10585         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10586         if (!RA)
10587           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10588             if (const SCEVMulExpr *ME =
10589                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10590               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10591                   ME->getOperand(0)->isAllOnesValue()) {
10592                 RHS = AE->getOperand(1);
10593                 LHS = ME->getOperand(1);
10594                 Changed = true;
10595               }
10596         break;
10597 
10598 
10599         // The "Should have been caught earlier!" messages refer to the fact
10600         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10601         // should have fired on the corresponding cases, and canonicalized the
10602         // check to trivial case.
10603 
10604       case ICmpInst::ICMP_UGE:
10605         assert(!RA.isMinValue() && "Should have been caught earlier!");
10606         Pred = ICmpInst::ICMP_UGT;
10607         RHS = getConstant(RA - 1);
10608         Changed = true;
10609         break;
10610       case ICmpInst::ICMP_ULE:
10611         assert(!RA.isMaxValue() && "Should have been caught earlier!");
10612         Pred = ICmpInst::ICMP_ULT;
10613         RHS = getConstant(RA + 1);
10614         Changed = true;
10615         break;
10616       case ICmpInst::ICMP_SGE:
10617         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10618         Pred = ICmpInst::ICMP_SGT;
10619         RHS = getConstant(RA - 1);
10620         Changed = true;
10621         break;
10622       case ICmpInst::ICMP_SLE:
10623         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10624         Pred = ICmpInst::ICMP_SLT;
10625         RHS = getConstant(RA + 1);
10626         Changed = true;
10627         break;
10628       }
10629     }
10630   }
10631 
10632   // Check for obvious equality.
10633   if (HasSameValue(LHS, RHS)) {
10634     if (ICmpInst::isTrueWhenEqual(Pred))
10635       return TrivialCase(true);
10636     if (ICmpInst::isFalseWhenEqual(Pred))
10637       return TrivialCase(false);
10638   }
10639 
10640   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10641   // adding or subtracting 1 from one of the operands.
10642   switch (Pred) {
10643   case ICmpInst::ICMP_SLE:
10644     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
10645       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10646                        SCEV::FlagNSW);
10647       Pred = ICmpInst::ICMP_SLT;
10648       Changed = true;
10649     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10650       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10651                        SCEV::FlagNSW);
10652       Pred = ICmpInst::ICMP_SLT;
10653       Changed = true;
10654     }
10655     break;
10656   case ICmpInst::ICMP_SGE:
10657     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
10658       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10659                        SCEV::FlagNSW);
10660       Pred = ICmpInst::ICMP_SGT;
10661       Changed = true;
10662     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10663       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10664                        SCEV::FlagNSW);
10665       Pred = ICmpInst::ICMP_SGT;
10666       Changed = true;
10667     }
10668     break;
10669   case ICmpInst::ICMP_ULE:
10670     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
10671       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10672                        SCEV::FlagNUW);
10673       Pred = ICmpInst::ICMP_ULT;
10674       Changed = true;
10675     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10676       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10677       Pred = ICmpInst::ICMP_ULT;
10678       Changed = true;
10679     }
10680     break;
10681   case ICmpInst::ICMP_UGE:
10682     if (!getUnsignedRangeMin(RHS).isMinValue()) {
10683       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10684       Pred = ICmpInst::ICMP_UGT;
10685       Changed = true;
10686     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10687       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10688                        SCEV::FlagNUW);
10689       Pred = ICmpInst::ICMP_UGT;
10690       Changed = true;
10691     }
10692     break;
10693   default:
10694     break;
10695   }
10696 
10697   // TODO: More simplifications are possible here.
10698 
10699   // Recursively simplify until we either hit a recursion limit or nothing
10700   // changes.
10701   if (Changed)
10702     return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
10703 
10704   return Changed;
10705 }
10706 
10707 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10708   return getSignedRangeMax(S).isNegative();
10709 }
10710 
10711 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10712   return getSignedRangeMin(S).isStrictlyPositive();
10713 }
10714 
10715 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10716   return !getSignedRangeMin(S).isNegative();
10717 }
10718 
10719 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10720   return !getSignedRangeMax(S).isStrictlyPositive();
10721 }
10722 
10723 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10724   // Query push down for cases where the unsigned range is
10725   // less than sufficient.
10726   if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
10727     return isKnownNonZero(SExt->getOperand(0));
10728   return getUnsignedRangeMin(S) != 0;
10729 }
10730 
10731 std::pair<const SCEV *, const SCEV *>
10732 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10733   // Compute SCEV on entry of loop L.
10734   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10735   if (Start == getCouldNotCompute())
10736     return { Start, Start };
10737   // Compute post increment SCEV for loop L.
10738   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10739   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10740   return { Start, PostInc };
10741 }
10742 
10743 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10744                                           const SCEV *LHS, const SCEV *RHS) {
10745   // First collect all loops.
10746   SmallPtrSet<const Loop *, 8> LoopsUsed;
10747   getUsedLoops(LHS, LoopsUsed);
10748   getUsedLoops(RHS, LoopsUsed);
10749 
10750   if (LoopsUsed.empty())
10751     return false;
10752 
10753   // Domination relationship must be a linear order on collected loops.
10754 #ifndef NDEBUG
10755   for (const auto *L1 : LoopsUsed)
10756     for (const auto *L2 : LoopsUsed)
10757       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10758               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10759              "Domination relationship is not a linear order");
10760 #endif
10761 
10762   const Loop *MDL =
10763       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10764                         [&](const Loop *L1, const Loop *L2) {
10765          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10766        });
10767 
10768   // Get init and post increment value for LHS.
10769   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10770   // if LHS contains unknown non-invariant SCEV then bail out.
10771   if (SplitLHS.first == getCouldNotCompute())
10772     return false;
10773   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10774   // Get init and post increment value for RHS.
10775   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10776   // if RHS contains unknown non-invariant SCEV then bail out.
10777   if (SplitRHS.first == getCouldNotCompute())
10778     return false;
10779   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10780   // It is possible that init SCEV contains an invariant load but it does
10781   // not dominate MDL and is not available at MDL loop entry, so we should
10782   // check it here.
10783   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10784       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10785     return false;
10786 
10787   // It seems backedge guard check is faster than entry one so in some cases
10788   // it can speed up whole estimation by short circuit
10789   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10790                                      SplitRHS.second) &&
10791          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10792 }
10793 
10794 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10795                                        const SCEV *LHS, const SCEV *RHS) {
10796   // Canonicalize the inputs first.
10797   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10798 
10799   if (isKnownViaInduction(Pred, LHS, RHS))
10800     return true;
10801 
10802   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10803     return true;
10804 
10805   // Otherwise see what can be done with some simple reasoning.
10806   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10807 }
10808 
10809 std::optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10810                                                        const SCEV *LHS,
10811                                                        const SCEV *RHS) {
10812   if (isKnownPredicate(Pred, LHS, RHS))
10813     return true;
10814   if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10815     return false;
10816   return std::nullopt;
10817 }
10818 
10819 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10820                                          const SCEV *LHS, const SCEV *RHS,
10821                                          const Instruction *CtxI) {
10822   // TODO: Analyze guards and assumes from Context's block.
10823   return isKnownPredicate(Pred, LHS, RHS) ||
10824          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10825 }
10826 
10827 std::optional<bool>
10828 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
10829                                      const SCEV *RHS, const Instruction *CtxI) {
10830   std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10831   if (KnownWithoutContext)
10832     return KnownWithoutContext;
10833 
10834   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10835     return true;
10836   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10837                                           ICmpInst::getInversePredicate(Pred),
10838                                           LHS, RHS))
10839     return false;
10840   return std::nullopt;
10841 }
10842 
10843 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10844                                               const SCEVAddRecExpr *LHS,
10845                                               const SCEV *RHS) {
10846   const Loop *L = LHS->getLoop();
10847   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10848          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10849 }
10850 
10851 std::optional<ScalarEvolution::MonotonicPredicateType>
10852 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10853                                            ICmpInst::Predicate Pred) {
10854   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10855 
10856 #ifndef NDEBUG
10857   // Verify an invariant: inverting the predicate should turn a monotonically
10858   // increasing change to a monotonically decreasing one, and vice versa.
10859   if (Result) {
10860     auto ResultSwapped =
10861         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10862 
10863     assert(*ResultSwapped != *Result &&
10864            "monotonicity should flip as we flip the predicate");
10865   }
10866 #endif
10867 
10868   return Result;
10869 }
10870 
10871 std::optional<ScalarEvolution::MonotonicPredicateType>
10872 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10873                                                ICmpInst::Predicate Pred) {
10874   // A zero step value for LHS means the induction variable is essentially a
10875   // loop invariant value. We don't really depend on the predicate actually
10876   // flipping from false to true (for increasing predicates, and the other way
10877   // around for decreasing predicates), all we care about is that *if* the
10878   // predicate changes then it only changes from false to true.
10879   //
10880   // A zero step value in itself is not very useful, but there may be places
10881   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10882   // as general as possible.
10883 
10884   // Only handle LE/LT/GE/GT predicates.
10885   if (!ICmpInst::isRelational(Pred))
10886     return std::nullopt;
10887 
10888   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10889   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10890          "Should be greater or less!");
10891 
10892   // Check that AR does not wrap.
10893   if (ICmpInst::isUnsigned(Pred)) {
10894     if (!LHS->hasNoUnsignedWrap())
10895       return std::nullopt;
10896     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10897   }
10898   assert(ICmpInst::isSigned(Pred) &&
10899          "Relational predicate is either signed or unsigned!");
10900   if (!LHS->hasNoSignedWrap())
10901     return std::nullopt;
10902 
10903   const SCEV *Step = LHS->getStepRecurrence(*this);
10904 
10905   if (isKnownNonNegative(Step))
10906     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10907 
10908   if (isKnownNonPositive(Step))
10909     return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10910 
10911   return std::nullopt;
10912 }
10913 
10914 std::optional<ScalarEvolution::LoopInvariantPredicate>
10915 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10916                                            const SCEV *LHS, const SCEV *RHS,
10917                                            const Loop *L,
10918                                            const Instruction *CtxI) {
10919   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10920   if (!isLoopInvariant(RHS, L)) {
10921     if (!isLoopInvariant(LHS, L))
10922       return std::nullopt;
10923 
10924     std::swap(LHS, RHS);
10925     Pred = ICmpInst::getSwappedPredicate(Pred);
10926   }
10927 
10928   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10929   if (!ArLHS || ArLHS->getLoop() != L)
10930     return std::nullopt;
10931 
10932   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10933   if (!MonotonicType)
10934     return std::nullopt;
10935   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10936   // true as the loop iterates, and the backedge is control dependent on
10937   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10938   //
10939   //   * if the predicate was false in the first iteration then the predicate
10940   //     is never evaluated again, since the loop exits without taking the
10941   //     backedge.
10942   //   * if the predicate was true in the first iteration then it will
10943   //     continue to be true for all future iterations since it is
10944   //     monotonically increasing.
10945   //
10946   // For both the above possibilities, we can replace the loop varying
10947   // predicate with its value on the first iteration of the loop (which is
10948   // loop invariant).
10949   //
10950   // A similar reasoning applies for a monotonically decreasing predicate, by
10951   // replacing true with false and false with true in the above two bullets.
10952   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10953   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10954 
10955   if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10956     return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
10957                                                    RHS);
10958 
10959   if (!CtxI)
10960     return std::nullopt;
10961   // Try to prove via context.
10962   // TODO: Support other cases.
10963   switch (Pred) {
10964   default:
10965     break;
10966   case ICmpInst::ICMP_ULE:
10967   case ICmpInst::ICMP_ULT: {
10968     assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
10969     // Given preconditions
10970     // (1) ArLHS does not cross the border of positive and negative parts of
10971     //     range because of:
10972     //     - Positive step; (TODO: lift this limitation)
10973     //     - nuw - does not cross zero boundary;
10974     //     - nsw - does not cross SINT_MAX boundary;
10975     // (2) ArLHS <s RHS
10976     // (3) RHS >=s 0
10977     // we can replace the loop variant ArLHS <u RHS condition with loop
10978     // invariant Start(ArLHS) <u RHS.
10979     //
10980     // Because of (1) there are two options:
10981     // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
10982     // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
10983     //   It means that ArLHS <s RHS <=> ArLHS <u RHS.
10984     //   Because of (2) ArLHS <u RHS is trivially true.
10985     // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
10986     // We can strengthen this to Start(ArLHS) <u RHS.
10987     auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
10988     if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
10989         isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
10990         isKnownNonNegative(RHS) &&
10991         isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
10992       return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
10993                                                      RHS);
10994   }
10995   }
10996 
10997   return std::nullopt;
10998 }
10999 
11000 std::optional<ScalarEvolution::LoopInvariantPredicate>
11001 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
11002     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11003     const Instruction *CtxI, const SCEV *MaxIter) {
11004   if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11005           Pred, LHS, RHS, L, CtxI, MaxIter))
11006     return LIP;
11007   if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11008     // Number of iterations expressed as UMIN isn't always great for expressing
11009     // the value on the last iteration. If the straightforward approach didn't
11010     // work, try the following trick: if the a predicate is invariant for X, it
11011     // is also invariant for umin(X, ...). So try to find something that works
11012     // among subexpressions of MaxIter expressed as umin.
11013     for (auto *Op : UMin->operands())
11014       if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11015               Pred, LHS, RHS, L, CtxI, Op))
11016         return LIP;
11017   return std::nullopt;
11018 }
11019 
11020 std::optional<ScalarEvolution::LoopInvariantPredicate>
11021 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
11022     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11023     const Instruction *CtxI, const SCEV *MaxIter) {
11024   // Try to prove the following set of facts:
11025   // - The predicate is monotonic in the iteration space.
11026   // - If the check does not fail on the 1st iteration:
11027   //   - No overflow will happen during first MaxIter iterations;
11028   //   - It will not fail on the MaxIter'th iteration.
11029   // If the check does fail on the 1st iteration, we leave the loop and no
11030   // other checks matter.
11031 
11032   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11033   if (!isLoopInvariant(RHS, L)) {
11034     if (!isLoopInvariant(LHS, L))
11035       return std::nullopt;
11036 
11037     std::swap(LHS, RHS);
11038     Pred = ICmpInst::getSwappedPredicate(Pred);
11039   }
11040 
11041   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11042   if (!AR || AR->getLoop() != L)
11043     return std::nullopt;
11044 
11045   // The predicate must be relational (i.e. <, <=, >=, >).
11046   if (!ICmpInst::isRelational(Pred))
11047     return std::nullopt;
11048 
11049   // TODO: Support steps other than +/- 1.
11050   const SCEV *Step = AR->getStepRecurrence(*this);
11051   auto *One = getOne(Step->getType());
11052   auto *MinusOne = getNegativeSCEV(One);
11053   if (Step != One && Step != MinusOne)
11054     return std::nullopt;
11055 
11056   // Type mismatch here means that MaxIter is potentially larger than max
11057   // unsigned value in start type, which mean we cannot prove no wrap for the
11058   // indvar.
11059   if (AR->getType() != MaxIter->getType())
11060     return std::nullopt;
11061 
11062   // Value of IV on suggested last iteration.
11063   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11064   // Does it still meet the requirement?
11065   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11066     return std::nullopt;
11067   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11068   // not exceed max unsigned value of this type), this effectively proves
11069   // that there is no wrap during the iteration. To prove that there is no
11070   // signed/unsigned wrap, we need to check that
11071   // Start <= Last for step = 1 or Start >= Last for step = -1.
11072   ICmpInst::Predicate NoOverflowPred =
11073       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
11074   if (Step == MinusOne)
11075     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
11076   const SCEV *Start = AR->getStart();
11077   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11078     return std::nullopt;
11079 
11080   // Everything is fine.
11081   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11082 }
11083 
11084 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
11085     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
11086   if (HasSameValue(LHS, RHS))
11087     return ICmpInst::isTrueWhenEqual(Pred);
11088 
11089   // This code is split out from isKnownPredicate because it is called from
11090   // within isLoopEntryGuardedByCond.
11091 
11092   auto CheckRanges = [&](const ConstantRange &RangeLHS,
11093                          const ConstantRange &RangeRHS) {
11094     return RangeLHS.icmp(Pred, RangeRHS);
11095   };
11096 
11097   // The check at the top of the function catches the case where the values are
11098   // known to be equal.
11099   if (Pred == CmpInst::ICMP_EQ)
11100     return false;
11101 
11102   if (Pred == CmpInst::ICMP_NE) {
11103     auto SL = getSignedRange(LHS);
11104     auto SR = getSignedRange(RHS);
11105     if (CheckRanges(SL, SR))
11106       return true;
11107     auto UL = getUnsignedRange(LHS);
11108     auto UR = getUnsignedRange(RHS);
11109     if (CheckRanges(UL, UR))
11110       return true;
11111     auto *Diff = getMinusSCEV(LHS, RHS);
11112     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11113   }
11114 
11115   if (CmpInst::isSigned(Pred)) {
11116     auto SL = getSignedRange(LHS);
11117     auto SR = getSignedRange(RHS);
11118     return CheckRanges(SL, SR);
11119   }
11120 
11121   auto UL = getUnsignedRange(LHS);
11122   auto UR = getUnsignedRange(RHS);
11123   return CheckRanges(UL, UR);
11124 }
11125 
11126 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
11127                                                     const SCEV *LHS,
11128                                                     const SCEV *RHS) {
11129   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11130   // C1 and C2 are constant integers. If either X or Y are not add expressions,
11131   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11132   // OutC1 and OutC2.
11133   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
11134                                       APInt &OutC1, APInt &OutC2,
11135                                       SCEV::NoWrapFlags ExpectedFlags) {
11136     const SCEV *XNonConstOp, *XConstOp;
11137     const SCEV *YNonConstOp, *YConstOp;
11138     SCEV::NoWrapFlags XFlagsPresent;
11139     SCEV::NoWrapFlags YFlagsPresent;
11140 
11141     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11142       XConstOp = getZero(X->getType());
11143       XNonConstOp = X;
11144       XFlagsPresent = ExpectedFlags;
11145     }
11146     if (!isa<SCEVConstant>(XConstOp) ||
11147         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
11148       return false;
11149 
11150     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11151       YConstOp = getZero(Y->getType());
11152       YNonConstOp = Y;
11153       YFlagsPresent = ExpectedFlags;
11154     }
11155 
11156     if (!isa<SCEVConstant>(YConstOp) ||
11157         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11158       return false;
11159 
11160     if (YNonConstOp != XNonConstOp)
11161       return false;
11162 
11163     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11164     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11165 
11166     return true;
11167   };
11168 
11169   APInt C1;
11170   APInt C2;
11171 
11172   switch (Pred) {
11173   default:
11174     break;
11175 
11176   case ICmpInst::ICMP_SGE:
11177     std::swap(LHS, RHS);
11178     [[fallthrough]];
11179   case ICmpInst::ICMP_SLE:
11180     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11181     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11182       return true;
11183 
11184     break;
11185 
11186   case ICmpInst::ICMP_SGT:
11187     std::swap(LHS, RHS);
11188     [[fallthrough]];
11189   case ICmpInst::ICMP_SLT:
11190     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11191     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11192       return true;
11193 
11194     break;
11195 
11196   case ICmpInst::ICMP_UGE:
11197     std::swap(LHS, RHS);
11198     [[fallthrough]];
11199   case ICmpInst::ICMP_ULE:
11200     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
11201     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
11202       return true;
11203 
11204     break;
11205 
11206   case ICmpInst::ICMP_UGT:
11207     std::swap(LHS, RHS);
11208     [[fallthrough]];
11209   case ICmpInst::ICMP_ULT:
11210     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
11211     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
11212       return true;
11213     break;
11214   }
11215 
11216   return false;
11217 }
11218 
11219 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
11220                                                    const SCEV *LHS,
11221                                                    const SCEV *RHS) {
11222   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11223     return false;
11224 
11225   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11226   // the stack can result in exponential time complexity.
11227   SaveAndRestore Restore(ProvingSplitPredicate, true);
11228 
11229   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11230   //
11231   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11232   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
11233   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11234   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
11235   // use isKnownPredicate later if needed.
11236   return isKnownNonNegative(RHS) &&
11237          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
11238          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
11239 }
11240 
11241 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
11242                                         ICmpInst::Predicate Pred,
11243                                         const SCEV *LHS, const SCEV *RHS) {
11244   // No need to even try if we know the module has no guards.
11245   if (!HasGuards)
11246     return false;
11247 
11248   return any_of(*BB, [&](const Instruction &I) {
11249     using namespace llvm::PatternMatch;
11250 
11251     Value *Condition;
11252     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
11253                          m_Value(Condition))) &&
11254            isImpliedCond(Pred, LHS, RHS, Condition, false);
11255   });
11256 }
11257 
11258 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11259 /// protected by a conditional between LHS and RHS.  This is used to
11260 /// to eliminate casts.
11261 bool
11262 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
11263                                              ICmpInst::Predicate Pred,
11264                                              const SCEV *LHS, const SCEV *RHS) {
11265   // Interpret a null as meaning no loop, where there is obviously no guard
11266   // (interprocedural conditions notwithstanding). Do not bother about
11267   // unreachable loops.
11268   if (!L || !DT.isReachableFromEntry(L->getHeader()))
11269     return true;
11270 
11271   if (VerifyIR)
11272     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11273            "This cannot be done on broken IR!");
11274 
11275 
11276   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11277     return true;
11278 
11279   BasicBlock *Latch = L->getLoopLatch();
11280   if (!Latch)
11281     return false;
11282 
11283   BranchInst *LoopContinuePredicate =
11284     dyn_cast<BranchInst>(Latch->getTerminator());
11285   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
11286       isImpliedCond(Pred, LHS, RHS,
11287                     LoopContinuePredicate->getCondition(),
11288                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11289     return true;
11290 
11291   // We don't want more than one activation of the following loops on the stack
11292   // -- that can lead to O(n!) time complexity.
11293   if (WalkingBEDominatingConds)
11294     return false;
11295 
11296   SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11297 
11298   // See if we can exploit a trip count to prove the predicate.
11299   const auto &BETakenInfo = getBackedgeTakenInfo(L);
11300   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11301   if (LatchBECount != getCouldNotCompute()) {
11302     // We know that Latch branches back to the loop header exactly
11303     // LatchBECount times.  This means the backdege condition at Latch is
11304     // equivalent to  "{0,+,1} u< LatchBECount".
11305     Type *Ty = LatchBECount->getType();
11306     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11307     const SCEV *LoopCounter =
11308       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11309     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11310                       LatchBECount))
11311       return true;
11312   }
11313 
11314   // Check conditions due to any @llvm.assume intrinsics.
11315   for (auto &AssumeVH : AC.assumptions()) {
11316     if (!AssumeVH)
11317       continue;
11318     auto *CI = cast<CallInst>(AssumeVH);
11319     if (!DT.dominates(CI, Latch->getTerminator()))
11320       continue;
11321 
11322     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11323       return true;
11324   }
11325 
11326   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11327     return true;
11328 
11329   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11330        DTN != HeaderDTN; DTN = DTN->getIDom()) {
11331     assert(DTN && "should reach the loop header before reaching the root!");
11332 
11333     BasicBlock *BB = DTN->getBlock();
11334     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11335       return true;
11336 
11337     BasicBlock *PBB = BB->getSinglePredecessor();
11338     if (!PBB)
11339       continue;
11340 
11341     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
11342     if (!ContinuePredicate || !ContinuePredicate->isConditional())
11343       continue;
11344 
11345     Value *Condition = ContinuePredicate->getCondition();
11346 
11347     // If we have an edge `E` within the loop body that dominates the only
11348     // latch, the condition guarding `E` also guards the backedge.  This
11349     // reasoning works only for loops with a single latch.
11350 
11351     BasicBlockEdge DominatingEdge(PBB, BB);
11352     if (DominatingEdge.isSingleEdge()) {
11353       // We're constructively (and conservatively) enumerating edges within the
11354       // loop body that dominate the latch.  The dominator tree better agree
11355       // with us on this:
11356       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
11357 
11358       if (isImpliedCond(Pred, LHS, RHS, Condition,
11359                         BB != ContinuePredicate->getSuccessor(0)))
11360         return true;
11361     }
11362   }
11363 
11364   return false;
11365 }
11366 
11367 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
11368                                                      ICmpInst::Predicate Pred,
11369                                                      const SCEV *LHS,
11370                                                      const SCEV *RHS) {
11371   // Do not bother proving facts for unreachable code.
11372   if (!DT.isReachableFromEntry(BB))
11373     return true;
11374   if (VerifyIR)
11375     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11376            "This cannot be done on broken IR!");
11377 
11378   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11379   // the facts (a >= b && a != b) separately. A typical situation is when the
11380   // non-strict comparison is known from ranges and non-equality is known from
11381   // dominating predicates. If we are proving strict comparison, we always try
11382   // to prove non-equality and non-strict comparison separately.
11383   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
11384   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
11385   bool ProvedNonStrictComparison = false;
11386   bool ProvedNonEquality = false;
11387 
11388   auto SplitAndProve =
11389     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
11390     if (!ProvedNonStrictComparison)
11391       ProvedNonStrictComparison = Fn(NonStrictPredicate);
11392     if (!ProvedNonEquality)
11393       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11394     if (ProvedNonStrictComparison && ProvedNonEquality)
11395       return true;
11396     return false;
11397   };
11398 
11399   if (ProvingStrictComparison) {
11400     auto ProofFn = [&](ICmpInst::Predicate P) {
11401       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11402     };
11403     if (SplitAndProve(ProofFn))
11404       return true;
11405   }
11406 
11407   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11408   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11409     const Instruction *CtxI = &BB->front();
11410     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11411       return true;
11412     if (ProvingStrictComparison) {
11413       auto ProofFn = [&](ICmpInst::Predicate P) {
11414         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11415       };
11416       if (SplitAndProve(ProofFn))
11417         return true;
11418     }
11419     return false;
11420   };
11421 
11422   // Starting at the block's predecessor, climb up the predecessor chain, as long
11423   // as there are predecessors that can be found that have unique successors
11424   // leading to the original block.
11425   const Loop *ContainingLoop = LI.getLoopFor(BB);
11426   const BasicBlock *PredBB;
11427   if (ContainingLoop && ContainingLoop->getHeader() == BB)
11428     PredBB = ContainingLoop->getLoopPredecessor();
11429   else
11430     PredBB = BB->getSinglePredecessor();
11431   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11432        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11433     const BranchInst *BlockEntryPredicate =
11434         dyn_cast<BranchInst>(Pair.first->getTerminator());
11435     if (!BlockEntryPredicate || BlockEntryPredicate->isUnconditional())
11436       continue;
11437 
11438     if (ProveViaCond(BlockEntryPredicate->getCondition(),
11439                      BlockEntryPredicate->getSuccessor(0) != Pair.second))
11440       return true;
11441   }
11442 
11443   // Check conditions due to any @llvm.assume intrinsics.
11444   for (auto &AssumeVH : AC.assumptions()) {
11445     if (!AssumeVH)
11446       continue;
11447     auto *CI = cast<CallInst>(AssumeVH);
11448     if (!DT.dominates(CI, BB))
11449       continue;
11450 
11451     if (ProveViaCond(CI->getArgOperand(0), false))
11452       return true;
11453   }
11454 
11455   // Check conditions due to any @llvm.experimental.guard intrinsics.
11456   auto *GuardDecl = F.getParent()->getFunction(
11457       Intrinsic::getName(Intrinsic::experimental_guard));
11458   if (GuardDecl)
11459     for (const auto *GU : GuardDecl->users())
11460       if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
11461         if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
11462           if (ProveViaCond(Guard->getArgOperand(0), false))
11463             return true;
11464   return false;
11465 }
11466 
11467 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
11468                                                ICmpInst::Predicate Pred,
11469                                                const SCEV *LHS,
11470                                                const SCEV *RHS) {
11471   // Interpret a null as meaning no loop, where there is obviously no guard
11472   // (interprocedural conditions notwithstanding).
11473   if (!L)
11474     return false;
11475 
11476   // Both LHS and RHS must be available at loop entry.
11477   assert(isAvailableAtLoopEntry(LHS, L) &&
11478          "LHS is not available at Loop Entry");
11479   assert(isAvailableAtLoopEntry(RHS, L) &&
11480          "RHS is not available at Loop Entry");
11481 
11482   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11483     return true;
11484 
11485   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11486 }
11487 
11488 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11489                                     const SCEV *RHS,
11490                                     const Value *FoundCondValue, bool Inverse,
11491                                     const Instruction *CtxI) {
11492   // False conditions implies anything. Do not bother analyzing it further.
11493   if (FoundCondValue ==
11494       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11495     return true;
11496 
11497   if (!PendingLoopPredicates.insert(FoundCondValue).second)
11498     return false;
11499 
11500   auto ClearOnExit =
11501       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11502 
11503   // Recursively handle And and Or conditions.
11504   const Value *Op0, *Op1;
11505   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11506     if (!Inverse)
11507       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11508              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11509   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11510     if (Inverse)
11511       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11512              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11513   }
11514 
11515   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11516   if (!ICI) return false;
11517 
11518   // Now that we found a conditional branch that dominates the loop or controls
11519   // the loop latch. Check to see if it is the comparison we are looking for.
11520   ICmpInst::Predicate FoundPred;
11521   if (Inverse)
11522     FoundPred = ICI->getInversePredicate();
11523   else
11524     FoundPred = ICI->getPredicate();
11525 
11526   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11527   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11528 
11529   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11530 }
11531 
11532 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11533                                     const SCEV *RHS,
11534                                     ICmpInst::Predicate FoundPred,
11535                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
11536                                     const Instruction *CtxI) {
11537   // Balance the types.
11538   if (getTypeSizeInBits(LHS->getType()) <
11539       getTypeSizeInBits(FoundLHS->getType())) {
11540     // For unsigned and equality predicates, try to prove that both found
11541     // operands fit into narrow unsigned range. If so, try to prove facts in
11542     // narrow types.
11543     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11544         !FoundRHS->getType()->isPointerTy()) {
11545       auto *NarrowType = LHS->getType();
11546       auto *WideType = FoundLHS->getType();
11547       auto BitWidth = getTypeSizeInBits(NarrowType);
11548       const SCEV *MaxValue = getZeroExtendExpr(
11549           getConstant(APInt::getMaxValue(BitWidth)), WideType);
11550       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11551                                           MaxValue) &&
11552           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11553                                           MaxValue)) {
11554         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11555         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11556         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11557                                        TruncFoundRHS, CtxI))
11558           return true;
11559       }
11560     }
11561 
11562     if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11563       return false;
11564     if (CmpInst::isSigned(Pred)) {
11565       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11566       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11567     } else {
11568       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11569       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11570     }
11571   } else if (getTypeSizeInBits(LHS->getType()) >
11572       getTypeSizeInBits(FoundLHS->getType())) {
11573     if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11574       return false;
11575     if (CmpInst::isSigned(FoundPred)) {
11576       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11577       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11578     } else {
11579       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11580       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11581     }
11582   }
11583   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11584                                     FoundRHS, CtxI);
11585 }
11586 
11587 bool ScalarEvolution::isImpliedCondBalancedTypes(
11588     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11589     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11590     const Instruction *CtxI) {
11591   assert(getTypeSizeInBits(LHS->getType()) ==
11592              getTypeSizeInBits(FoundLHS->getType()) &&
11593          "Types should be balanced!");
11594   // Canonicalize the query to match the way instcombine will have
11595   // canonicalized the comparison.
11596   if (SimplifyICmpOperands(Pred, LHS, RHS))
11597     if (LHS == RHS)
11598       return CmpInst::isTrueWhenEqual(Pred);
11599   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11600     if (FoundLHS == FoundRHS)
11601       return CmpInst::isFalseWhenEqual(FoundPred);
11602 
11603   // Check to see if we can make the LHS or RHS match.
11604   if (LHS == FoundRHS || RHS == FoundLHS) {
11605     if (isa<SCEVConstant>(RHS)) {
11606       std::swap(FoundLHS, FoundRHS);
11607       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11608     } else {
11609       std::swap(LHS, RHS);
11610       Pred = ICmpInst::getSwappedPredicate(Pred);
11611     }
11612   }
11613 
11614   // Check whether the found predicate is the same as the desired predicate.
11615   if (FoundPred == Pred)
11616     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11617 
11618   // Check whether swapping the found predicate makes it the same as the
11619   // desired predicate.
11620   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11621     // We can write the implication
11622     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
11623     // using one of the following ways:
11624     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
11625     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
11626     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
11627     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
11628     // Forms 1. and 2. require swapping the operands of one condition. Don't
11629     // do this if it would break canonical constant/addrec ordering.
11630     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11631       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11632                                    CtxI);
11633     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11634       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11635 
11636     // There's no clear preference between forms 3. and 4., try both.  Avoid
11637     // forming getNotSCEV of pointer values as the resulting subtract is
11638     // not legal.
11639     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11640         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11641                               FoundLHS, FoundRHS, CtxI))
11642       return true;
11643 
11644     if (!FoundLHS->getType()->isPointerTy() &&
11645         !FoundRHS->getType()->isPointerTy() &&
11646         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11647                               getNotSCEV(FoundRHS), CtxI))
11648       return true;
11649 
11650     return false;
11651   }
11652 
11653   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11654                                    CmpInst::Predicate P2) {
11655     assert(P1 != P2 && "Handled earlier!");
11656     return CmpInst::isRelational(P2) &&
11657            P1 == CmpInst::getFlippedSignednessPredicate(P2);
11658   };
11659   if (IsSignFlippedPredicate(Pred, FoundPred)) {
11660     // Unsigned comparison is the same as signed comparison when both the
11661     // operands are non-negative or negative.
11662     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11663         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11664       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11665     // Create local copies that we can freely swap and canonicalize our
11666     // conditions to "le/lt".
11667     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11668     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11669                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11670     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11671       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11672       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11673       std::swap(CanonicalLHS, CanonicalRHS);
11674       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11675     }
11676     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11677            "Must be!");
11678     assert((ICmpInst::isLT(CanonicalFoundPred) ||
11679             ICmpInst::isLE(CanonicalFoundPred)) &&
11680            "Must be!");
11681     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11682       // Use implication:
11683       // x <u y && y >=s 0 --> x <s y.
11684       // If we can prove the left part, the right part is also proven.
11685       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11686                                    CanonicalRHS, CanonicalFoundLHS,
11687                                    CanonicalFoundRHS);
11688     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11689       // Use implication:
11690       // x <s y && y <s 0 --> x <u y.
11691       // If we can prove the left part, the right part is also proven.
11692       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11693                                    CanonicalRHS, CanonicalFoundLHS,
11694                                    CanonicalFoundRHS);
11695   }
11696 
11697   // Check if we can make progress by sharpening ranges.
11698   if (FoundPred == ICmpInst::ICMP_NE &&
11699       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11700 
11701     const SCEVConstant *C = nullptr;
11702     const SCEV *V = nullptr;
11703 
11704     if (isa<SCEVConstant>(FoundLHS)) {
11705       C = cast<SCEVConstant>(FoundLHS);
11706       V = FoundRHS;
11707     } else {
11708       C = cast<SCEVConstant>(FoundRHS);
11709       V = FoundLHS;
11710     }
11711 
11712     // The guarding predicate tells us that C != V. If the known range
11713     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
11714     // range we consider has to correspond to same signedness as the
11715     // predicate we're interested in folding.
11716 
11717     APInt Min = ICmpInst::isSigned(Pred) ?
11718         getSignedRangeMin(V) : getUnsignedRangeMin(V);
11719 
11720     if (Min == C->getAPInt()) {
11721       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11722       // This is true even if (Min + 1) wraps around -- in case of
11723       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11724 
11725       APInt SharperMin = Min + 1;
11726 
11727       switch (Pred) {
11728         case ICmpInst::ICMP_SGE:
11729         case ICmpInst::ICMP_UGE:
11730           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
11731           // RHS, we're done.
11732           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11733                                     CtxI))
11734             return true;
11735           [[fallthrough]];
11736 
11737         case ICmpInst::ICMP_SGT:
11738         case ICmpInst::ICMP_UGT:
11739           // We know from the range information that (V `Pred` Min ||
11740           // V == Min).  We know from the guarding condition that !(V
11741           // == Min).  This gives us
11742           //
11743           //       V `Pred` Min || V == Min && !(V == Min)
11744           //   =>  V `Pred` Min
11745           //
11746           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11747 
11748           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11749             return true;
11750           break;
11751 
11752         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11753         case ICmpInst::ICMP_SLE:
11754         case ICmpInst::ICMP_ULE:
11755           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11756                                     LHS, V, getConstant(SharperMin), CtxI))
11757             return true;
11758           [[fallthrough]];
11759 
11760         case ICmpInst::ICMP_SLT:
11761         case ICmpInst::ICMP_ULT:
11762           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11763                                     LHS, V, getConstant(Min), CtxI))
11764             return true;
11765           break;
11766 
11767         default:
11768           // No change
11769           break;
11770       }
11771     }
11772   }
11773 
11774   // Check whether the actual condition is beyond sufficient.
11775   if (FoundPred == ICmpInst::ICMP_EQ)
11776     if (ICmpInst::isTrueWhenEqual(Pred))
11777       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11778         return true;
11779   if (Pred == ICmpInst::ICMP_NE)
11780     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11781       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11782         return true;
11783 
11784   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
11785     return true;
11786 
11787   // Otherwise assume the worst.
11788   return false;
11789 }
11790 
11791 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11792                                      const SCEV *&L, const SCEV *&R,
11793                                      SCEV::NoWrapFlags &Flags) {
11794   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11795   if (!AE || AE->getNumOperands() != 2)
11796     return false;
11797 
11798   L = AE->getOperand(0);
11799   R = AE->getOperand(1);
11800   Flags = AE->getNoWrapFlags();
11801   return true;
11802 }
11803 
11804 std::optional<APInt>
11805 ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
11806   // We avoid subtracting expressions here because this function is usually
11807   // fairly deep in the call stack (i.e. is called many times).
11808 
11809   // X - X = 0.
11810   if (More == Less)
11811     return APInt(getTypeSizeInBits(More->getType()), 0);
11812 
11813   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11814     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11815     const auto *MAR = cast<SCEVAddRecExpr>(More);
11816 
11817     if (LAR->getLoop() != MAR->getLoop())
11818       return std::nullopt;
11819 
11820     // We look at affine expressions only; not for correctness but to keep
11821     // getStepRecurrence cheap.
11822     if (!LAR->isAffine() || !MAR->isAffine())
11823       return std::nullopt;
11824 
11825     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11826       return std::nullopt;
11827 
11828     Less = LAR->getStart();
11829     More = MAR->getStart();
11830 
11831     // fall through
11832   }
11833 
11834   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11835     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11836     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11837     return M - L;
11838   }
11839 
11840   SCEV::NoWrapFlags Flags;
11841   const SCEV *LLess = nullptr, *RLess = nullptr;
11842   const SCEV *LMore = nullptr, *RMore = nullptr;
11843   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11844   // Compare (X + C1) vs X.
11845   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11846     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11847       if (RLess == More)
11848         return -(C1->getAPInt());
11849 
11850   // Compare X vs (X + C2).
11851   if (splitBinaryAdd(More, LMore, RMore, Flags))
11852     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11853       if (RMore == Less)
11854         return C2->getAPInt();
11855 
11856   // Compare (X + C1) vs (X + C2).
11857   if (C1 && C2 && RLess == RMore)
11858     return C2->getAPInt() - C1->getAPInt();
11859 
11860   return std::nullopt;
11861 }
11862 
11863 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11864     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11865     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11866   // Try to recognize the following pattern:
11867   //
11868   //   FoundRHS = ...
11869   // ...
11870   // loop:
11871   //   FoundLHS = {Start,+,W}
11872   // context_bb: // Basic block from the same loop
11873   //   known(Pred, FoundLHS, FoundRHS)
11874   //
11875   // If some predicate is known in the context of a loop, it is also known on
11876   // each iteration of this loop, including the first iteration. Therefore, in
11877   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11878   // prove the original pred using this fact.
11879   if (!CtxI)
11880     return false;
11881   const BasicBlock *ContextBB = CtxI->getParent();
11882   // Make sure AR varies in the context block.
11883   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11884     const Loop *L = AR->getLoop();
11885     // Make sure that context belongs to the loop and executes on 1st iteration
11886     // (if it ever executes at all).
11887     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11888       return false;
11889     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11890       return false;
11891     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11892   }
11893 
11894   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11895     const Loop *L = AR->getLoop();
11896     // Make sure that context belongs to the loop and executes on 1st iteration
11897     // (if it ever executes at all).
11898     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11899       return false;
11900     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11901       return false;
11902     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11903   }
11904 
11905   return false;
11906 }
11907 
11908 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11909     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11910     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11911   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11912     return false;
11913 
11914   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11915   if (!AddRecLHS)
11916     return false;
11917 
11918   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11919   if (!AddRecFoundLHS)
11920     return false;
11921 
11922   // We'd like to let SCEV reason about control dependencies, so we constrain
11923   // both the inequalities to be about add recurrences on the same loop.  This
11924   // way we can use isLoopEntryGuardedByCond later.
11925 
11926   const Loop *L = AddRecFoundLHS->getLoop();
11927   if (L != AddRecLHS->getLoop())
11928     return false;
11929 
11930   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11931   //
11932   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11933   //                                                                  ... (2)
11934   //
11935   // Informal proof for (2), assuming (1) [*]:
11936   //
11937   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11938   //
11939   // Then
11940   //
11941   //       FoundLHS s< FoundRHS s< INT_MIN - C
11942   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11943   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11944   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11945   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11946   // <=>  FoundLHS + C s< FoundRHS + C
11947   //
11948   // [*]: (1) can be proved by ruling out overflow.
11949   //
11950   // [**]: This can be proved by analyzing all the four possibilities:
11951   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11952   //    (A s>= 0, B s>= 0).
11953   //
11954   // Note:
11955   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11956   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11957   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11958   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11959   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11960   // C)".
11961 
11962   std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11963   std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11964   if (!LDiff || !RDiff || *LDiff != *RDiff)
11965     return false;
11966 
11967   if (LDiff->isMinValue())
11968     return true;
11969 
11970   APInt FoundRHSLimit;
11971 
11972   if (Pred == CmpInst::ICMP_ULT) {
11973     FoundRHSLimit = -(*RDiff);
11974   } else {
11975     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11976     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11977   }
11978 
11979   // Try to prove (1) or (2), as needed.
11980   return isAvailableAtLoopEntry(FoundRHS, L) &&
11981          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11982                                   getConstant(FoundRHSLimit));
11983 }
11984 
11985 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11986                                         const SCEV *LHS, const SCEV *RHS,
11987                                         const SCEV *FoundLHS,
11988                                         const SCEV *FoundRHS, unsigned Depth) {
11989   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11990 
11991   auto ClearOnExit = make_scope_exit([&]() {
11992     if (LPhi) {
11993       bool Erased = PendingMerges.erase(LPhi);
11994       assert(Erased && "Failed to erase LPhi!");
11995       (void)Erased;
11996     }
11997     if (RPhi) {
11998       bool Erased = PendingMerges.erase(RPhi);
11999       assert(Erased && "Failed to erase RPhi!");
12000       (void)Erased;
12001     }
12002   });
12003 
12004   // Find respective Phis and check that they are not being pending.
12005   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12006     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12007       if (!PendingMerges.insert(Phi).second)
12008         return false;
12009       LPhi = Phi;
12010     }
12011   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12012     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12013       // If we detect a loop of Phi nodes being processed by this method, for
12014       // example:
12015       //
12016       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12017       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12018       //
12019       // we don't want to deal with a case that complex, so return conservative
12020       // answer false.
12021       if (!PendingMerges.insert(Phi).second)
12022         return false;
12023       RPhi = Phi;
12024     }
12025 
12026   // If none of LHS, RHS is a Phi, nothing to do here.
12027   if (!LPhi && !RPhi)
12028     return false;
12029 
12030   // If there is a SCEVUnknown Phi we are interested in, make it left.
12031   if (!LPhi) {
12032     std::swap(LHS, RHS);
12033     std::swap(FoundLHS, FoundRHS);
12034     std::swap(LPhi, RPhi);
12035     Pred = ICmpInst::getSwappedPredicate(Pred);
12036   }
12037 
12038   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12039   const BasicBlock *LBB = LPhi->getParent();
12040   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12041 
12042   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12043     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12044            isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12045            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12046   };
12047 
12048   if (RPhi && RPhi->getParent() == LBB) {
12049     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12050     // If we compare two Phis from the same block, and for each entry block
12051     // the predicate is true for incoming values from this block, then the
12052     // predicate is also true for the Phis.
12053     for (const BasicBlock *IncBB : predecessors(LBB)) {
12054       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12055       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12056       if (!ProvedEasily(L, R))
12057         return false;
12058     }
12059   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12060     // Case two: RHS is also a Phi from the same basic block, and it is an
12061     // AddRec. It means that there is a loop which has both AddRec and Unknown
12062     // PHIs, for it we can compare incoming values of AddRec from above the loop
12063     // and latch with their respective incoming values of LPhi.
12064     // TODO: Generalize to handle loops with many inputs in a header.
12065     if (LPhi->getNumIncomingValues() != 2) return false;
12066 
12067     auto *RLoop = RAR->getLoop();
12068     auto *Predecessor = RLoop->getLoopPredecessor();
12069     assert(Predecessor && "Loop with AddRec with no predecessor?");
12070     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12071     if (!ProvedEasily(L1, RAR->getStart()))
12072       return false;
12073     auto *Latch = RLoop->getLoopLatch();
12074     assert(Latch && "Loop with AddRec with no latch?");
12075     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12076     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12077       return false;
12078   } else {
12079     // In all other cases go over inputs of LHS and compare each of them to RHS,
12080     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12081     // At this point RHS is either a non-Phi, or it is a Phi from some block
12082     // different from LBB.
12083     for (const BasicBlock *IncBB : predecessors(LBB)) {
12084       // Check that RHS is available in this block.
12085       if (!dominates(RHS, IncBB))
12086         return false;
12087       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12088       // Make sure L does not refer to a value from a potentially previous
12089       // iteration of a loop.
12090       if (!properlyDominates(L, LBB))
12091         return false;
12092       if (!ProvedEasily(L, RHS))
12093         return false;
12094     }
12095   }
12096   return true;
12097 }
12098 
12099 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
12100                                                     const SCEV *LHS,
12101                                                     const SCEV *RHS,
12102                                                     const SCEV *FoundLHS,
12103                                                     const SCEV *FoundRHS) {
12104   // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue).  First, make
12105   // sure that we are dealing with same LHS.
12106   if (RHS == FoundRHS) {
12107     std::swap(LHS, RHS);
12108     std::swap(FoundLHS, FoundRHS);
12109     Pred = ICmpInst::getSwappedPredicate(Pred);
12110   }
12111   if (LHS != FoundLHS)
12112     return false;
12113 
12114   auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12115   if (!SUFoundRHS)
12116     return false;
12117 
12118   Value *Shiftee, *ShiftValue;
12119 
12120   using namespace PatternMatch;
12121   if (match(SUFoundRHS->getValue(),
12122             m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12123     auto *ShifteeS = getSCEV(Shiftee);
12124     // Prove one of the following:
12125     // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12126     // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12127     // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12128     //   ---> LHS <s RHS
12129     // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12130     //   ---> LHS <=s RHS
12131     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12132       return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12133     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12134       if (isKnownNonNegative(ShifteeS))
12135         return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12136   }
12137 
12138   return false;
12139 }
12140 
12141 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
12142                                             const SCEV *LHS, const SCEV *RHS,
12143                                             const SCEV *FoundLHS,
12144                                             const SCEV *FoundRHS,
12145                                             const Instruction *CtxI) {
12146   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS, FoundRHS))
12147     return true;
12148 
12149   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
12150     return true;
12151 
12152   if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
12153     return true;
12154 
12155   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12156                                           CtxI))
12157     return true;
12158 
12159   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
12160                                      FoundLHS, FoundRHS);
12161 }
12162 
12163 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12164 template <typename MinMaxExprType>
12165 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12166                                  const SCEV *Candidate) {
12167   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12168   if (!MinMaxExpr)
12169     return false;
12170 
12171   return is_contained(MinMaxExpr->operands(), Candidate);
12172 }
12173 
12174 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
12175                                            ICmpInst::Predicate Pred,
12176                                            const SCEV *LHS, const SCEV *RHS) {
12177   // If both sides are affine addrecs for the same loop, with equal
12178   // steps, and we know the recurrences don't wrap, then we only
12179   // need to check the predicate on the starting values.
12180 
12181   if (!ICmpInst::isRelational(Pred))
12182     return false;
12183 
12184   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
12185   if (!LAR)
12186     return false;
12187   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12188   if (!RAR)
12189     return false;
12190   if (LAR->getLoop() != RAR->getLoop())
12191     return false;
12192   if (!LAR->isAffine() || !RAR->isAffine())
12193     return false;
12194 
12195   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
12196     return false;
12197 
12198   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
12199                          SCEV::FlagNSW : SCEV::FlagNUW;
12200   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12201     return false;
12202 
12203   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
12204 }
12205 
12206 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12207 /// expression?
12208 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
12209                                         ICmpInst::Predicate Pred,
12210                                         const SCEV *LHS, const SCEV *RHS) {
12211   switch (Pred) {
12212   default:
12213     return false;
12214 
12215   case ICmpInst::ICMP_SGE:
12216     std::swap(LHS, RHS);
12217     [[fallthrough]];
12218   case ICmpInst::ICMP_SLE:
12219     return
12220         // min(A, ...) <= A
12221         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
12222         // A <= max(A, ...)
12223         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
12224 
12225   case ICmpInst::ICMP_UGE:
12226     std::swap(LHS, RHS);
12227     [[fallthrough]];
12228   case ICmpInst::ICMP_ULE:
12229     return
12230         // min(A, ...) <= A
12231         // FIXME: what about umin_seq?
12232         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
12233         // A <= max(A, ...)
12234         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
12235   }
12236 
12237   llvm_unreachable("covered switch fell through?!");
12238 }
12239 
12240 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
12241                                              const SCEV *LHS, const SCEV *RHS,
12242                                              const SCEV *FoundLHS,
12243                                              const SCEV *FoundRHS,
12244                                              unsigned Depth) {
12245   assert(getTypeSizeInBits(LHS->getType()) ==
12246              getTypeSizeInBits(RHS->getType()) &&
12247          "LHS and RHS have different sizes?");
12248   assert(getTypeSizeInBits(FoundLHS->getType()) ==
12249              getTypeSizeInBits(FoundRHS->getType()) &&
12250          "FoundLHS and FoundRHS have different sizes?");
12251   // We want to avoid hurting the compile time with analysis of too big trees.
12252   if (Depth > MaxSCEVOperationsImplicationDepth)
12253     return false;
12254 
12255   // We only want to work with GT comparison so far.
12256   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
12257     Pred = CmpInst::getSwappedPredicate(Pred);
12258     std::swap(LHS, RHS);
12259     std::swap(FoundLHS, FoundRHS);
12260   }
12261 
12262   // For unsigned, try to reduce it to corresponding signed comparison.
12263   if (Pred == ICmpInst::ICMP_UGT)
12264     // We can replace unsigned predicate with its signed counterpart if all
12265     // involved values are non-negative.
12266     // TODO: We could have better support for unsigned.
12267     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12268       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12269       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12270       // use this fact to prove that LHS and RHS are non-negative.
12271       const SCEV *MinusOne = getMinusOne(LHS->getType());
12272       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12273                                 FoundRHS) &&
12274           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12275                                 FoundRHS))
12276         Pred = ICmpInst::ICMP_SGT;
12277     }
12278 
12279   if (Pred != ICmpInst::ICMP_SGT)
12280     return false;
12281 
12282   auto GetOpFromSExt = [&](const SCEV *S) {
12283     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12284       return Ext->getOperand();
12285     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12286     // the constant in some cases.
12287     return S;
12288   };
12289 
12290   // Acquire values from extensions.
12291   auto *OrigLHS = LHS;
12292   auto *OrigFoundLHS = FoundLHS;
12293   LHS = GetOpFromSExt(LHS);
12294   FoundLHS = GetOpFromSExt(FoundLHS);
12295 
12296   // Is the SGT predicate can be proved trivially or using the found context.
12297   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12298     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12299            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12300                                   FoundRHS, Depth + 1);
12301   };
12302 
12303   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12304     // We want to avoid creation of any new non-constant SCEV. Since we are
12305     // going to compare the operands to RHS, we should be certain that we don't
12306     // need any size extensions for this. So let's decline all cases when the
12307     // sizes of types of LHS and RHS do not match.
12308     // TODO: Maybe try to get RHS from sext to catch more cases?
12309     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
12310       return false;
12311 
12312     // Should not overflow.
12313     if (!LHSAddExpr->hasNoSignedWrap())
12314       return false;
12315 
12316     auto *LL = LHSAddExpr->getOperand(0);
12317     auto *LR = LHSAddExpr->getOperand(1);
12318     auto *MinusOne = getMinusOne(RHS->getType());
12319 
12320     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12321     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12322       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12323     };
12324     // Try to prove the following rule:
12325     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12326     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12327     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12328       return true;
12329   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12330     Value *LL, *LR;
12331     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12332 
12333     using namespace llvm::PatternMatch;
12334 
12335     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12336       // Rules for division.
12337       // We are going to perform some comparisons with Denominator and its
12338       // derivative expressions. In general case, creating a SCEV for it may
12339       // lead to a complex analysis of the entire graph, and in particular it
12340       // can request trip count recalculation for the same loop. This would
12341       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
12342       // this, we only want to create SCEVs that are constants in this section.
12343       // So we bail if Denominator is not a constant.
12344       if (!isa<ConstantInt>(LR))
12345         return false;
12346 
12347       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
12348 
12349       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
12350       // then a SCEV for the numerator already exists and matches with FoundLHS.
12351       auto *Numerator = getExistingSCEV(LL);
12352       if (!Numerator || Numerator->getType() != FoundLHS->getType())
12353         return false;
12354 
12355       // Make sure that the numerator matches with FoundLHS and the denominator
12356       // is positive.
12357       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
12358         return false;
12359 
12360       auto *DTy = Denominator->getType();
12361       auto *FRHSTy = FoundRHS->getType();
12362       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
12363         // One of types is a pointer and another one is not. We cannot extend
12364         // them properly to a wider type, so let us just reject this case.
12365         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
12366         // to avoid this check.
12367         return false;
12368 
12369       // Given that:
12370       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
12371       auto *WTy = getWiderType(DTy, FRHSTy);
12372       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
12373       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
12374 
12375       // Try to prove the following rule:
12376       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
12377       // For example, given that FoundLHS > 2. It means that FoundLHS is at
12378       // least 3. If we divide it by Denominator < 4, we will have at least 1.
12379       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
12380       if (isKnownNonPositive(RHS) &&
12381           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
12382         return true;
12383 
12384       // Try to prove the following rule:
12385       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
12386       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
12387       // If we divide it by Denominator > 2, then:
12388       // 1. If FoundLHS is negative, then the result is 0.
12389       // 2. If FoundLHS is non-negative, then the result is non-negative.
12390       // Anyways, the result is non-negative.
12391       auto *MinusOne = getMinusOne(WTy);
12392       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
12393       if (isKnownNegative(RHS) &&
12394           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
12395         return true;
12396     }
12397   }
12398 
12399   // If our expression contained SCEVUnknown Phis, and we split it down and now
12400   // need to prove something for them, try to prove the predicate for every
12401   // possible incoming values of those Phis.
12402   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
12403     return true;
12404 
12405   return false;
12406 }
12407 
12408 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
12409                                         const SCEV *LHS, const SCEV *RHS) {
12410   // zext x u<= sext x, sext x s<= zext x
12411   switch (Pred) {
12412   case ICmpInst::ICMP_SGE:
12413     std::swap(LHS, RHS);
12414     [[fallthrough]];
12415   case ICmpInst::ICMP_SLE: {
12416     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
12417     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
12418     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
12419     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12420       return true;
12421     break;
12422   }
12423   case ICmpInst::ICMP_UGE:
12424     std::swap(LHS, RHS);
12425     [[fallthrough]];
12426   case ICmpInst::ICMP_ULE: {
12427     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
12428     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
12429     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
12430     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12431       return true;
12432     break;
12433   }
12434   default:
12435     break;
12436   };
12437   return false;
12438 }
12439 
12440 bool
12441 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
12442                                            const SCEV *LHS, const SCEV *RHS) {
12443   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
12444          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12445          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
12446          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
12447          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12448 }
12449 
12450 bool
12451 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
12452                                              const SCEV *LHS, const SCEV *RHS,
12453                                              const SCEV *FoundLHS,
12454                                              const SCEV *FoundRHS) {
12455   switch (Pred) {
12456   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
12457   case ICmpInst::ICMP_EQ:
12458   case ICmpInst::ICMP_NE:
12459     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
12460       return true;
12461     break;
12462   case ICmpInst::ICMP_SLT:
12463   case ICmpInst::ICMP_SLE:
12464     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
12465         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
12466       return true;
12467     break;
12468   case ICmpInst::ICMP_SGT:
12469   case ICmpInst::ICMP_SGE:
12470     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
12471         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
12472       return true;
12473     break;
12474   case ICmpInst::ICMP_ULT:
12475   case ICmpInst::ICMP_ULE:
12476     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12477         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12478       return true;
12479     break;
12480   case ICmpInst::ICMP_UGT:
12481   case ICmpInst::ICMP_UGE:
12482     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12483         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12484       return true;
12485     break;
12486   }
12487 
12488   // Maybe it can be proved via operations?
12489   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12490     return true;
12491 
12492   return false;
12493 }
12494 
12495 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12496                                                      const SCEV *LHS,
12497                                                      const SCEV *RHS,
12498                                                      ICmpInst::Predicate FoundPred,
12499                                                      const SCEV *FoundLHS,
12500                                                      const SCEV *FoundRHS) {
12501   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12502     // The restriction on `FoundRHS` be lifted easily -- it exists only to
12503     // reduce the compile time impact of this optimization.
12504     return false;
12505 
12506   std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12507   if (!Addend)
12508     return false;
12509 
12510   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12511 
12512   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12513   // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
12514   ConstantRange FoundLHSRange =
12515       ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
12516 
12517   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12518   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12519 
12520   // We can also compute the range of values for `LHS` that satisfy the
12521   // consequent, "`LHS` `Pred` `RHS`":
12522   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12523   // The antecedent implies the consequent if every value of `LHS` that
12524   // satisfies the antecedent also satisfies the consequent.
12525   return LHSRange.icmp(Pred, ConstRHS);
12526 }
12527 
12528 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12529                                         bool IsSigned) {
12530   assert(isKnownPositive(Stride) && "Positive stride expected!");
12531 
12532   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12533   const SCEV *One = getOne(Stride->getType());
12534 
12535   if (IsSigned) {
12536     APInt MaxRHS = getSignedRangeMax(RHS);
12537     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12538     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12539 
12540     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12541     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12542   }
12543 
12544   APInt MaxRHS = getUnsignedRangeMax(RHS);
12545   APInt MaxValue = APInt::getMaxValue(BitWidth);
12546   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12547 
12548   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12549   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12550 }
12551 
12552 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12553                                         bool IsSigned) {
12554 
12555   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12556   const SCEV *One = getOne(Stride->getType());
12557 
12558   if (IsSigned) {
12559     APInt MinRHS = getSignedRangeMin(RHS);
12560     APInt MinValue = APInt::getSignedMinValue(BitWidth);
12561     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12562 
12563     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12564     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12565   }
12566 
12567   APInt MinRHS = getUnsignedRangeMin(RHS);
12568   APInt MinValue = APInt::getMinValue(BitWidth);
12569   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12570 
12571   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12572   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12573 }
12574 
12575 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12576   // umin(N, 1) + floor((N - umin(N, 1)) / D)
12577   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12578   // expression fixes the case of N=0.
12579   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12580   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12581   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12582 }
12583 
12584 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12585                                                     const SCEV *Stride,
12586                                                     const SCEV *End,
12587                                                     unsigned BitWidth,
12588                                                     bool IsSigned) {
12589   // The logic in this function assumes we can represent a positive stride.
12590   // If we can't, the backedge-taken count must be zero.
12591   if (IsSigned && BitWidth == 1)
12592     return getZero(Stride->getType());
12593 
12594   // This code below only been closely audited for negative strides in the
12595   // unsigned comparison case, it may be correct for signed comparison, but
12596   // that needs to be established.
12597   if (IsSigned && isKnownNegative(Stride))
12598     return getCouldNotCompute();
12599 
12600   // Calculate the maximum backedge count based on the range of values
12601   // permitted by Start, End, and Stride.
12602   APInt MinStart =
12603       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12604 
12605   APInt MinStride =
12606       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12607 
12608   // We assume either the stride is positive, or the backedge-taken count
12609   // is zero. So force StrideForMaxBECount to be at least one.
12610   APInt One(BitWidth, 1);
12611   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12612                                        : APIntOps::umax(One, MinStride);
12613 
12614   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12615                             : APInt::getMaxValue(BitWidth);
12616   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12617 
12618   // Although End can be a MAX expression we estimate MaxEnd considering only
12619   // the case End = RHS of the loop termination condition. This is safe because
12620   // in the other case (End - Start) is zero, leading to a zero maximum backedge
12621   // taken count.
12622   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12623                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12624 
12625   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12626   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12627                     : APIntOps::umax(MaxEnd, MinStart);
12628 
12629   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12630                          getConstant(StrideForMaxBECount) /* Step */);
12631 }
12632 
12633 ScalarEvolution::ExitLimit
12634 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12635                                   const Loop *L, bool IsSigned,
12636                                   bool ControlsOnlyExit, bool AllowPredicates) {
12637   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12638 
12639   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12640   bool PredicatedIV = false;
12641 
12642   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12643     // Can we prove this loop *must* be UB if overflow of IV occurs?
12644     // Reasoning goes as follows:
12645     // * Suppose the IV did self wrap.
12646     // * If Stride evenly divides the iteration space, then once wrap
12647     //   occurs, the loop must revisit the same values.
12648     // * We know that RHS is invariant, and that none of those values
12649     //   caused this exit to be taken previously.  Thus, this exit is
12650     //   dynamically dead.
12651     // * If this is the sole exit, then a dead exit implies the loop
12652     //   must be infinite if there are no abnormal exits.
12653     // * If the loop were infinite, then it must either not be mustprogress
12654     //   or have side effects. Otherwise, it must be UB.
12655     // * It can't (by assumption), be UB so we have contradicted our
12656     //   premise and can conclude the IV did not in fact self-wrap.
12657     if (!isLoopInvariant(RHS, L))
12658       return false;
12659 
12660     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12661     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12662       return false;
12663 
12664     if (!ControlsOnlyExit || !loopHasNoAbnormalExits(L))
12665       return false;
12666 
12667     return loopIsFiniteByAssumption(L);
12668   };
12669 
12670   if (!IV) {
12671     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12672       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12673       if (AR && AR->getLoop() == L && AR->isAffine()) {
12674         auto canProveNUW = [&]() {
12675           // We can use the comparison to infer no-wrap flags only if it fully
12676           // controls the loop exit.
12677           if (!ControlsOnlyExit)
12678             return false;
12679 
12680           if (!isLoopInvariant(RHS, L))
12681             return false;
12682 
12683           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12684             // We need the sequence defined by AR to strictly increase in the
12685             // unsigned integer domain for the logic below to hold.
12686             return false;
12687 
12688           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12689           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12690           // If RHS <=u Limit, then there must exist a value V in the sequence
12691           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12692           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
12693           // overflow occurs.  This limit also implies that a signed comparison
12694           // (in the wide bitwidth) is equivalent to an unsigned comparison as
12695           // the high bits on both sides must be zero.
12696           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12697           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12698           Limit = Limit.zext(OuterBitWidth);
12699           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12700         };
12701         auto Flags = AR->getNoWrapFlags();
12702         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12703           Flags = setFlags(Flags, SCEV::FlagNUW);
12704 
12705         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12706         if (AR->hasNoUnsignedWrap()) {
12707           // Emulate what getZeroExtendExpr would have done during construction
12708           // if we'd been able to infer the fact just above at that time.
12709           const SCEV *Step = AR->getStepRecurrence(*this);
12710           Type *Ty = ZExt->getType();
12711           auto *S = getAddRecExpr(
12712             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12713             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12714           IV = dyn_cast<SCEVAddRecExpr>(S);
12715         }
12716       }
12717     }
12718   }
12719 
12720 
12721   if (!IV && AllowPredicates) {
12722     // Try to make this an AddRec using runtime tests, in the first X
12723     // iterations of this loop, where X is the SCEV expression found by the
12724     // algorithm below.
12725     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12726     PredicatedIV = true;
12727   }
12728 
12729   // Avoid weird loops
12730   if (!IV || IV->getLoop() != L || !IV->isAffine())
12731     return getCouldNotCompute();
12732 
12733   // A precondition of this method is that the condition being analyzed
12734   // reaches an exiting branch which dominates the latch.  Given that, we can
12735   // assume that an increment which violates the nowrap specification and
12736   // produces poison must cause undefined behavior when the resulting poison
12737   // value is branched upon and thus we can conclude that the backedge is
12738   // taken no more often than would be required to produce that poison value.
12739   // Note that a well defined loop can exit on the iteration which violates
12740   // the nowrap specification if there is another exit (either explicit or
12741   // implicit/exceptional) which causes the loop to execute before the
12742   // exiting instruction we're analyzing would trigger UB.
12743   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12744   bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
12745   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12746 
12747   const SCEV *Stride = IV->getStepRecurrence(*this);
12748 
12749   bool PositiveStride = isKnownPositive(Stride);
12750 
12751   // Avoid negative or zero stride values.
12752   if (!PositiveStride) {
12753     // We can compute the correct backedge taken count for loops with unknown
12754     // strides if we can prove that the loop is not an infinite loop with side
12755     // effects. Here's the loop structure we are trying to handle -
12756     //
12757     // i = start
12758     // do {
12759     //   A[i] = i;
12760     //   i += s;
12761     // } while (i < end);
12762     //
12763     // The backedge taken count for such loops is evaluated as -
12764     // (max(end, start + stride) - start - 1) /u stride
12765     //
12766     // The additional preconditions that we need to check to prove correctness
12767     // of the above formula is as follows -
12768     //
12769     // a) IV is either nuw or nsw depending upon signedness (indicated by the
12770     //    NoWrap flag).
12771     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12772     //    no side effects within the loop)
12773     // c) loop has a single static exit (with no abnormal exits)
12774     //
12775     // Precondition a) implies that if the stride is negative, this is a single
12776     // trip loop. The backedge taken count formula reduces to zero in this case.
12777     //
12778     // Precondition b) and c) combine to imply that if rhs is invariant in L,
12779     // then a zero stride means the backedge can't be taken without executing
12780     // undefined behavior.
12781     //
12782     // The positive stride case is the same as isKnownPositive(Stride) returning
12783     // true (original behavior of the function).
12784     //
12785     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12786         !loopHasNoAbnormalExits(L))
12787       return getCouldNotCompute();
12788 
12789     if (!isKnownNonZero(Stride)) {
12790       // If we have a step of zero, and RHS isn't invariant in L, we don't know
12791       // if it might eventually be greater than start and if so, on which
12792       // iteration.  We can't even produce a useful upper bound.
12793       if (!isLoopInvariant(RHS, L))
12794         return getCouldNotCompute();
12795 
12796       // We allow a potentially zero stride, but we need to divide by stride
12797       // below.  Since the loop can't be infinite and this check must control
12798       // the sole exit, we can infer the exit must be taken on the first
12799       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
12800       // we know the numerator in the divides below must be zero, so we can
12801       // pick an arbitrary non-zero value for the denominator (e.g. stride)
12802       // and produce the right result.
12803       // FIXME: Handle the case where Stride is poison?
12804       auto wouldZeroStrideBeUB = [&]() {
12805         // Proof by contradiction.  Suppose the stride were zero.  If we can
12806         // prove that the backedge *is* taken on the first iteration, then since
12807         // we know this condition controls the sole exit, we must have an
12808         // infinite loop.  We can't have a (well defined) infinite loop per
12809         // check just above.
12810         // Note: The (Start - Stride) term is used to get the start' term from
12811         // (start' + stride,+,stride). Remember that we only care about the
12812         // result of this expression when stride == 0 at runtime.
12813         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12814         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12815       };
12816       if (!wouldZeroStrideBeUB()) {
12817         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12818       }
12819     }
12820   } else if (!Stride->isOne() && !NoWrap) {
12821     auto isUBOnWrap = [&]() {
12822       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12823       // follows trivially from the fact that every (un)signed-wrapped, but
12824       // not self-wrapped value must be LT than the last value before
12825       // (un)signed wrap.  Since we know that last value didn't exit, nor
12826       // will any smaller one.
12827       return canAssumeNoSelfWrap(IV);
12828     };
12829 
12830     // Avoid proven overflow cases: this will ensure that the backedge taken
12831     // count will not generate any unsigned overflow. Relaxed no-overflow
12832     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12833     // undefined behaviors like the case of C language.
12834     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12835       return getCouldNotCompute();
12836   }
12837 
12838   // On all paths just preceeding, we established the following invariant:
12839   //   IV can be assumed not to overflow up to and including the exiting
12840   //   iteration.  We proved this in one of two ways:
12841   //   1) We can show overflow doesn't occur before the exiting iteration
12842   //      1a) canIVOverflowOnLT, and b) step of one
12843   //   2) We can show that if overflow occurs, the loop must execute UB
12844   //      before any possible exit.
12845   // Note that we have not yet proved RHS invariant (in general).
12846 
12847   const SCEV *Start = IV->getStart();
12848 
12849   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12850   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12851   // Use integer-typed versions for actual computation; we can't subtract
12852   // pointers in general.
12853   const SCEV *OrigStart = Start;
12854   const SCEV *OrigRHS = RHS;
12855   if (Start->getType()->isPointerTy()) {
12856     Start = getLosslessPtrToIntExpr(Start);
12857     if (isa<SCEVCouldNotCompute>(Start))
12858       return Start;
12859   }
12860   if (RHS->getType()->isPointerTy()) {
12861     RHS = getLosslessPtrToIntExpr(RHS);
12862     if (isa<SCEVCouldNotCompute>(RHS))
12863       return RHS;
12864   }
12865 
12866   // When the RHS is not invariant, we do not know the end bound of the loop and
12867   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12868   // calculate the MaxBECount, given the start, stride and max value for the end
12869   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12870   // checked above).
12871   if (!isLoopInvariant(RHS, L)) {
12872     const SCEV *MaxBECount = computeMaxBECountForLT(
12873         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12874     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12875                      MaxBECount, false /*MaxOrZero*/, Predicates);
12876   }
12877 
12878   // We use the expression (max(End,Start)-Start)/Stride to describe the
12879   // backedge count, as if the backedge is taken at least once max(End,Start)
12880   // is End and so the result is as above, and if not max(End,Start) is Start
12881   // so we get a backedge count of zero.
12882   const SCEV *BECount = nullptr;
12883   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12884   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12885   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12886   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12887   // Can we prove (max(RHS,Start) > Start - Stride?
12888   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12889       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12890     // In this case, we can use a refined formula for computing backedge taken
12891     // count.  The general formula remains:
12892     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12893     // We want to use the alternate formula:
12894     //   "((End - 1) - (Start - Stride)) /u Stride"
12895     // Let's do a quick case analysis to show these are equivalent under
12896     // our precondition that max(RHS,Start) > Start - Stride.
12897     // * For RHS <= Start, the backedge-taken count must be zero.
12898     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12899     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12900     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12901     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12902     //     this to the stride of 1 case.
12903     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12904     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12905     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12906     //   "((RHS - (Start - Stride) - 1) /u Stride".
12907     //   Our preconditions trivially imply no overflow in that form.
12908     const SCEV *MinusOne = getMinusOne(Stride->getType());
12909     const SCEV *Numerator =
12910         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12911     BECount = getUDivExpr(Numerator, Stride);
12912   }
12913 
12914   const SCEV *BECountIfBackedgeTaken = nullptr;
12915   if (!BECount) {
12916     auto canProveRHSGreaterThanEqualStart = [&]() {
12917       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12918       const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
12919       const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
12920 
12921       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
12922           isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
12923         return true;
12924 
12925       // (RHS > Start - 1) implies RHS >= Start.
12926       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12927       //   "Start - 1" doesn't overflow.
12928       // * For signed comparison, if Start - 1 does overflow, it's equal
12929       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12930       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12931       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12932       //
12933       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12934       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12935       auto *StartMinusOne = getAddExpr(OrigStart,
12936                                        getMinusOne(OrigStart->getType()));
12937       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12938     };
12939 
12940     // If we know that RHS >= Start in the context of loop, then we know that
12941     // max(RHS, Start) = RHS at this point.
12942     const SCEV *End;
12943     if (canProveRHSGreaterThanEqualStart()) {
12944       End = RHS;
12945     } else {
12946       // If RHS < Start, the backedge will be taken zero times.  So in
12947       // general, we can write the backedge-taken count as:
12948       //
12949       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12950       //
12951       // We convert it to the following to make it more convenient for SCEV:
12952       //
12953       //     ceil(max(RHS, Start) - Start) / Stride
12954       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12955 
12956       // See what would happen if we assume the backedge is taken. This is
12957       // used to compute MaxBECount.
12958       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12959     }
12960 
12961     // At this point, we know:
12962     //
12963     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12964     // 2. The index variable doesn't overflow.
12965     //
12966     // Therefore, we know N exists such that
12967     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12968     // doesn't overflow.
12969     //
12970     // Using this information, try to prove whether the addition in
12971     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12972     const SCEV *One = getOne(Stride->getType());
12973     bool MayAddOverflow = [&] {
12974       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12975         if (StrideC->getAPInt().isPowerOf2()) {
12976           // Suppose Stride is a power of two, and Start/End are unsigned
12977           // integers.  Let UMAX be the largest representable unsigned
12978           // integer.
12979           //
12980           // By the preconditions of this function, we know
12981           // "(Start + Stride * N) >= End", and this doesn't overflow.
12982           // As a formula:
12983           //
12984           //   End <= (Start + Stride * N) <= UMAX
12985           //
12986           // Subtracting Start from all the terms:
12987           //
12988           //   End - Start <= Stride * N <= UMAX - Start
12989           //
12990           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12991           //
12992           //   End - Start <= Stride * N <= UMAX
12993           //
12994           // Stride * N is a multiple of Stride. Therefore,
12995           //
12996           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12997           //
12998           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12999           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
13000           //
13001           //   End - Start <= Stride * N <= UMAX - Stride - 1
13002           //
13003           // Dropping the middle term:
13004           //
13005           //   End - Start <= UMAX - Stride - 1
13006           //
13007           // Adding Stride - 1 to both sides:
13008           //
13009           //   (End - Start) + (Stride - 1) <= UMAX
13010           //
13011           // In other words, the addition doesn't have unsigned overflow.
13012           //
13013           // A similar proof works if we treat Start/End as signed values.
13014           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
13015           // use signed max instead of unsigned max. Note that we're trying
13016           // to prove a lack of unsigned overflow in either case.
13017           return false;
13018         }
13019       }
13020       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13021         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
13022         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
13023         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
13024         //
13025         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
13026         return false;
13027       }
13028       return true;
13029     }();
13030 
13031     const SCEV *Delta = getMinusSCEV(End, Start);
13032     if (!MayAddOverflow) {
13033       // floor((D + (S - 1)) / S)
13034       // We prefer this formulation if it's legal because it's fewer operations.
13035       BECount =
13036           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13037     } else {
13038       BECount = getUDivCeilSCEV(Delta, Stride);
13039     }
13040   }
13041 
13042   const SCEV *ConstantMaxBECount;
13043   bool MaxOrZero = false;
13044   if (isa<SCEVConstant>(BECount)) {
13045     ConstantMaxBECount = BECount;
13046   } else if (BECountIfBackedgeTaken &&
13047              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13048     // If we know exactly how many times the backedge will be taken if it's
13049     // taken at least once, then the backedge count will either be that or
13050     // zero.
13051     ConstantMaxBECount = BECountIfBackedgeTaken;
13052     MaxOrZero = true;
13053   } else {
13054     ConstantMaxBECount = computeMaxBECountForLT(
13055         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13056   }
13057 
13058   if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13059       !isa<SCEVCouldNotCompute>(BECount))
13060     ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13061 
13062   const SCEV *SymbolicMaxBECount =
13063       isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13064   return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13065                    Predicates);
13066 }
13067 
13068 ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13069     const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13070     bool ControlsOnlyExit, bool AllowPredicates) {
13071   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
13072   // We handle only IV > Invariant
13073   if (!isLoopInvariant(RHS, L))
13074     return getCouldNotCompute();
13075 
13076   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13077   if (!IV && AllowPredicates)
13078     // Try to make this an AddRec using runtime tests, in the first X
13079     // iterations of this loop, where X is the SCEV expression found by the
13080     // algorithm below.
13081     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13082 
13083   // Avoid weird loops
13084   if (!IV || IV->getLoop() != L || !IV->isAffine())
13085     return getCouldNotCompute();
13086 
13087   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13088   bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
13089   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13090 
13091   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13092 
13093   // Avoid negative or zero stride values
13094   if (!isKnownPositive(Stride))
13095     return getCouldNotCompute();
13096 
13097   // Avoid proven overflow cases: this will ensure that the backedge taken count
13098   // will not generate any unsigned overflow. Relaxed no-overflow conditions
13099   // exploit NoWrapFlags, allowing to optimize in presence of undefined
13100   // behaviors like the case of C language.
13101   if (!Stride->isOne() && !NoWrap)
13102     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13103       return getCouldNotCompute();
13104 
13105   const SCEV *Start = IV->getStart();
13106   const SCEV *End = RHS;
13107   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13108     // If we know that Start >= RHS in the context of loop, then we know that
13109     // min(RHS, Start) = RHS at this point.
13110     if (isLoopEntryGuardedByCond(
13111             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13112       End = RHS;
13113     else
13114       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13115   }
13116 
13117   if (Start->getType()->isPointerTy()) {
13118     Start = getLosslessPtrToIntExpr(Start);
13119     if (isa<SCEVCouldNotCompute>(Start))
13120       return Start;
13121   }
13122   if (End->getType()->isPointerTy()) {
13123     End = getLosslessPtrToIntExpr(End);
13124     if (isa<SCEVCouldNotCompute>(End))
13125       return End;
13126   }
13127 
13128   // Compute ((Start - End) + (Stride - 1)) / Stride.
13129   // FIXME: This can overflow. Holding off on fixing this for now;
13130   // howManyGreaterThans will hopefully be gone soon.
13131   const SCEV *One = getOne(Stride->getType());
13132   const SCEV *BECount = getUDivExpr(
13133       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13134 
13135   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13136                             : getUnsignedRangeMax(Start);
13137 
13138   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13139                              : getUnsignedRangeMin(Stride);
13140 
13141   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13142   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13143                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
13144 
13145   // Although End can be a MIN expression we estimate MinEnd considering only
13146   // the case End = RHS. This is safe because in the other case (Start - End)
13147   // is zero, leading to a zero maximum backedge taken count.
13148   APInt MinEnd =
13149     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13150              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13151 
13152   const SCEV *ConstantMaxBECount =
13153       isa<SCEVConstant>(BECount)
13154           ? BECount
13155           : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13156                             getConstant(MinStride));
13157 
13158   if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13159     ConstantMaxBECount = BECount;
13160   const SCEV *SymbolicMaxBECount =
13161       isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13162 
13163   return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13164                    Predicates);
13165 }
13166 
13167 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
13168                                                     ScalarEvolution &SE) const {
13169   if (Range.isFullSet())  // Infinite loop.
13170     return SE.getCouldNotCompute();
13171 
13172   // If the start is a non-zero constant, shift the range to simplify things.
13173   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13174     if (!SC->getValue()->isZero()) {
13175       SmallVector<const SCEV *, 4> Operands(operands());
13176       Operands[0] = SE.getZero(SC->getType());
13177       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13178                                              getNoWrapFlags(FlagNW));
13179       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13180         return ShiftedAddRec->getNumIterationsInRange(
13181             Range.subtract(SC->getAPInt()), SE);
13182       // This is strange and shouldn't happen.
13183       return SE.getCouldNotCompute();
13184     }
13185 
13186   // The only time we can solve this is when we have all constant indices.
13187   // Otherwise, we cannot determine the overflow conditions.
13188   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13189     return SE.getCouldNotCompute();
13190 
13191   // Okay at this point we know that all elements of the chrec are constants and
13192   // that the start element is zero.
13193 
13194   // First check to see if the range contains zero.  If not, the first
13195   // iteration exits.
13196   unsigned BitWidth = SE.getTypeSizeInBits(getType());
13197   if (!Range.contains(APInt(BitWidth, 0)))
13198     return SE.getZero(getType());
13199 
13200   if (isAffine()) {
13201     // If this is an affine expression then we have this situation:
13202     //   Solve {0,+,A} in Range  ===  Ax in Range
13203 
13204     // We know that zero is in the range.  If A is positive then we know that
13205     // the upper value of the range must be the first possible exit value.
13206     // If A is negative then the lower of the range is the last possible loop
13207     // value.  Also note that we already checked for a full range.
13208     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13209     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13210 
13211     // The exit value should be (End+A)/A.
13212     APInt ExitVal = (End + A).udiv(A);
13213     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13214 
13215     // Evaluate at the exit value.  If we really did fall out of the valid
13216     // range, then we computed our trip count, otherwise wrap around or other
13217     // things must have happened.
13218     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13219     if (Range.contains(Val->getValue()))
13220       return SE.getCouldNotCompute();  // Something strange happened
13221 
13222     // Ensure that the previous value is in the range.
13223     assert(Range.contains(
13224            EvaluateConstantChrecAtConstant(this,
13225            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13226            "Linear scev computation is off in a bad way!");
13227     return SE.getConstant(ExitValue);
13228   }
13229 
13230   if (isQuadratic()) {
13231     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13232       return SE.getConstant(*S);
13233   }
13234 
13235   return SE.getCouldNotCompute();
13236 }
13237 
13238 const SCEVAddRecExpr *
13239 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
13240   assert(getNumOperands() > 1 && "AddRec with zero step?");
13241   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13242   // but in this case we cannot guarantee that the value returned will be an
13243   // AddRec because SCEV does not have a fixed point where it stops
13244   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13245   // may happen if we reach arithmetic depth limit while simplifying. So we
13246   // construct the returned value explicitly.
13247   SmallVector<const SCEV *, 3> Ops;
13248   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13249   // (this + Step) is {A+B,+,B+C,+...,+,N}.
13250   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13251     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13252   // We know that the last operand is not a constant zero (otherwise it would
13253   // have been popped out earlier). This guarantees us that if the result has
13254   // the same last operand, then it will also not be popped out, meaning that
13255   // the returned value will be an AddRec.
13256   const SCEV *Last = getOperand(getNumOperands() - 1);
13257   assert(!Last->isZero() && "Recurrency with zero step?");
13258   Ops.push_back(Last);
13259   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
13260                                                SCEV::FlagAnyWrap));
13261 }
13262 
13263 // Return true when S contains at least an undef value.
13264 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
13265   return SCEVExprContains(S, [](const SCEV *S) {
13266     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13267       return isa<UndefValue>(SU->getValue());
13268     return false;
13269   });
13270 }
13271 
13272 // Return true when S contains a value that is a nullptr.
13273 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
13274   return SCEVExprContains(S, [](const SCEV *S) {
13275     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13276       return SU->getValue() == nullptr;
13277     return false;
13278   });
13279 }
13280 
13281 /// Return the size of an element read or written by Inst.
13282 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
13283   Type *Ty;
13284   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
13285     Ty = Store->getValueOperand()->getType();
13286   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
13287     Ty = Load->getType();
13288   else
13289     return nullptr;
13290 
13291   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
13292   return getSizeOfExpr(ETy, Ty);
13293 }
13294 
13295 //===----------------------------------------------------------------------===//
13296 //                   SCEVCallbackVH Class Implementation
13297 //===----------------------------------------------------------------------===//
13298 
13299 void ScalarEvolution::SCEVCallbackVH::deleted() {
13300   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13301   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13302     SE->ConstantEvolutionLoopExitValue.erase(PN);
13303   SE->eraseValueFromMap(getValPtr());
13304   // this now dangles!
13305 }
13306 
13307 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13308   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13309 
13310   // Forget all the expressions associated with users of the old value,
13311   // so that future queries will recompute the expressions using the new
13312   // value.
13313   SE->forgetValue(getValPtr());
13314   // this now dangles!
13315 }
13316 
13317 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13318   : CallbackVH(V), SE(se) {}
13319 
13320 //===----------------------------------------------------------------------===//
13321 //                   ScalarEvolution Class Implementation
13322 //===----------------------------------------------------------------------===//
13323 
13324 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
13325                                  AssumptionCache &AC, DominatorTree &DT,
13326                                  LoopInfo &LI)
13327     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
13328       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
13329       LoopDispositions(64), BlockDispositions(64) {
13330   // To use guards for proving predicates, we need to scan every instruction in
13331   // relevant basic blocks, and not just terminators.  Doing this is a waste of
13332   // time if the IR does not actually contain any calls to
13333   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
13334   //
13335   // This pessimizes the case where a pass that preserves ScalarEvolution wants
13336   // to _add_ guards to the module when there weren't any before, and wants
13337   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
13338   // efficient in lieu of being smart in that rather obscure case.
13339 
13340   auto *GuardDecl = F.getParent()->getFunction(
13341       Intrinsic::getName(Intrinsic::experimental_guard));
13342   HasGuards = GuardDecl && !GuardDecl->use_empty();
13343 }
13344 
13345 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
13346     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
13347       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
13348       ValueExprMap(std::move(Arg.ValueExprMap)),
13349       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
13350       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
13351       PendingMerges(std::move(Arg.PendingMerges)),
13352       ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
13353       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
13354       PredicatedBackedgeTakenCounts(
13355           std::move(Arg.PredicatedBackedgeTakenCounts)),
13356       BECountUsers(std::move(Arg.BECountUsers)),
13357       ConstantEvolutionLoopExitValue(
13358           std::move(Arg.ConstantEvolutionLoopExitValue)),
13359       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
13360       ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
13361       LoopDispositions(std::move(Arg.LoopDispositions)),
13362       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
13363       BlockDispositions(std::move(Arg.BlockDispositions)),
13364       SCEVUsers(std::move(Arg.SCEVUsers)),
13365       UnsignedRanges(std::move(Arg.UnsignedRanges)),
13366       SignedRanges(std::move(Arg.SignedRanges)),
13367       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
13368       UniquePreds(std::move(Arg.UniquePreds)),
13369       SCEVAllocator(std::move(Arg.SCEVAllocator)),
13370       LoopUsers(std::move(Arg.LoopUsers)),
13371       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
13372       FirstUnknown(Arg.FirstUnknown) {
13373   Arg.FirstUnknown = nullptr;
13374 }
13375 
13376 ScalarEvolution::~ScalarEvolution() {
13377   // Iterate through all the SCEVUnknown instances and call their
13378   // destructors, so that they release their references to their values.
13379   for (SCEVUnknown *U = FirstUnknown; U;) {
13380     SCEVUnknown *Tmp = U;
13381     U = U->Next;
13382     Tmp->~SCEVUnknown();
13383   }
13384   FirstUnknown = nullptr;
13385 
13386   ExprValueMap.clear();
13387   ValueExprMap.clear();
13388   HasRecMap.clear();
13389   BackedgeTakenCounts.clear();
13390   PredicatedBackedgeTakenCounts.clear();
13391 
13392   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
13393   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
13394   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
13395   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
13396   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
13397 }
13398 
13399 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
13400   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
13401 }
13402 
13403 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
13404                           const Loop *L) {
13405   // Print all inner loops first
13406   for (Loop *I : *L)
13407     PrintLoopInfo(OS, SE, I);
13408 
13409   OS << "Loop ";
13410   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13411   OS << ": ";
13412 
13413   SmallVector<BasicBlock *, 8> ExitingBlocks;
13414   L->getExitingBlocks(ExitingBlocks);
13415   if (ExitingBlocks.size() != 1)
13416     OS << "<multiple exits> ";
13417 
13418   if (SE->hasLoopInvariantBackedgeTakenCount(L))
13419     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
13420   else
13421     OS << "Unpredictable backedge-taken count.\n";
13422 
13423   if (ExitingBlocks.size() > 1)
13424     for (BasicBlock *ExitingBlock : ExitingBlocks) {
13425       OS << "  exit count for " << ExitingBlock->getName() << ": "
13426          << *SE->getExitCount(L, ExitingBlock) << "\n";
13427     }
13428 
13429   OS << "Loop ";
13430   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13431   OS << ": ";
13432 
13433   auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
13434   if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
13435     OS << "constant max backedge-taken count is " << *ConstantBTC;
13436     if (SE->isBackedgeTakenCountMaxOrZero(L))
13437       OS << ", actual taken count either this or zero.";
13438   } else {
13439     OS << "Unpredictable constant max backedge-taken count. ";
13440   }
13441 
13442   OS << "\n"
13443         "Loop ";
13444   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13445   OS << ": ";
13446 
13447   auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
13448   if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
13449     OS << "symbolic max backedge-taken count is " << *SymbolicBTC;
13450     if (SE->isBackedgeTakenCountMaxOrZero(L))
13451       OS << ", actual taken count either this or zero.";
13452   } else {
13453     OS << "Unpredictable symbolic max backedge-taken count. ";
13454   }
13455 
13456   OS << "\n";
13457   if (ExitingBlocks.size() > 1)
13458     for (BasicBlock *ExitingBlock : ExitingBlocks) {
13459       OS << "  symbolic max exit count for " << ExitingBlock->getName() << ": "
13460          << *SE->getExitCount(L, ExitingBlock, ScalarEvolution::SymbolicMaximum)
13461          << "\n";
13462     }
13463 
13464   OS << "Loop ";
13465   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13466   OS << ": ";
13467 
13468   SmallVector<const SCEVPredicate *, 4> Preds;
13469   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
13470   if (!isa<SCEVCouldNotCompute>(PBT)) {
13471     OS << "Predicated backedge-taken count is " << *PBT << "\n";
13472     OS << " Predicates:\n";
13473     for (const auto *P : Preds)
13474       P->print(OS, 4);
13475   } else {
13476     OS << "Unpredictable predicated backedge-taken count.\n";
13477   }
13478 
13479   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
13480     OS << "Loop ";
13481     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13482     OS << ": ";
13483     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
13484   }
13485 }
13486 
13487 namespace llvm {
13488 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::LoopDisposition LD) {
13489   switch (LD) {
13490   case ScalarEvolution::LoopVariant:
13491     OS << "Variant";
13492     break;
13493   case ScalarEvolution::LoopInvariant:
13494     OS << "Invariant";
13495     break;
13496   case ScalarEvolution::LoopComputable:
13497     OS << "Computable";
13498     break;
13499   }
13500   return OS;
13501 }
13502 
13503 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::BlockDisposition BD) {
13504   switch (BD) {
13505   case ScalarEvolution::DoesNotDominateBlock:
13506     OS << "DoesNotDominate";
13507     break;
13508   case ScalarEvolution::DominatesBlock:
13509     OS << "Dominates";
13510     break;
13511   case ScalarEvolution::ProperlyDominatesBlock:
13512     OS << "ProperlyDominates";
13513     break;
13514   }
13515   return OS;
13516 }
13517 }
13518 
13519 void ScalarEvolution::print(raw_ostream &OS) const {
13520   // ScalarEvolution's implementation of the print method is to print
13521   // out SCEV values of all instructions that are interesting. Doing
13522   // this potentially causes it to create new SCEV objects though,
13523   // which technically conflicts with the const qualifier. This isn't
13524   // observable from outside the class though, so casting away the
13525   // const isn't dangerous.
13526   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13527 
13528   if (ClassifyExpressions) {
13529     OS << "Classifying expressions for: ";
13530     F.printAsOperand(OS, /*PrintType=*/false);
13531     OS << "\n";
13532     for (Instruction &I : instructions(F))
13533       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13534         OS << I << '\n';
13535         OS << "  -->  ";
13536         const SCEV *SV = SE.getSCEV(&I);
13537         SV->print(OS);
13538         if (!isa<SCEVCouldNotCompute>(SV)) {
13539           OS << " U: ";
13540           SE.getUnsignedRange(SV).print(OS);
13541           OS << " S: ";
13542           SE.getSignedRange(SV).print(OS);
13543         }
13544 
13545         const Loop *L = LI.getLoopFor(I.getParent());
13546 
13547         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13548         if (AtUse != SV) {
13549           OS << "  -->  ";
13550           AtUse->print(OS);
13551           if (!isa<SCEVCouldNotCompute>(AtUse)) {
13552             OS << " U: ";
13553             SE.getUnsignedRange(AtUse).print(OS);
13554             OS << " S: ";
13555             SE.getSignedRange(AtUse).print(OS);
13556           }
13557         }
13558 
13559         if (L) {
13560           OS << "\t\t" "Exits: ";
13561           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13562           if (!SE.isLoopInvariant(ExitValue, L)) {
13563             OS << "<<Unknown>>";
13564           } else {
13565             OS << *ExitValue;
13566           }
13567 
13568           bool First = true;
13569           for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13570             if (First) {
13571               OS << "\t\t" "LoopDispositions: { ";
13572               First = false;
13573             } else {
13574               OS << ", ";
13575             }
13576 
13577             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13578             OS << ": " << SE.getLoopDisposition(SV, Iter);
13579           }
13580 
13581           for (const auto *InnerL : depth_first(L)) {
13582             if (InnerL == L)
13583               continue;
13584             if (First) {
13585               OS << "\t\t" "LoopDispositions: { ";
13586               First = false;
13587             } else {
13588               OS << ", ";
13589             }
13590 
13591             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13592             OS << ": " << SE.getLoopDisposition(SV, InnerL);
13593           }
13594 
13595           OS << " }";
13596         }
13597 
13598         OS << "\n";
13599       }
13600   }
13601 
13602   OS << "Determining loop execution counts for: ";
13603   F.printAsOperand(OS, /*PrintType=*/false);
13604   OS << "\n";
13605   for (Loop *I : LI)
13606     PrintLoopInfo(OS, &SE, I);
13607 }
13608 
13609 ScalarEvolution::LoopDisposition
13610 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13611   auto &Values = LoopDispositions[S];
13612   for (auto &V : Values) {
13613     if (V.getPointer() == L)
13614       return V.getInt();
13615   }
13616   Values.emplace_back(L, LoopVariant);
13617   LoopDisposition D = computeLoopDisposition(S, L);
13618   auto &Values2 = LoopDispositions[S];
13619   for (auto &V : llvm::reverse(Values2)) {
13620     if (V.getPointer() == L) {
13621       V.setInt(D);
13622       break;
13623     }
13624   }
13625   return D;
13626 }
13627 
13628 ScalarEvolution::LoopDisposition
13629 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13630   switch (S->getSCEVType()) {
13631   case scConstant:
13632   case scVScale:
13633     return LoopInvariant;
13634   case scAddRecExpr: {
13635     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13636 
13637     // If L is the addrec's loop, it's computable.
13638     if (AR->getLoop() == L)
13639       return LoopComputable;
13640 
13641     // Add recurrences are never invariant in the function-body (null loop).
13642     if (!L)
13643       return LoopVariant;
13644 
13645     // Everything that is not defined at loop entry is variant.
13646     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13647       return LoopVariant;
13648     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13649            " dominate the contained loop's header?");
13650 
13651     // This recurrence is invariant w.r.t. L if AR's loop contains L.
13652     if (AR->getLoop()->contains(L))
13653       return LoopInvariant;
13654 
13655     // This recurrence is variant w.r.t. L if any of its operands
13656     // are variant.
13657     for (const auto *Op : AR->operands())
13658       if (!isLoopInvariant(Op, L))
13659         return LoopVariant;
13660 
13661     // Otherwise it's loop-invariant.
13662     return LoopInvariant;
13663   }
13664   case scTruncate:
13665   case scZeroExtend:
13666   case scSignExtend:
13667   case scPtrToInt:
13668   case scAddExpr:
13669   case scMulExpr:
13670   case scUDivExpr:
13671   case scUMaxExpr:
13672   case scSMaxExpr:
13673   case scUMinExpr:
13674   case scSMinExpr:
13675   case scSequentialUMinExpr: {
13676     bool HasVarying = false;
13677     for (const auto *Op : S->operands()) {
13678       LoopDisposition D = getLoopDisposition(Op, L);
13679       if (D == LoopVariant)
13680         return LoopVariant;
13681       if (D == LoopComputable)
13682         HasVarying = true;
13683     }
13684     return HasVarying ? LoopComputable : LoopInvariant;
13685   }
13686   case scUnknown:
13687     // All non-instruction values are loop invariant.  All instructions are loop
13688     // invariant if they are not contained in the specified loop.
13689     // Instructions are never considered invariant in the function body
13690     // (null loop) because they are defined within the "loop".
13691     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13692       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13693     return LoopInvariant;
13694   case scCouldNotCompute:
13695     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13696   }
13697   llvm_unreachable("Unknown SCEV kind!");
13698 }
13699 
13700 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13701   return getLoopDisposition(S, L) == LoopInvariant;
13702 }
13703 
13704 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13705   return getLoopDisposition(S, L) == LoopComputable;
13706 }
13707 
13708 ScalarEvolution::BlockDisposition
13709 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13710   auto &Values = BlockDispositions[S];
13711   for (auto &V : Values) {
13712     if (V.getPointer() == BB)
13713       return V.getInt();
13714   }
13715   Values.emplace_back(BB, DoesNotDominateBlock);
13716   BlockDisposition D = computeBlockDisposition(S, BB);
13717   auto &Values2 = BlockDispositions[S];
13718   for (auto &V : llvm::reverse(Values2)) {
13719     if (V.getPointer() == BB) {
13720       V.setInt(D);
13721       break;
13722     }
13723   }
13724   return D;
13725 }
13726 
13727 ScalarEvolution::BlockDisposition
13728 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13729   switch (S->getSCEVType()) {
13730   case scConstant:
13731   case scVScale:
13732     return ProperlyDominatesBlock;
13733   case scAddRecExpr: {
13734     // This uses a "dominates" query instead of "properly dominates" query
13735     // to test for proper dominance too, because the instruction which
13736     // produces the addrec's value is a PHI, and a PHI effectively properly
13737     // dominates its entire containing block.
13738     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13739     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13740       return DoesNotDominateBlock;
13741 
13742     // Fall through into SCEVNAryExpr handling.
13743     [[fallthrough]];
13744   }
13745   case scTruncate:
13746   case scZeroExtend:
13747   case scSignExtend:
13748   case scPtrToInt:
13749   case scAddExpr:
13750   case scMulExpr:
13751   case scUDivExpr:
13752   case scUMaxExpr:
13753   case scSMaxExpr:
13754   case scUMinExpr:
13755   case scSMinExpr:
13756   case scSequentialUMinExpr: {
13757     bool Proper = true;
13758     for (const SCEV *NAryOp : S->operands()) {
13759       BlockDisposition D = getBlockDisposition(NAryOp, BB);
13760       if (D == DoesNotDominateBlock)
13761         return DoesNotDominateBlock;
13762       if (D == DominatesBlock)
13763         Proper = false;
13764     }
13765     return Proper ? ProperlyDominatesBlock : DominatesBlock;
13766   }
13767   case scUnknown:
13768     if (Instruction *I =
13769           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13770       if (I->getParent() == BB)
13771         return DominatesBlock;
13772       if (DT.properlyDominates(I->getParent(), BB))
13773         return ProperlyDominatesBlock;
13774       return DoesNotDominateBlock;
13775     }
13776     return ProperlyDominatesBlock;
13777   case scCouldNotCompute:
13778     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13779   }
13780   llvm_unreachable("Unknown SCEV kind!");
13781 }
13782 
13783 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13784   return getBlockDisposition(S, BB) >= DominatesBlock;
13785 }
13786 
13787 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13788   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13789 }
13790 
13791 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13792   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13793 }
13794 
13795 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13796                                                 bool Predicated) {
13797   auto &BECounts =
13798       Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13799   auto It = BECounts.find(L);
13800   if (It != BECounts.end()) {
13801     for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13802       for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
13803         if (!isa<SCEVConstant>(S)) {
13804           auto UserIt = BECountUsers.find(S);
13805           assert(UserIt != BECountUsers.end());
13806           UserIt->second.erase({L, Predicated});
13807         }
13808       }
13809     }
13810     BECounts.erase(It);
13811   }
13812 }
13813 
13814 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13815   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13816   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13817 
13818   while (!Worklist.empty()) {
13819     const SCEV *Curr = Worklist.pop_back_val();
13820     auto Users = SCEVUsers.find(Curr);
13821     if (Users != SCEVUsers.end())
13822       for (const auto *User : Users->second)
13823         if (ToForget.insert(User).second)
13824           Worklist.push_back(User);
13825   }
13826 
13827   for (const auto *S : ToForget)
13828     forgetMemoizedResultsImpl(S);
13829 
13830   for (auto I = PredicatedSCEVRewrites.begin();
13831        I != PredicatedSCEVRewrites.end();) {
13832     std::pair<const SCEV *, const Loop *> Entry = I->first;
13833     if (ToForget.count(Entry.first))
13834       PredicatedSCEVRewrites.erase(I++);
13835     else
13836       ++I;
13837   }
13838 }
13839 
13840 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13841   LoopDispositions.erase(S);
13842   BlockDispositions.erase(S);
13843   UnsignedRanges.erase(S);
13844   SignedRanges.erase(S);
13845   HasRecMap.erase(S);
13846   ConstantMultipleCache.erase(S);
13847 
13848   if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
13849     UnsignedWrapViaInductionTried.erase(AR);
13850     SignedWrapViaInductionTried.erase(AR);
13851   }
13852 
13853   auto ExprIt = ExprValueMap.find(S);
13854   if (ExprIt != ExprValueMap.end()) {
13855     for (Value *V : ExprIt->second) {
13856       auto ValueIt = ValueExprMap.find_as(V);
13857       if (ValueIt != ValueExprMap.end())
13858         ValueExprMap.erase(ValueIt);
13859     }
13860     ExprValueMap.erase(ExprIt);
13861   }
13862 
13863   auto ScopeIt = ValuesAtScopes.find(S);
13864   if (ScopeIt != ValuesAtScopes.end()) {
13865     for (const auto &Pair : ScopeIt->second)
13866       if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13867         llvm::erase(ValuesAtScopesUsers[Pair.second],
13868                     std::make_pair(Pair.first, S));
13869     ValuesAtScopes.erase(ScopeIt);
13870   }
13871 
13872   auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13873   if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13874     for (const auto &Pair : ScopeUserIt->second)
13875       llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13876     ValuesAtScopesUsers.erase(ScopeUserIt);
13877   }
13878 
13879   auto BEUsersIt = BECountUsers.find(S);
13880   if (BEUsersIt != BECountUsers.end()) {
13881     // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13882     auto Copy = BEUsersIt->second;
13883     for (const auto &Pair : Copy)
13884       forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13885     BECountUsers.erase(BEUsersIt);
13886   }
13887 
13888   auto FoldUser = FoldCacheUser.find(S);
13889   if (FoldUser != FoldCacheUser.end())
13890     for (auto &KV : FoldUser->second)
13891       FoldCache.erase(KV);
13892   FoldCacheUser.erase(S);
13893 }
13894 
13895 void
13896 ScalarEvolution::getUsedLoops(const SCEV *S,
13897                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13898   struct FindUsedLoops {
13899     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13900         : LoopsUsed(LoopsUsed) {}
13901     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13902     bool follow(const SCEV *S) {
13903       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13904         LoopsUsed.insert(AR->getLoop());
13905       return true;
13906     }
13907 
13908     bool isDone() const { return false; }
13909   };
13910 
13911   FindUsedLoops F(LoopsUsed);
13912   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13913 }
13914 
13915 void ScalarEvolution::getReachableBlocks(
13916     SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13917   SmallVector<BasicBlock *> Worklist;
13918   Worklist.push_back(&F.getEntryBlock());
13919   while (!Worklist.empty()) {
13920     BasicBlock *BB = Worklist.pop_back_val();
13921     if (!Reachable.insert(BB).second)
13922       continue;
13923 
13924     Value *Cond;
13925     BasicBlock *TrueBB, *FalseBB;
13926     if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
13927                                         m_BasicBlock(FalseBB)))) {
13928       if (auto *C = dyn_cast<ConstantInt>(Cond)) {
13929         Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
13930         continue;
13931       }
13932 
13933       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13934         const SCEV *L = getSCEV(Cmp->getOperand(0));
13935         const SCEV *R = getSCEV(Cmp->getOperand(1));
13936         if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
13937           Worklist.push_back(TrueBB);
13938           continue;
13939         }
13940         if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
13941                                               R)) {
13942           Worklist.push_back(FalseBB);
13943           continue;
13944         }
13945       }
13946     }
13947 
13948     append_range(Worklist, successors(BB));
13949   }
13950 }
13951 
13952 void ScalarEvolution::verify() const {
13953   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13954   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13955 
13956   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13957 
13958   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13959   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13960     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13961 
13962     const SCEV *visitConstant(const SCEVConstant *Constant) {
13963       return SE.getConstant(Constant->getAPInt());
13964     }
13965 
13966     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13967       return SE.getUnknown(Expr->getValue());
13968     }
13969 
13970     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13971       return SE.getCouldNotCompute();
13972     }
13973   };
13974 
13975   SCEVMapper SCM(SE2);
13976   SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13977   SE2.getReachableBlocks(ReachableBlocks, F);
13978 
13979   auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
13980     if (containsUndefs(Old) || containsUndefs(New)) {
13981       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13982       // not propagate undef aggressively).  This means we can (and do) fail
13983       // verification in cases where a transform makes a value go from "undef"
13984       // to "undef+1" (say).  The transform is fine, since in both cases the
13985       // result is "undef", but SCEV thinks the value increased by 1.
13986       return nullptr;
13987     }
13988 
13989     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13990     const SCEV *Delta = SE2.getMinusSCEV(Old, New);
13991     if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
13992       return nullptr;
13993 
13994     return Delta;
13995   };
13996 
13997   while (!LoopStack.empty()) {
13998     auto *L = LoopStack.pop_back_val();
13999     llvm::append_range(LoopStack, *L);
14000 
14001     // Only verify BECounts in reachable loops. For an unreachable loop,
14002     // any BECount is legal.
14003     if (!ReachableBlocks.contains(L->getHeader()))
14004       continue;
14005 
14006     // Only verify cached BECounts. Computing new BECounts may change the
14007     // results of subsequent SCEV uses.
14008     auto It = BackedgeTakenCounts.find(L);
14009     if (It == BackedgeTakenCounts.end())
14010       continue;
14011 
14012     auto *CurBECount =
14013         SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14014     auto *NewBECount = SE2.getBackedgeTakenCount(L);
14015 
14016     if (CurBECount == SE2.getCouldNotCompute() ||
14017         NewBECount == SE2.getCouldNotCompute()) {
14018       // NB! This situation is legal, but is very suspicious -- whatever pass
14019       // change the loop to make a trip count go from could not compute to
14020       // computable or vice-versa *should have* invalidated SCEV.  However, we
14021       // choose not to assert here (for now) since we don't want false
14022       // positives.
14023       continue;
14024     }
14025 
14026     if (SE.getTypeSizeInBits(CurBECount->getType()) >
14027         SE.getTypeSizeInBits(NewBECount->getType()))
14028       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14029     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14030              SE.getTypeSizeInBits(NewBECount->getType()))
14031       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14032 
14033     const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14034     if (Delta && !Delta->isZero()) {
14035       dbgs() << "Trip Count for " << *L << " Changed!\n";
14036       dbgs() << "Old: " << *CurBECount << "\n";
14037       dbgs() << "New: " << *NewBECount << "\n";
14038       dbgs() << "Delta: " << *Delta << "\n";
14039       std::abort();
14040     }
14041   }
14042 
14043   // Collect all valid loops currently in LoopInfo.
14044   SmallPtrSet<Loop *, 32> ValidLoops;
14045   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14046   while (!Worklist.empty()) {
14047     Loop *L = Worklist.pop_back_val();
14048     if (ValidLoops.insert(L).second)
14049       Worklist.append(L->begin(), L->end());
14050   }
14051   for (const auto &KV : ValueExprMap) {
14052 #ifndef NDEBUG
14053     // Check for SCEV expressions referencing invalid/deleted loops.
14054     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14055       assert(ValidLoops.contains(AR->getLoop()) &&
14056              "AddRec references invalid loop");
14057     }
14058 #endif
14059 
14060     // Check that the value is also part of the reverse map.
14061     auto It = ExprValueMap.find(KV.second);
14062     if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14063       dbgs() << "Value " << *KV.first
14064              << " is in ValueExprMap but not in ExprValueMap\n";
14065       std::abort();
14066     }
14067 
14068     if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14069       if (!ReachableBlocks.contains(I->getParent()))
14070         continue;
14071       const SCEV *OldSCEV = SCM.visit(KV.second);
14072       const SCEV *NewSCEV = SE2.getSCEV(I);
14073       const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14074       if (Delta && !Delta->isZero()) {
14075         dbgs() << "SCEV for value " << *I << " changed!\n"
14076                << "Old: " << *OldSCEV << "\n"
14077                << "New: " << *NewSCEV << "\n"
14078                << "Delta: " << *Delta << "\n";
14079         std::abort();
14080       }
14081     }
14082   }
14083 
14084   for (const auto &KV : ExprValueMap) {
14085     for (Value *V : KV.second) {
14086       auto It = ValueExprMap.find_as(V);
14087       if (It == ValueExprMap.end()) {
14088         dbgs() << "Value " << *V
14089                << " is in ExprValueMap but not in ValueExprMap\n";
14090         std::abort();
14091       }
14092       if (It->second != KV.first) {
14093         dbgs() << "Value " << *V << " mapped to " << *It->second
14094                << " rather than " << *KV.first << "\n";
14095         std::abort();
14096       }
14097     }
14098   }
14099 
14100   // Verify integrity of SCEV users.
14101   for (const auto &S : UniqueSCEVs) {
14102     for (const auto *Op : S.operands()) {
14103       // We do not store dependencies of constants.
14104       if (isa<SCEVConstant>(Op))
14105         continue;
14106       auto It = SCEVUsers.find(Op);
14107       if (It != SCEVUsers.end() && It->second.count(&S))
14108         continue;
14109       dbgs() << "Use of operand  " << *Op << " by user " << S
14110              << " is not being tracked!\n";
14111       std::abort();
14112     }
14113   }
14114 
14115   // Verify integrity of ValuesAtScopes users.
14116   for (const auto &ValueAndVec : ValuesAtScopes) {
14117     const SCEV *Value = ValueAndVec.first;
14118     for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14119       const Loop *L = LoopAndValueAtScope.first;
14120       const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14121       if (!isa<SCEVConstant>(ValueAtScope)) {
14122         auto It = ValuesAtScopesUsers.find(ValueAtScope);
14123         if (It != ValuesAtScopesUsers.end() &&
14124             is_contained(It->second, std::make_pair(L, Value)))
14125           continue;
14126         dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14127                << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14128         std::abort();
14129       }
14130     }
14131   }
14132 
14133   for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14134     const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14135     for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14136       const Loop *L = LoopAndValue.first;
14137       const SCEV *Value = LoopAndValue.second;
14138       assert(!isa<SCEVConstant>(Value));
14139       auto It = ValuesAtScopes.find(Value);
14140       if (It != ValuesAtScopes.end() &&
14141           is_contained(It->second, std::make_pair(L, ValueAtScope)))
14142         continue;
14143       dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14144              << *ValueAtScope << " missing in ValuesAtScopes\n";
14145       std::abort();
14146     }
14147   }
14148 
14149   // Verify integrity of BECountUsers.
14150   auto VerifyBECountUsers = [&](bool Predicated) {
14151     auto &BECounts =
14152         Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14153     for (const auto &LoopAndBEInfo : BECounts) {
14154       for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14155         for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14156           if (!isa<SCEVConstant>(S)) {
14157             auto UserIt = BECountUsers.find(S);
14158             if (UserIt != BECountUsers.end() &&
14159                 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14160               continue;
14161             dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14162                    << " missing from BECountUsers\n";
14163             std::abort();
14164           }
14165         }
14166       }
14167     }
14168   };
14169   VerifyBECountUsers(/* Predicated */ false);
14170   VerifyBECountUsers(/* Predicated */ true);
14171 
14172   // Verify intergity of loop disposition cache.
14173   for (auto &[S, Values] : LoopDispositions) {
14174     for (auto [Loop, CachedDisposition] : Values) {
14175       const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14176       if (CachedDisposition != RecomputedDisposition) {
14177         dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14178                << " is incorrect: cached " << CachedDisposition << ", actual "
14179                << RecomputedDisposition << "\n";
14180         std::abort();
14181       }
14182     }
14183   }
14184 
14185   // Verify integrity of the block disposition cache.
14186   for (auto &[S, Values] : BlockDispositions) {
14187     for (auto [BB, CachedDisposition] : Values) {
14188       const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14189       if (CachedDisposition != RecomputedDisposition) {
14190         dbgs() << "Cached disposition of " << *S << " for block %"
14191                << BB->getName() << " is incorrect: cached " << CachedDisposition
14192                << ", actual " << RecomputedDisposition << "\n";
14193         std::abort();
14194       }
14195     }
14196   }
14197 
14198   // Verify FoldCache/FoldCacheUser caches.
14199   for (auto [FoldID, Expr] : FoldCache) {
14200     auto I = FoldCacheUser.find(Expr);
14201     if (I == FoldCacheUser.end()) {
14202       dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14203              << "!\n";
14204       std::abort();
14205     }
14206     if (!is_contained(I->second, FoldID)) {
14207       dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14208       std::abort();
14209     }
14210   }
14211   for (auto [Expr, IDs] : FoldCacheUser) {
14212     for (auto &FoldID : IDs) {
14213       auto I = FoldCache.find(FoldID);
14214       if (I == FoldCache.end()) {
14215         dbgs() << "Missing entry in FoldCache for expression " << *Expr
14216                << "!\n";
14217         std::abort();
14218       }
14219       if (I->second != Expr) {
14220         dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: "
14221                << *I->second << " != " << *Expr << "!\n";
14222         std::abort();
14223       }
14224     }
14225   }
14226 
14227   // Verify that ConstantMultipleCache computations are correct. We check that
14228   // cached multiples and recomputed multiples are multiples of each other to
14229   // verify correctness. It is possible that a recomputed multiple is different
14230   // from the cached multiple due to strengthened no wrap flags or changes in
14231   // KnownBits computations.
14232   for (auto [S, Multiple] : ConstantMultipleCache) {
14233     APInt RecomputedMultiple = SE2.getConstantMultiple(S);
14234     if ((Multiple != 0 && RecomputedMultiple != 0 &&
14235          Multiple.urem(RecomputedMultiple) != 0 &&
14236          RecomputedMultiple.urem(Multiple) != 0)) {
14237       dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
14238              << *S << " : Computed " << RecomputedMultiple
14239              << " but cache contains " << Multiple << "!\n";
14240       std::abort();
14241     }
14242   }
14243 }
14244 
14245 bool ScalarEvolution::invalidate(
14246     Function &F, const PreservedAnalyses &PA,
14247     FunctionAnalysisManager::Invalidator &Inv) {
14248   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
14249   // of its dependencies is invalidated.
14250   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
14251   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
14252          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
14253          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
14254          Inv.invalidate<LoopAnalysis>(F, PA);
14255 }
14256 
14257 AnalysisKey ScalarEvolutionAnalysis::Key;
14258 
14259 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
14260                                              FunctionAnalysisManager &AM) {
14261   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
14262   auto &AC = AM.getResult<AssumptionAnalysis>(F);
14263   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
14264   auto &LI = AM.getResult<LoopAnalysis>(F);
14265   return ScalarEvolution(F, TLI, AC, DT, LI);
14266 }
14267 
14268 PreservedAnalyses
14269 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
14270   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
14271   return PreservedAnalyses::all();
14272 }
14273 
14274 PreservedAnalyses
14275 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
14276   // For compatibility with opt's -analyze feature under legacy pass manager
14277   // which was not ported to NPM. This keeps tests using
14278   // update_analyze_test_checks.py working.
14279   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
14280      << F.getName() << "':\n";
14281   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
14282   return PreservedAnalyses::all();
14283 }
14284 
14285 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
14286                       "Scalar Evolution Analysis", false, true)
14287 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
14288 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
14289 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
14290 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
14291 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
14292                     "Scalar Evolution Analysis", false, true)
14293 
14294 char ScalarEvolutionWrapperPass::ID = 0;
14295 
14296 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
14297   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
14298 }
14299 
14300 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
14301   SE.reset(new ScalarEvolution(
14302       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
14303       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
14304       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
14305       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
14306   return false;
14307 }
14308 
14309 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
14310 
14311 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
14312   SE->print(OS);
14313 }
14314 
14315 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
14316   if (!VerifySCEV)
14317     return;
14318 
14319   SE->verify();
14320 }
14321 
14322 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
14323   AU.setPreservesAll();
14324   AU.addRequiredTransitive<AssumptionCacheTracker>();
14325   AU.addRequiredTransitive<LoopInfoWrapperPass>();
14326   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
14327   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
14328 }
14329 
14330 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
14331                                                         const SCEV *RHS) {
14332   return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
14333 }
14334 
14335 const SCEVPredicate *
14336 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
14337                                      const SCEV *LHS, const SCEV *RHS) {
14338   FoldingSetNodeID ID;
14339   assert(LHS->getType() == RHS->getType() &&
14340          "Type mismatch between LHS and RHS");
14341   // Unique this node based on the arguments
14342   ID.AddInteger(SCEVPredicate::P_Compare);
14343   ID.AddInteger(Pred);
14344   ID.AddPointer(LHS);
14345   ID.AddPointer(RHS);
14346   void *IP = nullptr;
14347   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14348     return S;
14349   SCEVComparePredicate *Eq = new (SCEVAllocator)
14350     SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
14351   UniquePreds.InsertNode(Eq, IP);
14352   return Eq;
14353 }
14354 
14355 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
14356     const SCEVAddRecExpr *AR,
14357     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14358   FoldingSetNodeID ID;
14359   // Unique this node based on the arguments
14360   ID.AddInteger(SCEVPredicate::P_Wrap);
14361   ID.AddPointer(AR);
14362   ID.AddInteger(AddedFlags);
14363   void *IP = nullptr;
14364   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14365     return S;
14366   auto *OF = new (SCEVAllocator)
14367       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
14368   UniquePreds.InsertNode(OF, IP);
14369   return OF;
14370 }
14371 
14372 namespace {
14373 
14374 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
14375 public:
14376 
14377   /// Rewrites \p S in the context of a loop L and the SCEV predication
14378   /// infrastructure.
14379   ///
14380   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
14381   /// equivalences present in \p Pred.
14382   ///
14383   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
14384   /// \p NewPreds such that the result will be an AddRecExpr.
14385   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
14386                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14387                              const SCEVPredicate *Pred) {
14388     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
14389     return Rewriter.visit(S);
14390   }
14391 
14392   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14393     if (Pred) {
14394       if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
14395         for (const auto *Pred : U->getPredicates())
14396           if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
14397             if (IPred->getLHS() == Expr &&
14398                 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14399               return IPred->getRHS();
14400       } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
14401         if (IPred->getLHS() == Expr &&
14402             IPred->getPredicate() == ICmpInst::ICMP_EQ)
14403           return IPred->getRHS();
14404       }
14405     }
14406     return convertToAddRecWithPreds(Expr);
14407   }
14408 
14409   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14410     const SCEV *Operand = visit(Expr->getOperand());
14411     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14412     if (AR && AR->getLoop() == L && AR->isAffine()) {
14413       // This couldn't be folded because the operand didn't have the nuw
14414       // flag. Add the nusw flag as an assumption that we could make.
14415       const SCEV *Step = AR->getStepRecurrence(SE);
14416       Type *Ty = Expr->getType();
14417       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
14418         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
14419                                 SE.getSignExtendExpr(Step, Ty), L,
14420                                 AR->getNoWrapFlags());
14421     }
14422     return SE.getZeroExtendExpr(Operand, Expr->getType());
14423   }
14424 
14425   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14426     const SCEV *Operand = visit(Expr->getOperand());
14427     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14428     if (AR && AR->getLoop() == L && AR->isAffine()) {
14429       // This couldn't be folded because the operand didn't have the nsw
14430       // flag. Add the nssw flag as an assumption that we could make.
14431       const SCEV *Step = AR->getStepRecurrence(SE);
14432       Type *Ty = Expr->getType();
14433       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
14434         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
14435                                 SE.getSignExtendExpr(Step, Ty), L,
14436                                 AR->getNoWrapFlags());
14437     }
14438     return SE.getSignExtendExpr(Operand, Expr->getType());
14439   }
14440 
14441 private:
14442   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
14443                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14444                         const SCEVPredicate *Pred)
14445       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
14446 
14447   bool addOverflowAssumption(const SCEVPredicate *P) {
14448     if (!NewPreds) {
14449       // Check if we've already made this assumption.
14450       return Pred && Pred->implies(P);
14451     }
14452     NewPreds->insert(P);
14453     return true;
14454   }
14455 
14456   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
14457                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14458     auto *A = SE.getWrapPredicate(AR, AddedFlags);
14459     return addOverflowAssumption(A);
14460   }
14461 
14462   // If \p Expr represents a PHINode, we try to see if it can be represented
14463   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
14464   // to add this predicate as a runtime overflow check, we return the AddRec.
14465   // If \p Expr does not meet these conditions (is not a PHI node, or we
14466   // couldn't create an AddRec for it, or couldn't add the predicate), we just
14467   // return \p Expr.
14468   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
14469     if (!isa<PHINode>(Expr->getValue()))
14470       return Expr;
14471     std::optional<
14472         std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
14473         PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
14474     if (!PredicatedRewrite)
14475       return Expr;
14476     for (const auto *P : PredicatedRewrite->second){
14477       // Wrap predicates from outer loops are not supported.
14478       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
14479         if (L != WP->getExpr()->getLoop())
14480           return Expr;
14481       }
14482       if (!addOverflowAssumption(P))
14483         return Expr;
14484     }
14485     return PredicatedRewrite->first;
14486   }
14487 
14488   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
14489   const SCEVPredicate *Pred;
14490   const Loop *L;
14491 };
14492 
14493 } // end anonymous namespace
14494 
14495 const SCEV *
14496 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
14497                                        const SCEVPredicate &Preds) {
14498   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
14499 }
14500 
14501 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
14502     const SCEV *S, const Loop *L,
14503     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
14504   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
14505   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
14506   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
14507 
14508   if (!AddRec)
14509     return nullptr;
14510 
14511   // Since the transformation was successful, we can now transfer the SCEV
14512   // predicates.
14513   for (const auto *P : TransformPreds)
14514     Preds.insert(P);
14515 
14516   return AddRec;
14517 }
14518 
14519 /// SCEV predicates
14520 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
14521                              SCEVPredicateKind Kind)
14522     : FastID(ID), Kind(Kind) {}
14523 
14524 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
14525                                    const ICmpInst::Predicate Pred,
14526                                    const SCEV *LHS, const SCEV *RHS)
14527   : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
14528   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
14529   assert(LHS != RHS && "LHS and RHS are the same SCEV");
14530 }
14531 
14532 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
14533   const auto *Op = dyn_cast<SCEVComparePredicate>(N);
14534 
14535   if (!Op)
14536     return false;
14537 
14538   if (Pred != ICmpInst::ICMP_EQ)
14539     return false;
14540 
14541   return Op->LHS == LHS && Op->RHS == RHS;
14542 }
14543 
14544 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
14545 
14546 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
14547   if (Pred == ICmpInst::ICMP_EQ)
14548     OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
14549   else
14550     OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
14551                      << *RHS << "\n";
14552 
14553 }
14554 
14555 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
14556                                      const SCEVAddRecExpr *AR,
14557                                      IncrementWrapFlags Flags)
14558     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
14559 
14560 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
14561 
14562 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
14563   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
14564 
14565   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
14566 }
14567 
14568 bool SCEVWrapPredicate::isAlwaysTrue() const {
14569   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14570   IncrementWrapFlags IFlags = Flags;
14571 
14572   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14573     IFlags = clearFlags(IFlags, IncrementNSSW);
14574 
14575   return IFlags == IncrementAnyWrap;
14576 }
14577 
14578 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14579   OS.indent(Depth) << *getExpr() << " Added Flags: ";
14580   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14581     OS << "<nusw>";
14582   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14583     OS << "<nssw>";
14584   OS << "\n";
14585 }
14586 
14587 SCEVWrapPredicate::IncrementWrapFlags
14588 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14589                                    ScalarEvolution &SE) {
14590   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14591   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14592 
14593   // We can safely transfer the NSW flag as NSSW.
14594   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14595     ImpliedFlags = IncrementNSSW;
14596 
14597   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14598     // If the increment is positive, the SCEV NUW flag will also imply the
14599     // WrapPredicate NUSW flag.
14600     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14601       if (Step->getValue()->getValue().isNonNegative())
14602         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14603   }
14604 
14605   return ImpliedFlags;
14606 }
14607 
14608 /// Union predicates don't get cached so create a dummy set ID for it.
14609 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14610   : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14611   for (const auto *P : Preds)
14612     add(P);
14613 }
14614 
14615 bool SCEVUnionPredicate::isAlwaysTrue() const {
14616   return all_of(Preds,
14617                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14618 }
14619 
14620 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14621   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14622     return all_of(Set->Preds,
14623                   [this](const SCEVPredicate *I) { return this->implies(I); });
14624 
14625   return any_of(Preds,
14626                 [N](const SCEVPredicate *I) { return I->implies(N); });
14627 }
14628 
14629 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14630   for (const auto *Pred : Preds)
14631     Pred->print(OS, Depth);
14632 }
14633 
14634 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14635   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14636     for (const auto *Pred : Set->Preds)
14637       add(Pred);
14638     return;
14639   }
14640 
14641   Preds.push_back(N);
14642 }
14643 
14644 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14645                                                      Loop &L)
14646     : SE(SE), L(L) {
14647   SmallVector<const SCEVPredicate*, 4> Empty;
14648   Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14649 }
14650 
14651 void ScalarEvolution::registerUser(const SCEV *User,
14652                                    ArrayRef<const SCEV *> Ops) {
14653   for (const auto *Op : Ops)
14654     // We do not expect that forgetting cached data for SCEVConstants will ever
14655     // open any prospects for sharpening or introduce any correctness issues,
14656     // so we don't bother storing their dependencies.
14657     if (!isa<SCEVConstant>(Op))
14658       SCEVUsers[Op].insert(User);
14659 }
14660 
14661 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14662   const SCEV *Expr = SE.getSCEV(V);
14663   RewriteEntry &Entry = RewriteMap[Expr];
14664 
14665   // If we already have an entry and the version matches, return it.
14666   if (Entry.second && Generation == Entry.first)
14667     return Entry.second;
14668 
14669   // We found an entry but it's stale. Rewrite the stale entry
14670   // according to the current predicate.
14671   if (Entry.second)
14672     Expr = Entry.second;
14673 
14674   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14675   Entry = {Generation, NewSCEV};
14676 
14677   return NewSCEV;
14678 }
14679 
14680 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14681   if (!BackedgeCount) {
14682     SmallVector<const SCEVPredicate *, 4> Preds;
14683     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14684     for (const auto *P : Preds)
14685       addPredicate(*P);
14686   }
14687   return BackedgeCount;
14688 }
14689 
14690 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14691   if (Preds->implies(&Pred))
14692     return;
14693 
14694   auto &OldPreds = Preds->getPredicates();
14695   SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14696   NewPreds.push_back(&Pred);
14697   Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14698   updateGeneration();
14699 }
14700 
14701 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14702   return *Preds;
14703 }
14704 
14705 void PredicatedScalarEvolution::updateGeneration() {
14706   // If the generation number wrapped recompute everything.
14707   if (++Generation == 0) {
14708     for (auto &II : RewriteMap) {
14709       const SCEV *Rewritten = II.second.second;
14710       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14711     }
14712   }
14713 }
14714 
14715 void PredicatedScalarEvolution::setNoOverflow(
14716     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14717   const SCEV *Expr = getSCEV(V);
14718   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14719 
14720   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14721 
14722   // Clear the statically implied flags.
14723   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14724   addPredicate(*SE.getWrapPredicate(AR, Flags));
14725 
14726   auto II = FlagsMap.insert({V, Flags});
14727   if (!II.second)
14728     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14729 }
14730 
14731 bool PredicatedScalarEvolution::hasNoOverflow(
14732     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14733   const SCEV *Expr = getSCEV(V);
14734   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14735 
14736   Flags = SCEVWrapPredicate::clearFlags(
14737       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14738 
14739   auto II = FlagsMap.find(V);
14740 
14741   if (II != FlagsMap.end())
14742     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14743 
14744   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14745 }
14746 
14747 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14748   const SCEV *Expr = this->getSCEV(V);
14749   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14750   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14751 
14752   if (!New)
14753     return nullptr;
14754 
14755   for (const auto *P : NewPreds)
14756     addPredicate(*P);
14757 
14758   RewriteMap[SE.getSCEV(V)] = {Generation, New};
14759   return New;
14760 }
14761 
14762 PredicatedScalarEvolution::PredicatedScalarEvolution(
14763     const PredicatedScalarEvolution &Init)
14764   : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14765     Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14766     Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14767   for (auto I : Init.FlagsMap)
14768     FlagsMap.insert(I);
14769 }
14770 
14771 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14772   // For each block.
14773   for (auto *BB : L.getBlocks())
14774     for (auto &I : *BB) {
14775       if (!SE.isSCEVable(I.getType()))
14776         continue;
14777 
14778       auto *Expr = SE.getSCEV(&I);
14779       auto II = RewriteMap.find(Expr);
14780 
14781       if (II == RewriteMap.end())
14782         continue;
14783 
14784       // Don't print things that are not interesting.
14785       if (II->second.second == Expr)
14786         continue;
14787 
14788       OS.indent(Depth) << "[PSE]" << I << ":\n";
14789       OS.indent(Depth + 2) << *Expr << "\n";
14790       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14791     }
14792 }
14793 
14794 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14795 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14796 // for URem with constant power-of-2 second operands.
14797 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14798 // 4, A / B becomes X / 8).
14799 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14800                                 const SCEV *&RHS) {
14801   // Try to match 'zext (trunc A to iB) to iY', which is used
14802   // for URem with constant power-of-2 second operands. Make sure the size of
14803   // the operand A matches the size of the whole expressions.
14804   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14805     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14806       LHS = Trunc->getOperand();
14807       // Bail out if the type of the LHS is larger than the type of the
14808       // expression for now.
14809       if (getTypeSizeInBits(LHS->getType()) >
14810           getTypeSizeInBits(Expr->getType()))
14811         return false;
14812       if (LHS->getType() != Expr->getType())
14813         LHS = getZeroExtendExpr(LHS, Expr->getType());
14814       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14815                         << getTypeSizeInBits(Trunc->getType()));
14816       return true;
14817     }
14818   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14819   if (Add == nullptr || Add->getNumOperands() != 2)
14820     return false;
14821 
14822   const SCEV *A = Add->getOperand(1);
14823   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14824 
14825   if (Mul == nullptr)
14826     return false;
14827 
14828   const auto MatchURemWithDivisor = [&](const SCEV *B) {
14829     // (SomeExpr + (-(SomeExpr / B) * B)).
14830     if (Expr == getURemExpr(A, B)) {
14831       LHS = A;
14832       RHS = B;
14833       return true;
14834     }
14835     return false;
14836   };
14837 
14838   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14839   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14840     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14841            MatchURemWithDivisor(Mul->getOperand(2));
14842 
14843   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14844   if (Mul->getNumOperands() == 2)
14845     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14846            MatchURemWithDivisor(Mul->getOperand(0)) ||
14847            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14848            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14849   return false;
14850 }
14851 
14852 const SCEV *
14853 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14854   SmallVector<BasicBlock*, 16> ExitingBlocks;
14855   L->getExitingBlocks(ExitingBlocks);
14856 
14857   // Form an expression for the maximum exit count possible for this loop. We
14858   // merge the max and exact information to approximate a version of
14859   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14860   SmallVector<const SCEV*, 4> ExitCounts;
14861   for (BasicBlock *ExitingBB : ExitingBlocks) {
14862     const SCEV *ExitCount =
14863         getExitCount(L, ExitingBB, ScalarEvolution::SymbolicMaximum);
14864     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14865       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14866              "We should only have known counts for exiting blocks that "
14867              "dominate latch!");
14868       ExitCounts.push_back(ExitCount);
14869     }
14870   }
14871   if (ExitCounts.empty())
14872     return getCouldNotCompute();
14873   return getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
14874 }
14875 
14876 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14877 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14878 /// replacement is loop invariant in the loop of the AddRec.
14879 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14880   const DenseMap<const SCEV *, const SCEV *> &Map;
14881 
14882 public:
14883   SCEVLoopGuardRewriter(ScalarEvolution &SE,
14884                         DenseMap<const SCEV *, const SCEV *> &M)
14885       : SCEVRewriteVisitor(SE), Map(M) {}
14886 
14887   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14888 
14889   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14890     auto I = Map.find(Expr);
14891     if (I == Map.end())
14892       return Expr;
14893     return I->second;
14894   }
14895 
14896   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14897     auto I = Map.find(Expr);
14898     if (I == Map.end()) {
14899       // If we didn't find the extact ZExt expr in the map, check if there's an
14900       // entry for a smaller ZExt we can use instead.
14901       Type *Ty = Expr->getType();
14902       const SCEV *Op = Expr->getOperand(0);
14903       unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
14904       while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
14905              Bitwidth > Op->getType()->getScalarSizeInBits()) {
14906         Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
14907         auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
14908         auto I = Map.find(NarrowExt);
14909         if (I != Map.end())
14910           return SE.getZeroExtendExpr(I->second, Ty);
14911         Bitwidth = Bitwidth / 2;
14912       }
14913 
14914       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14915           Expr);
14916     }
14917     return I->second;
14918   }
14919 
14920   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14921     auto I = Map.find(Expr);
14922     if (I == Map.end())
14923       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSignExtendExpr(
14924           Expr);
14925     return I->second;
14926   }
14927 
14928   const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
14929     auto I = Map.find(Expr);
14930     if (I == Map.end())
14931       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitUMinExpr(Expr);
14932     return I->second;
14933   }
14934 
14935   const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
14936     auto I = Map.find(Expr);
14937     if (I == Map.end())
14938       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSMinExpr(Expr);
14939     return I->second;
14940   }
14941 };
14942 
14943 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14944   SmallVector<const SCEV *> ExprsToRewrite;
14945   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14946                               const SCEV *RHS,
14947                               DenseMap<const SCEV *, const SCEV *>
14948                                   &RewriteMap) {
14949     // WARNING: It is generally unsound to apply any wrap flags to the proposed
14950     // replacement SCEV which isn't directly implied by the structure of that
14951     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
14952     // legal.  See the scoping rules for flags in the header to understand why.
14953 
14954     // If LHS is a constant, apply information to the other expression.
14955     if (isa<SCEVConstant>(LHS)) {
14956       std::swap(LHS, RHS);
14957       Predicate = CmpInst::getSwappedPredicate(Predicate);
14958     }
14959 
14960     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
14961     // create this form when combining two checks of the form (X u< C2 + C1) and
14962     // (X >=u C1).
14963     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14964                                  &ExprsToRewrite]() {
14965       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14966       if (!AddExpr || AddExpr->getNumOperands() != 2)
14967         return false;
14968 
14969       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14970       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14971       auto *C2 = dyn_cast<SCEVConstant>(RHS);
14972       if (!C1 || !C2 || !LHSUnknown)
14973         return false;
14974 
14975       auto ExactRegion =
14976           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14977               .sub(C1->getAPInt());
14978 
14979       // Bail out, unless we have a non-wrapping, monotonic range.
14980       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14981         return false;
14982       auto I = RewriteMap.find(LHSUnknown);
14983       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14984       RewriteMap[LHSUnknown] = getUMaxExpr(
14985           getConstant(ExactRegion.getUnsignedMin()),
14986           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14987       ExprsToRewrite.push_back(LHSUnknown);
14988       return true;
14989     };
14990     if (MatchRangeCheckIdiom())
14991       return;
14992 
14993     // Return true if \p Expr is a MinMax SCEV expression with a non-negative
14994     // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
14995     // the non-constant operand and in \p LHS the constant operand.
14996     auto IsMinMaxSCEVWithNonNegativeConstant =
14997         [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
14998             const SCEV *&RHS) {
14999           if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15000             if (MinMax->getNumOperands() != 2)
15001               return false;
15002             if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15003               if (C->getAPInt().isNegative())
15004                 return false;
15005               SCTy = MinMax->getSCEVType();
15006               LHS = MinMax->getOperand(0);
15007               RHS = MinMax->getOperand(1);
15008               return true;
15009             }
15010           }
15011           return false;
15012         };
15013 
15014     // Checks whether Expr is a non-negative constant, and Divisor is a positive
15015     // constant, and returns their APInt in ExprVal and in DivisorVal.
15016     auto GetNonNegExprAndPosDivisor = [&](const SCEV *Expr, const SCEV *Divisor,
15017                                           APInt &ExprVal, APInt &DivisorVal) {
15018       auto *ConstExpr = dyn_cast<SCEVConstant>(Expr);
15019       auto *ConstDivisor = dyn_cast<SCEVConstant>(Divisor);
15020       if (!ConstExpr || !ConstDivisor)
15021         return false;
15022       ExprVal = ConstExpr->getAPInt();
15023       DivisorVal = ConstDivisor->getAPInt();
15024       return ExprVal.isNonNegative() && !DivisorVal.isNonPositive();
15025     };
15026 
15027     // Return a new SCEV that modifies \p Expr to the closest number divides by
15028     // \p Divisor and greater or equal than Expr.
15029     // For now, only handle constant Expr and Divisor.
15030     auto GetNextSCEVDividesByDivisor = [&](const SCEV *Expr,
15031                                            const SCEV *Divisor) {
15032       APInt ExprVal;
15033       APInt DivisorVal;
15034       if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15035         return Expr;
15036       APInt Rem = ExprVal.urem(DivisorVal);
15037       if (!Rem.isZero())
15038         // return the SCEV: Expr + Divisor - Expr % Divisor
15039         return getConstant(ExprVal + DivisorVal - Rem);
15040       return Expr;
15041     };
15042 
15043     // Return a new SCEV that modifies \p Expr to the closest number divides by
15044     // \p Divisor and less or equal than Expr.
15045     // For now, only handle constant Expr and Divisor.
15046     auto GetPreviousSCEVDividesByDivisor = [&](const SCEV *Expr,
15047                                                const SCEV *Divisor) {
15048       APInt ExprVal;
15049       APInt DivisorVal;
15050       if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15051         return Expr;
15052       APInt Rem = ExprVal.urem(DivisorVal);
15053       // return the SCEV: Expr - Expr % Divisor
15054       return getConstant(ExprVal - Rem);
15055     };
15056 
15057     // Apply divisibilty by \p Divisor on MinMaxExpr with constant values,
15058     // recursively. This is done by aligning up/down the constant value to the
15059     // Divisor.
15060     std::function<const SCEV *(const SCEV *, const SCEV *)>
15061         ApplyDivisibiltyOnMinMaxExpr = [&](const SCEV *MinMaxExpr,
15062                                            const SCEV *Divisor) {
15063           const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15064           SCEVTypes SCTy;
15065           if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15066                                                    MinMaxRHS))
15067             return MinMaxExpr;
15068           auto IsMin =
15069               isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15070           assert(isKnownNonNegative(MinMaxLHS) &&
15071                  "Expected non-negative operand!");
15072           auto *DivisibleExpr =
15073               IsMin ? GetPreviousSCEVDividesByDivisor(MinMaxLHS, Divisor)
15074                     : GetNextSCEVDividesByDivisor(MinMaxLHS, Divisor);
15075           SmallVector<const SCEV *> Ops = {
15076               ApplyDivisibiltyOnMinMaxExpr(MinMaxRHS, Divisor), DivisibleExpr};
15077           return getMinMaxExpr(SCTy, Ops);
15078         };
15079 
15080     // If we have LHS == 0, check if LHS is computing a property of some unknown
15081     // SCEV %v which we can rewrite %v to express explicitly.
15082     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
15083     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
15084         RHSC->getValue()->isNullValue()) {
15085       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15086       // explicitly express that.
15087       const SCEV *URemLHS = nullptr;
15088       const SCEV *URemRHS = nullptr;
15089       if (matchURem(LHS, URemLHS, URemRHS)) {
15090         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
15091           auto I = RewriteMap.find(LHSUnknown);
15092           const SCEV *RewrittenLHS =
15093               I != RewriteMap.end() ? I->second : LHSUnknown;
15094           RewrittenLHS = ApplyDivisibiltyOnMinMaxExpr(RewrittenLHS, URemRHS);
15095           const auto *Multiple =
15096               getMulExpr(getUDivExpr(RewrittenLHS, URemRHS), URemRHS);
15097           RewriteMap[LHSUnknown] = Multiple;
15098           ExprsToRewrite.push_back(LHSUnknown);
15099           return;
15100         }
15101       }
15102     }
15103 
15104     // Do not apply information for constants or if RHS contains an AddRec.
15105     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
15106       return;
15107 
15108     // If RHS is SCEVUnknown, make sure the information is applied to it.
15109     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
15110       std::swap(LHS, RHS);
15111       Predicate = CmpInst::getSwappedPredicate(Predicate);
15112     }
15113 
15114     // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15115     // and \p FromRewritten are the same (i.e. there has been no rewrite
15116     // registered for \p From), then puts this value in the list of rewritten
15117     // expressions.
15118     auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15119                           const SCEV *To) {
15120       if (From == FromRewritten)
15121         ExprsToRewrite.push_back(From);
15122       RewriteMap[From] = To;
15123     };
15124 
15125     // Checks whether \p S has already been rewritten. In that case returns the
15126     // existing rewrite because we want to chain further rewrites onto the
15127     // already rewritten value. Otherwise returns \p S.
15128     auto GetMaybeRewritten = [&](const SCEV *S) {
15129       auto I = RewriteMap.find(S);
15130       return I != RewriteMap.end() ? I->second : S;
15131     };
15132 
15133     // Check for the SCEV expression (A /u B) * B while B is a constant, inside
15134     // \p Expr. The check is done recuresively on \p Expr, which is assumed to
15135     // be a composition of Min/Max SCEVs. Return whether the SCEV expression (A
15136     // /u B) * B was found, and return the divisor B in \p DividesBy. For
15137     // example, if Expr = umin (umax ((A /u 8) * 8, 16), 64), return true since
15138     // (A /u 8) * 8 matched the pattern, and return the constant SCEV 8 in \p
15139     // DividesBy.
15140     std::function<bool(const SCEV *, const SCEV *&)> HasDivisibiltyInfo =
15141         [&](const SCEV *Expr, const SCEV *&DividesBy) {
15142           if (auto *Mul = dyn_cast<SCEVMulExpr>(Expr)) {
15143             if (Mul->getNumOperands() != 2)
15144               return false;
15145             auto *MulLHS = Mul->getOperand(0);
15146             auto *MulRHS = Mul->getOperand(1);
15147             if (isa<SCEVConstant>(MulLHS))
15148               std::swap(MulLHS, MulRHS);
15149             if (auto *Div = dyn_cast<SCEVUDivExpr>(MulLHS))
15150               if (Div->getOperand(1) == MulRHS) {
15151                 DividesBy = MulRHS;
15152                 return true;
15153               }
15154           }
15155           if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15156             return HasDivisibiltyInfo(MinMax->getOperand(0), DividesBy) ||
15157                    HasDivisibiltyInfo(MinMax->getOperand(1), DividesBy);
15158           return false;
15159         };
15160 
15161     // Return true if Expr known to divide by \p DividesBy.
15162     std::function<bool(const SCEV *, const SCEV *&)> IsKnownToDivideBy =
15163         [&](const SCEV *Expr, const SCEV *DividesBy) {
15164           if (getURemExpr(Expr, DividesBy)->isZero())
15165             return true;
15166           if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15167             return IsKnownToDivideBy(MinMax->getOperand(0), DividesBy) &&
15168                    IsKnownToDivideBy(MinMax->getOperand(1), DividesBy);
15169           return false;
15170         };
15171 
15172     const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15173     const SCEV *DividesBy = nullptr;
15174     if (HasDivisibiltyInfo(RewrittenLHS, DividesBy))
15175       // Check that the whole expression is divided by DividesBy
15176       DividesBy =
15177           IsKnownToDivideBy(RewrittenLHS, DividesBy) ? DividesBy : nullptr;
15178 
15179     // Collect rewrites for LHS and its transitive operands based on the
15180     // condition.
15181     // For min/max expressions, also apply the guard to its operands:
15182     //  'min(a, b) >= c'   ->   '(a >= c) and (b >= c)',
15183     //  'min(a, b) >  c'   ->   '(a >  c) and (b >  c)',
15184     //  'max(a, b) <= c'   ->   '(a <= c) and (b <= c)',
15185     //  'max(a, b) <  c'   ->   '(a <  c) and (b <  c)'.
15186 
15187     // We cannot express strict predicates in SCEV, so instead we replace them
15188     // with non-strict ones against plus or minus one of RHS depending on the
15189     // predicate.
15190     const SCEV *One = getOne(RHS->getType());
15191     switch (Predicate) {
15192       case CmpInst::ICMP_ULT:
15193         if (RHS->getType()->isPointerTy())
15194           return;
15195         RHS = getUMaxExpr(RHS, One);
15196         [[fallthrough]];
15197       case CmpInst::ICMP_SLT: {
15198         RHS = getMinusSCEV(RHS, One);
15199         RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15200         break;
15201       }
15202       case CmpInst::ICMP_UGT:
15203       case CmpInst::ICMP_SGT:
15204         RHS = getAddExpr(RHS, One);
15205         RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15206         break;
15207       case CmpInst::ICMP_ULE:
15208       case CmpInst::ICMP_SLE:
15209         RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15210         break;
15211       case CmpInst::ICMP_UGE:
15212       case CmpInst::ICMP_SGE:
15213         RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15214         break;
15215       default:
15216         break;
15217     }
15218 
15219     SmallVector<const SCEV *, 16> Worklist(1, LHS);
15220     SmallPtrSet<const SCEV *, 16> Visited;
15221 
15222     auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15223       append_range(Worklist, S->operands());
15224     };
15225 
15226     while (!Worklist.empty()) {
15227       const SCEV *From = Worklist.pop_back_val();
15228       if (isa<SCEVConstant>(From))
15229         continue;
15230       if (!Visited.insert(From).second)
15231         continue;
15232       const SCEV *FromRewritten = GetMaybeRewritten(From);
15233       const SCEV *To = nullptr;
15234 
15235       switch (Predicate) {
15236       case CmpInst::ICMP_ULT:
15237       case CmpInst::ICMP_ULE:
15238         To = getUMinExpr(FromRewritten, RHS);
15239         if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15240           EnqueueOperands(UMax);
15241         break;
15242       case CmpInst::ICMP_SLT:
15243       case CmpInst::ICMP_SLE:
15244         To = getSMinExpr(FromRewritten, RHS);
15245         if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15246           EnqueueOperands(SMax);
15247         break;
15248       case CmpInst::ICMP_UGT:
15249       case CmpInst::ICMP_UGE:
15250         To = getUMaxExpr(FromRewritten, RHS);
15251         if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15252           EnqueueOperands(UMin);
15253         break;
15254       case CmpInst::ICMP_SGT:
15255       case CmpInst::ICMP_SGE:
15256         To = getSMaxExpr(FromRewritten, RHS);
15257         if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15258           EnqueueOperands(SMin);
15259         break;
15260       case CmpInst::ICMP_EQ:
15261         if (isa<SCEVConstant>(RHS))
15262           To = RHS;
15263         break;
15264       case CmpInst::ICMP_NE:
15265         if (isa<SCEVConstant>(RHS) &&
15266             cast<SCEVConstant>(RHS)->getValue()->isNullValue()) {
15267           const SCEV *OneAlignedUp =
15268               DividesBy ? GetNextSCEVDividesByDivisor(One, DividesBy) : One;
15269           To = getUMaxExpr(FromRewritten, OneAlignedUp);
15270         }
15271         break;
15272       default:
15273         break;
15274       }
15275 
15276       if (To)
15277         AddRewrite(From, FromRewritten, To);
15278     }
15279   };
15280 
15281   BasicBlock *Header = L->getHeader();
15282   SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
15283   // First, collect information from assumptions dominating the loop.
15284   for (auto &AssumeVH : AC.assumptions()) {
15285     if (!AssumeVH)
15286       continue;
15287     auto *AssumeI = cast<CallInst>(AssumeVH);
15288     if (!DT.dominates(AssumeI, Header))
15289       continue;
15290     Terms.emplace_back(AssumeI->getOperand(0), true);
15291   }
15292 
15293   // Second, collect information from llvm.experimental.guards dominating the loop.
15294   auto *GuardDecl = F.getParent()->getFunction(
15295       Intrinsic::getName(Intrinsic::experimental_guard));
15296   if (GuardDecl)
15297     for (const auto *GU : GuardDecl->users())
15298       if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
15299         if (Guard->getFunction() == Header->getParent() && DT.dominates(Guard, Header))
15300           Terms.emplace_back(Guard->getArgOperand(0), true);
15301 
15302   // Third, collect conditions from dominating branches. Starting at the loop
15303   // predecessor, climb up the predecessor chain, as long as there are
15304   // predecessors that can be found that have unique successors leading to the
15305   // original header.
15306   // TODO: share this logic with isLoopEntryGuardedByCond.
15307   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
15308            L->getLoopPredecessor(), Header);
15309        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15310 
15311     const BranchInst *LoopEntryPredicate =
15312         dyn_cast<BranchInst>(Pair.first->getTerminator());
15313     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
15314       continue;
15315 
15316     Terms.emplace_back(LoopEntryPredicate->getCondition(),
15317                        LoopEntryPredicate->getSuccessor(0) == Pair.second);
15318   }
15319 
15320   // Now apply the information from the collected conditions to RewriteMap.
15321   // Conditions are processed in reverse order, so the earliest conditions is
15322   // processed first. This ensures the SCEVs with the shortest dependency chains
15323   // are constructed first.
15324   DenseMap<const SCEV *, const SCEV *> RewriteMap;
15325   for (auto [Term, EnterIfTrue] : reverse(Terms)) {
15326     SmallVector<Value *, 8> Worklist;
15327     SmallPtrSet<Value *, 8> Visited;
15328     Worklist.push_back(Term);
15329     while (!Worklist.empty()) {
15330       Value *Cond = Worklist.pop_back_val();
15331       if (!Visited.insert(Cond).second)
15332         continue;
15333 
15334       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
15335         auto Predicate =
15336             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
15337         const auto *LHS = getSCEV(Cmp->getOperand(0));
15338         const auto *RHS = getSCEV(Cmp->getOperand(1));
15339         CollectCondition(Predicate, LHS, RHS, RewriteMap);
15340         continue;
15341       }
15342 
15343       Value *L, *R;
15344       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
15345                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
15346         Worklist.push_back(L);
15347         Worklist.push_back(R);
15348       }
15349     }
15350   }
15351 
15352   if (RewriteMap.empty())
15353     return Expr;
15354 
15355   // Now that all rewrite information is collect, rewrite the collected
15356   // expressions with the information in the map. This applies information to
15357   // sub-expressions.
15358   if (ExprsToRewrite.size() > 1) {
15359     for (const SCEV *Expr : ExprsToRewrite) {
15360       const SCEV *RewriteTo = RewriteMap[Expr];
15361       RewriteMap.erase(Expr);
15362       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15363       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
15364     }
15365   }
15366 
15367   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15368   return Rewriter.visit(Expr);
15369 }
15370