1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionDivision.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/InitializePasses.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/KnownBits.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <climits>
128 #include <cstddef>
129 #include <cstdint>
130 #include <cstdlib>
131 #include <map>
132 #include <memory>
133 #include <tuple>
134 #include <utility>
135 #include <vector>
136 
137 using namespace llvm;
138 using namespace PatternMatch;
139 
140 #define DEBUG_TYPE "scalar-evolution"
141 
142 STATISTIC(NumArrayLenItCounts,
143           "Number of trip counts computed with array length");
144 STATISTIC(NumTripCountsComputed,
145           "Number of loops with predictable loop counts");
146 STATISTIC(NumTripCountsNotComputed,
147           "Number of loops without predictable loop counts");
148 STATISTIC(NumBruteForceTripCountsComputed,
149           "Number of loops with trip counts computed by force");
150 
151 static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153                         cl::ZeroOrMore,
154                         cl::desc("Maximum number of iterations SCEV will "
155                                  "symbolically execute a constant "
156                                  "derived loop"),
157                         cl::init(100));
158 
159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
160 static cl::opt<bool> VerifySCEV(
161     "verify-scev", cl::Hidden,
162     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 static cl::opt<bool> VerifySCEVStrict(
164     "verify-scev-strict", cl::Hidden,
165     cl::desc("Enable stricter verification with -verify-scev is passed"));
166 static cl::opt<bool>
167     VerifySCEVMap("verify-scev-maps", cl::Hidden,
168                   cl::desc("Verify no dangling value in ScalarEvolution's "
169                            "ExprValueMap (slow)"));
170 
171 static cl::opt<bool> VerifyIR(
172     "scev-verify-ir", cl::Hidden,
173     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
174     cl::init(false));
175 
176 static cl::opt<unsigned> MulOpsInlineThreshold(
177     "scev-mulops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
179     cl::init(32));
180 
181 static cl::opt<unsigned> AddOpsInlineThreshold(
182     "scev-addops-inline-threshold", cl::Hidden,
183     cl::desc("Threshold for inlining addition operands into a SCEV"),
184     cl::init(500));
185 
186 static cl::opt<unsigned> MaxSCEVCompareDepth(
187     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
189     cl::init(32));
190 
191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
192     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
194     cl::init(2));
195 
196 static cl::opt<unsigned> MaxValueCompareDepth(
197     "scalar-evolution-max-value-compare-depth", cl::Hidden,
198     cl::desc("Maximum depth of recursive value complexity comparisons"),
199     cl::init(2));
200 
201 static cl::opt<unsigned>
202     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
203                   cl::desc("Maximum depth of recursive arithmetics"),
204                   cl::init(32));
205 
206 static cl::opt<unsigned> MaxConstantEvolvingDepth(
207     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
208     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
209 
210 static cl::opt<unsigned>
211     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
212                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
213                  cl::init(8));
214 
215 static cl::opt<unsigned>
216     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
217                   cl::desc("Max coefficients in AddRec during evolving"),
218                   cl::init(8));
219 
220 static cl::opt<unsigned>
221     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
222                   cl::desc("Size of the expression which is considered huge"),
223                   cl::init(4096));
224 
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227     cl::Hidden, cl::init(true),
228     cl::desc("When printing analysis, include information on every instruction"));
229 
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232     cl::init(false),
233     cl::desc("Use more powerful methods of sharpening expression ranges. May "
234              "be costly in terms of compile time"));
235 
236 //===----------------------------------------------------------------------===//
237 //                           SCEV class definitions
238 //===----------------------------------------------------------------------===//
239 
240 //===----------------------------------------------------------------------===//
241 // Implementation of the SCEV class.
242 //
243 
244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
245 LLVM_DUMP_METHOD void SCEV::dump() const {
246   print(dbgs());
247   dbgs() << '\n';
248 }
249 #endif
250 
251 void SCEV::print(raw_ostream &OS) const {
252   switch (getSCEVType()) {
253   case scConstant:
254     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
255     return;
256   case scPtrToInt: {
257     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
258     const SCEV *Op = PtrToInt->getOperand();
259     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
260        << *PtrToInt->getType() << ")";
261     return;
262   }
263   case scTruncate: {
264     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
265     const SCEV *Op = Trunc->getOperand();
266     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
267        << *Trunc->getType() << ")";
268     return;
269   }
270   case scZeroExtend: {
271     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
272     const SCEV *Op = ZExt->getOperand();
273     OS << "(zext " << *Op->getType() << " " << *Op << " to "
274        << *ZExt->getType() << ")";
275     return;
276   }
277   case scSignExtend: {
278     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
279     const SCEV *Op = SExt->getOperand();
280     OS << "(sext " << *Op->getType() << " " << *Op << " to "
281        << *SExt->getType() << ")";
282     return;
283   }
284   case scAddRecExpr: {
285     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
286     OS << "{" << *AR->getOperand(0);
287     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
288       OS << ",+," << *AR->getOperand(i);
289     OS << "}<";
290     if (AR->hasNoUnsignedWrap())
291       OS << "nuw><";
292     if (AR->hasNoSignedWrap())
293       OS << "nsw><";
294     if (AR->hasNoSelfWrap() &&
295         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
296       OS << "nw><";
297     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
298     OS << ">";
299     return;
300   }
301   case scAddExpr:
302   case scMulExpr:
303   case scUMaxExpr:
304   case scSMaxExpr:
305   case scUMinExpr:
306   case scSMinExpr: {
307     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
308     const char *OpStr = nullptr;
309     switch (NAry->getSCEVType()) {
310     case scAddExpr: OpStr = " + "; break;
311     case scMulExpr: OpStr = " * "; break;
312     case scUMaxExpr: OpStr = " umax "; break;
313     case scSMaxExpr: OpStr = " smax "; break;
314     case scUMinExpr:
315       OpStr = " umin ";
316       break;
317     case scSMinExpr:
318       OpStr = " smin ";
319       break;
320     default:
321       llvm_unreachable("There are no other nary expression types.");
322     }
323     OS << "(";
324     ListSeparator LS(OpStr);
325     for (const SCEV *Op : NAry->operands())
326       OS << LS << *Op;
327     OS << ")";
328     switch (NAry->getSCEVType()) {
329     case scAddExpr:
330     case scMulExpr:
331       if (NAry->hasNoUnsignedWrap())
332         OS << "<nuw>";
333       if (NAry->hasNoSignedWrap())
334         OS << "<nsw>";
335       break;
336     default:
337       // Nothing to print for other nary expressions.
338       break;
339     }
340     return;
341   }
342   case scUDivExpr: {
343     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
344     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
345     return;
346   }
347   case scUnknown: {
348     const SCEVUnknown *U = cast<SCEVUnknown>(this);
349     Type *AllocTy;
350     if (U->isSizeOf(AllocTy)) {
351       OS << "sizeof(" << *AllocTy << ")";
352       return;
353     }
354     if (U->isAlignOf(AllocTy)) {
355       OS << "alignof(" << *AllocTy << ")";
356       return;
357     }
358 
359     Type *CTy;
360     Constant *FieldNo;
361     if (U->isOffsetOf(CTy, FieldNo)) {
362       OS << "offsetof(" << *CTy << ", ";
363       FieldNo->printAsOperand(OS, false);
364       OS << ")";
365       return;
366     }
367 
368     // Otherwise just print it normally.
369     U->getValue()->printAsOperand(OS, false);
370     return;
371   }
372   case scCouldNotCompute:
373     OS << "***COULDNOTCOMPUTE***";
374     return;
375   }
376   llvm_unreachable("Unknown SCEV kind!");
377 }
378 
379 Type *SCEV::getType() const {
380   switch (getSCEVType()) {
381   case scConstant:
382     return cast<SCEVConstant>(this)->getType();
383   case scPtrToInt:
384   case scTruncate:
385   case scZeroExtend:
386   case scSignExtend:
387     return cast<SCEVCastExpr>(this)->getType();
388   case scAddRecExpr:
389     return cast<SCEVAddRecExpr>(this)->getType();
390   case scMulExpr:
391     return cast<SCEVMulExpr>(this)->getType();
392   case scUMaxExpr:
393   case scSMaxExpr:
394   case scUMinExpr:
395   case scSMinExpr:
396     return cast<SCEVMinMaxExpr>(this)->getType();
397   case scAddExpr:
398     return cast<SCEVAddExpr>(this)->getType();
399   case scUDivExpr:
400     return cast<SCEVUDivExpr>(this)->getType();
401   case scUnknown:
402     return cast<SCEVUnknown>(this)->getType();
403   case scCouldNotCompute:
404     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
405   }
406   llvm_unreachable("Unknown SCEV kind!");
407 }
408 
409 bool SCEV::isZero() const {
410   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
411     return SC->getValue()->isZero();
412   return false;
413 }
414 
415 bool SCEV::isOne() const {
416   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
417     return SC->getValue()->isOne();
418   return false;
419 }
420 
421 bool SCEV::isAllOnesValue() const {
422   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
423     return SC->getValue()->isMinusOne();
424   return false;
425 }
426 
427 bool SCEV::isNonConstantNegative() const {
428   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
429   if (!Mul) return false;
430 
431   // If there is a constant factor, it will be first.
432   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
433   if (!SC) return false;
434 
435   // Return true if the value is negative, this matches things like (-42 * V).
436   return SC->getAPInt().isNegative();
437 }
438 
439 SCEVCouldNotCompute::SCEVCouldNotCompute() :
440   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
441 
442 bool SCEVCouldNotCompute::classof(const SCEV *S) {
443   return S->getSCEVType() == scCouldNotCompute;
444 }
445 
446 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
447   FoldingSetNodeID ID;
448   ID.AddInteger(scConstant);
449   ID.AddPointer(V);
450   void *IP = nullptr;
451   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
452   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
453   UniqueSCEVs.InsertNode(S, IP);
454   return S;
455 }
456 
457 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
458   return getConstant(ConstantInt::get(getContext(), Val));
459 }
460 
461 const SCEV *
462 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
463   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
464   return getConstant(ConstantInt::get(ITy, V, isSigned));
465 }
466 
467 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
468                            const SCEV *op, Type *ty)
469     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
470   Operands[0] = op;
471 }
472 
473 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
474                                    Type *ITy)
475     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
476   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
477          "Must be a non-bit-width-changing pointer-to-integer cast!");
478 }
479 
480 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
481                                            SCEVTypes SCEVTy, const SCEV *op,
482                                            Type *ty)
483     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
484 
485 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
486                                    Type *ty)
487     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
488   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
489          "Cannot truncate non-integer value!");
490 }
491 
492 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
493                                        const SCEV *op, Type *ty)
494     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
495   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
496          "Cannot zero extend non-integer value!");
497 }
498 
499 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
500                                        const SCEV *op, Type *ty)
501     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
502   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
503          "Cannot sign extend non-integer value!");
504 }
505 
506 void SCEVUnknown::deleted() {
507   // Clear this SCEVUnknown from various maps.
508   SE->forgetMemoizedResults(this);
509 
510   // Remove this SCEVUnknown from the uniquing map.
511   SE->UniqueSCEVs.RemoveNode(this);
512 
513   // Release the value.
514   setValPtr(nullptr);
515 }
516 
517 void SCEVUnknown::allUsesReplacedWith(Value *New) {
518   // Remove this SCEVUnknown from the uniquing map.
519   SE->UniqueSCEVs.RemoveNode(this);
520 
521   // Update this SCEVUnknown to point to the new value. This is needed
522   // because there may still be outstanding SCEVs which still point to
523   // this SCEVUnknown.
524   setValPtr(New);
525 }
526 
527 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
528   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
529     if (VCE->getOpcode() == Instruction::PtrToInt)
530       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
531         if (CE->getOpcode() == Instruction::GetElementPtr &&
532             CE->getOperand(0)->isNullValue() &&
533             CE->getNumOperands() == 2)
534           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
535             if (CI->isOne()) {
536               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
537                                  ->getElementType();
538               return true;
539             }
540 
541   return false;
542 }
543 
544 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
545   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
546     if (VCE->getOpcode() == Instruction::PtrToInt)
547       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
548         if (CE->getOpcode() == Instruction::GetElementPtr &&
549             CE->getOperand(0)->isNullValue()) {
550           Type *Ty =
551             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
552           if (StructType *STy = dyn_cast<StructType>(Ty))
553             if (!STy->isPacked() &&
554                 CE->getNumOperands() == 3 &&
555                 CE->getOperand(1)->isNullValue()) {
556               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
557                 if (CI->isOne() &&
558                     STy->getNumElements() == 2 &&
559                     STy->getElementType(0)->isIntegerTy(1)) {
560                   AllocTy = STy->getElementType(1);
561                   return true;
562                 }
563             }
564         }
565 
566   return false;
567 }
568 
569 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
570   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
571     if (VCE->getOpcode() == Instruction::PtrToInt)
572       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
573         if (CE->getOpcode() == Instruction::GetElementPtr &&
574             CE->getNumOperands() == 3 &&
575             CE->getOperand(0)->isNullValue() &&
576             CE->getOperand(1)->isNullValue()) {
577           Type *Ty =
578             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
579           // Ignore vector types here so that ScalarEvolutionExpander doesn't
580           // emit getelementptrs that index into vectors.
581           if (Ty->isStructTy() || Ty->isArrayTy()) {
582             CTy = Ty;
583             FieldNo = CE->getOperand(2);
584             return true;
585           }
586         }
587 
588   return false;
589 }
590 
591 //===----------------------------------------------------------------------===//
592 //                               SCEV Utilities
593 //===----------------------------------------------------------------------===//
594 
595 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
596 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
597 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
598 /// have been previously deemed to be "equally complex" by this routine.  It is
599 /// intended to avoid exponential time complexity in cases like:
600 ///
601 ///   %a = f(%x, %y)
602 ///   %b = f(%a, %a)
603 ///   %c = f(%b, %b)
604 ///
605 ///   %d = f(%x, %y)
606 ///   %e = f(%d, %d)
607 ///   %f = f(%e, %e)
608 ///
609 ///   CompareValueComplexity(%f, %c)
610 ///
611 /// Since we do not continue running this routine on expression trees once we
612 /// have seen unequal values, there is no need to track them in the cache.
613 static int
614 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
615                        const LoopInfo *const LI, Value *LV, Value *RV,
616                        unsigned Depth) {
617   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
618     return 0;
619 
620   // Order pointer values after integer values. This helps SCEVExpander form
621   // GEPs.
622   bool LIsPointer = LV->getType()->isPointerTy(),
623        RIsPointer = RV->getType()->isPointerTy();
624   if (LIsPointer != RIsPointer)
625     return (int)LIsPointer - (int)RIsPointer;
626 
627   // Compare getValueID values.
628   unsigned LID = LV->getValueID(), RID = RV->getValueID();
629   if (LID != RID)
630     return (int)LID - (int)RID;
631 
632   // Sort arguments by their position.
633   if (const auto *LA = dyn_cast<Argument>(LV)) {
634     const auto *RA = cast<Argument>(RV);
635     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
636     return (int)LArgNo - (int)RArgNo;
637   }
638 
639   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
640     const auto *RGV = cast<GlobalValue>(RV);
641 
642     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
643       auto LT = GV->getLinkage();
644       return !(GlobalValue::isPrivateLinkage(LT) ||
645                GlobalValue::isInternalLinkage(LT));
646     };
647 
648     // Use the names to distinguish the two values, but only if the
649     // names are semantically important.
650     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
651       return LGV->getName().compare(RGV->getName());
652   }
653 
654   // For instructions, compare their loop depth, and their operand count.  This
655   // is pretty loose.
656   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
657     const auto *RInst = cast<Instruction>(RV);
658 
659     // Compare loop depths.
660     const BasicBlock *LParent = LInst->getParent(),
661                      *RParent = RInst->getParent();
662     if (LParent != RParent) {
663       unsigned LDepth = LI->getLoopDepth(LParent),
664                RDepth = LI->getLoopDepth(RParent);
665       if (LDepth != RDepth)
666         return (int)LDepth - (int)RDepth;
667     }
668 
669     // Compare the number of operands.
670     unsigned LNumOps = LInst->getNumOperands(),
671              RNumOps = RInst->getNumOperands();
672     if (LNumOps != RNumOps)
673       return (int)LNumOps - (int)RNumOps;
674 
675     for (unsigned Idx : seq(0u, LNumOps)) {
676       int Result =
677           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
678                                  RInst->getOperand(Idx), Depth + 1);
679       if (Result != 0)
680         return Result;
681     }
682   }
683 
684   EqCacheValue.unionSets(LV, RV);
685   return 0;
686 }
687 
688 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
689 // than RHS, respectively. A three-way result allows recursive comparisons to be
690 // more efficient.
691 // If the max analysis depth was reached, return None, assuming we do not know
692 // if they are equivalent for sure.
693 static Optional<int>
694 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
695                       EquivalenceClasses<const Value *> &EqCacheValue,
696                       const LoopInfo *const LI, const SCEV *LHS,
697                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
698   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
699   if (LHS == RHS)
700     return 0;
701 
702   // Primarily, sort the SCEVs by their getSCEVType().
703   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
704   if (LType != RType)
705     return (int)LType - (int)RType;
706 
707   if (EqCacheSCEV.isEquivalent(LHS, RHS))
708     return 0;
709 
710   if (Depth > MaxSCEVCompareDepth)
711     return None;
712 
713   // Aside from the getSCEVType() ordering, the particular ordering
714   // isn't very important except that it's beneficial to be consistent,
715   // so that (a + b) and (b + a) don't end up as different expressions.
716   switch (LType) {
717   case scUnknown: {
718     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
719     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
720 
721     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
722                                    RU->getValue(), Depth + 1);
723     if (X == 0)
724       EqCacheSCEV.unionSets(LHS, RHS);
725     return X;
726   }
727 
728   case scConstant: {
729     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
730     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
731 
732     // Compare constant values.
733     const APInt &LA = LC->getAPInt();
734     const APInt &RA = RC->getAPInt();
735     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
736     if (LBitWidth != RBitWidth)
737       return (int)LBitWidth - (int)RBitWidth;
738     return LA.ult(RA) ? -1 : 1;
739   }
740 
741   case scAddRecExpr: {
742     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
743     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
744 
745     // There is always a dominance between two recs that are used by one SCEV,
746     // so we can safely sort recs by loop header dominance. We require such
747     // order in getAddExpr.
748     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
749     if (LLoop != RLoop) {
750       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
751       assert(LHead != RHead && "Two loops share the same header?");
752       if (DT.dominates(LHead, RHead))
753         return 1;
754       else
755         assert(DT.dominates(RHead, LHead) &&
756                "No dominance between recurrences used by one SCEV?");
757       return -1;
758     }
759 
760     // Addrec complexity grows with operand count.
761     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
762     if (LNumOps != RNumOps)
763       return (int)LNumOps - (int)RNumOps;
764 
765     // Lexicographically compare.
766     for (unsigned i = 0; i != LNumOps; ++i) {
767       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
768                                      LA->getOperand(i), RA->getOperand(i), DT,
769                                      Depth + 1);
770       if (X != 0)
771         return X;
772     }
773     EqCacheSCEV.unionSets(LHS, RHS);
774     return 0;
775   }
776 
777   case scAddExpr:
778   case scMulExpr:
779   case scSMaxExpr:
780   case scUMaxExpr:
781   case scSMinExpr:
782   case scUMinExpr: {
783     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
784     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
785 
786     // Lexicographically compare n-ary expressions.
787     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
788     if (LNumOps != RNumOps)
789       return (int)LNumOps - (int)RNumOps;
790 
791     for (unsigned i = 0; i != LNumOps; ++i) {
792       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
793                                      LC->getOperand(i), RC->getOperand(i), DT,
794                                      Depth + 1);
795       if (X != 0)
796         return X;
797     }
798     EqCacheSCEV.unionSets(LHS, RHS);
799     return 0;
800   }
801 
802   case scUDivExpr: {
803     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
804     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
805 
806     // Lexicographically compare udiv expressions.
807     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
808                                    RC->getLHS(), DT, Depth + 1);
809     if (X != 0)
810       return X;
811     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
812                               RC->getRHS(), DT, Depth + 1);
813     if (X == 0)
814       EqCacheSCEV.unionSets(LHS, RHS);
815     return X;
816   }
817 
818   case scPtrToInt:
819   case scTruncate:
820   case scZeroExtend:
821   case scSignExtend: {
822     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
823     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
824 
825     // Compare cast expressions by operand.
826     auto X =
827         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
828                               RC->getOperand(), DT, Depth + 1);
829     if (X == 0)
830       EqCacheSCEV.unionSets(LHS, RHS);
831     return X;
832   }
833 
834   case scCouldNotCompute:
835     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
836   }
837   llvm_unreachable("Unknown SCEV kind!");
838 }
839 
840 /// Given a list of SCEV objects, order them by their complexity, and group
841 /// objects of the same complexity together by value.  When this routine is
842 /// finished, we know that any duplicates in the vector are consecutive and that
843 /// complexity is monotonically increasing.
844 ///
845 /// Note that we go take special precautions to ensure that we get deterministic
846 /// results from this routine.  In other words, we don't want the results of
847 /// this to depend on where the addresses of various SCEV objects happened to
848 /// land in memory.
849 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
850                               LoopInfo *LI, DominatorTree &DT) {
851   if (Ops.size() < 2) return;  // Noop
852 
853   EquivalenceClasses<const SCEV *> EqCacheSCEV;
854   EquivalenceClasses<const Value *> EqCacheValue;
855 
856   // Whether LHS has provably less complexity than RHS.
857   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
858     auto Complexity =
859         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
860     return Complexity && *Complexity < 0;
861   };
862   if (Ops.size() == 2) {
863     // This is the common case, which also happens to be trivially simple.
864     // Special case it.
865     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
866     if (IsLessComplex(RHS, LHS))
867       std::swap(LHS, RHS);
868     return;
869   }
870 
871   // Do the rough sort by complexity.
872   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
873     return IsLessComplex(LHS, RHS);
874   });
875 
876   // Now that we are sorted by complexity, group elements of the same
877   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
878   // be extremely short in practice.  Note that we take this approach because we
879   // do not want to depend on the addresses of the objects we are grouping.
880   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
881     const SCEV *S = Ops[i];
882     unsigned Complexity = S->getSCEVType();
883 
884     // If there are any objects of the same complexity and same value as this
885     // one, group them.
886     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
887       if (Ops[j] == S) { // Found a duplicate.
888         // Move it to immediately after i'th element.
889         std::swap(Ops[i+1], Ops[j]);
890         ++i;   // no need to rescan it.
891         if (i == e-2) return;  // Done!
892       }
893     }
894   }
895 }
896 
897 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
898 /// least HugeExprThreshold nodes).
899 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
900   return any_of(Ops, [](const SCEV *S) {
901     return S->getExpressionSize() >= HugeExprThreshold;
902   });
903 }
904 
905 //===----------------------------------------------------------------------===//
906 //                      Simple SCEV method implementations
907 //===----------------------------------------------------------------------===//
908 
909 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
910 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
911                                        ScalarEvolution &SE,
912                                        Type *ResultTy) {
913   // Handle the simplest case efficiently.
914   if (K == 1)
915     return SE.getTruncateOrZeroExtend(It, ResultTy);
916 
917   // We are using the following formula for BC(It, K):
918   //
919   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
920   //
921   // Suppose, W is the bitwidth of the return value.  We must be prepared for
922   // overflow.  Hence, we must assure that the result of our computation is
923   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
924   // safe in modular arithmetic.
925   //
926   // However, this code doesn't use exactly that formula; the formula it uses
927   // is something like the following, where T is the number of factors of 2 in
928   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
929   // exponentiation:
930   //
931   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
932   //
933   // This formula is trivially equivalent to the previous formula.  However,
934   // this formula can be implemented much more efficiently.  The trick is that
935   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
936   // arithmetic.  To do exact division in modular arithmetic, all we have
937   // to do is multiply by the inverse.  Therefore, this step can be done at
938   // width W.
939   //
940   // The next issue is how to safely do the division by 2^T.  The way this
941   // is done is by doing the multiplication step at a width of at least W + T
942   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
943   // when we perform the division by 2^T (which is equivalent to a right shift
944   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
945   // truncated out after the division by 2^T.
946   //
947   // In comparison to just directly using the first formula, this technique
948   // is much more efficient; using the first formula requires W * K bits,
949   // but this formula less than W + K bits. Also, the first formula requires
950   // a division step, whereas this formula only requires multiplies and shifts.
951   //
952   // It doesn't matter whether the subtraction step is done in the calculation
953   // width or the input iteration count's width; if the subtraction overflows,
954   // the result must be zero anyway.  We prefer here to do it in the width of
955   // the induction variable because it helps a lot for certain cases; CodeGen
956   // isn't smart enough to ignore the overflow, which leads to much less
957   // efficient code if the width of the subtraction is wider than the native
958   // register width.
959   //
960   // (It's possible to not widen at all by pulling out factors of 2 before
961   // the multiplication; for example, K=2 can be calculated as
962   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
963   // extra arithmetic, so it's not an obvious win, and it gets
964   // much more complicated for K > 3.)
965 
966   // Protection from insane SCEVs; this bound is conservative,
967   // but it probably doesn't matter.
968   if (K > 1000)
969     return SE.getCouldNotCompute();
970 
971   unsigned W = SE.getTypeSizeInBits(ResultTy);
972 
973   // Calculate K! / 2^T and T; we divide out the factors of two before
974   // multiplying for calculating K! / 2^T to avoid overflow.
975   // Other overflow doesn't matter because we only care about the bottom
976   // W bits of the result.
977   APInt OddFactorial(W, 1);
978   unsigned T = 1;
979   for (unsigned i = 3; i <= K; ++i) {
980     APInt Mult(W, i);
981     unsigned TwoFactors = Mult.countTrailingZeros();
982     T += TwoFactors;
983     Mult.lshrInPlace(TwoFactors);
984     OddFactorial *= Mult;
985   }
986 
987   // We need at least W + T bits for the multiplication step
988   unsigned CalculationBits = W + T;
989 
990   // Calculate 2^T, at width T+W.
991   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
992 
993   // Calculate the multiplicative inverse of K! / 2^T;
994   // this multiplication factor will perform the exact division by
995   // K! / 2^T.
996   APInt Mod = APInt::getSignedMinValue(W+1);
997   APInt MultiplyFactor = OddFactorial.zext(W+1);
998   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
999   MultiplyFactor = MultiplyFactor.trunc(W);
1000 
1001   // Calculate the product, at width T+W
1002   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1003                                                       CalculationBits);
1004   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1005   for (unsigned i = 1; i != K; ++i) {
1006     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1007     Dividend = SE.getMulExpr(Dividend,
1008                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1009   }
1010 
1011   // Divide by 2^T
1012   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1013 
1014   // Truncate the result, and divide by K! / 2^T.
1015 
1016   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1017                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1018 }
1019 
1020 /// Return the value of this chain of recurrences at the specified iteration
1021 /// number.  We can evaluate this recurrence by multiplying each element in the
1022 /// chain by the binomial coefficient corresponding to it.  In other words, we
1023 /// can evaluate {A,+,B,+,C,+,D} as:
1024 ///
1025 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1026 ///
1027 /// where BC(It, k) stands for binomial coefficient.
1028 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1029                                                 ScalarEvolution &SE) const {
1030   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1031 }
1032 
1033 const SCEV *
1034 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1035                                     const SCEV *It, ScalarEvolution &SE) {
1036   assert(Operands.size() > 0);
1037   const SCEV *Result = Operands[0];
1038   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1039     // The computation is correct in the face of overflow provided that the
1040     // multiplication is performed _after_ the evaluation of the binomial
1041     // coefficient.
1042     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1043     if (isa<SCEVCouldNotCompute>(Coeff))
1044       return Coeff;
1045 
1046     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1047   }
1048   return Result;
1049 }
1050 
1051 //===----------------------------------------------------------------------===//
1052 //                    SCEV Expression folder implementations
1053 //===----------------------------------------------------------------------===//
1054 
1055 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1056                                                      unsigned Depth) {
1057   assert(Depth <= 1 &&
1058          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1059 
1060   // We could be called with an integer-typed operands during SCEV rewrites.
1061   // Since the operand is an integer already, just perform zext/trunc/self cast.
1062   if (!Op->getType()->isPointerTy())
1063     return Op;
1064 
1065   // What would be an ID for such a SCEV cast expression?
1066   FoldingSetNodeID ID;
1067   ID.AddInteger(scPtrToInt);
1068   ID.AddPointer(Op);
1069 
1070   void *IP = nullptr;
1071 
1072   // Is there already an expression for such a cast?
1073   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1074     return S;
1075 
1076   // It isn't legal for optimizations to construct new ptrtoint expressions
1077   // for non-integral pointers.
1078   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1079     return getCouldNotCompute();
1080 
1081   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1082 
1083   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1084   // is sufficiently wide to represent all possible pointer values.
1085   // We could theoretically teach SCEV to truncate wider pointers, but
1086   // that isn't implemented for now.
1087   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1088       getDataLayout().getTypeSizeInBits(IntPtrTy))
1089     return getCouldNotCompute();
1090 
1091   // If not, is this expression something we can't reduce any further?
1092   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1093     // Perform some basic constant folding. If the operand of the ptr2int cast
1094     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1095     // left as-is), but produce a zero constant.
1096     // NOTE: We could handle a more general case, but lack motivational cases.
1097     if (isa<ConstantPointerNull>(U->getValue()))
1098       return getZero(IntPtrTy);
1099 
1100     // Create an explicit cast node.
1101     // We can reuse the existing insert position since if we get here,
1102     // we won't have made any changes which would invalidate it.
1103     SCEV *S = new (SCEVAllocator)
1104         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1105     UniqueSCEVs.InsertNode(S, IP);
1106     addToLoopUseLists(S);
1107     return S;
1108   }
1109 
1110   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1111                        "non-SCEVUnknown's.");
1112 
1113   // Otherwise, we've got some expression that is more complex than just a
1114   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1115   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1116   // only, and the expressions must otherwise be integer-typed.
1117   // So sink the cast down to the SCEVUnknown's.
1118 
1119   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1120   /// which computes a pointer-typed value, and rewrites the whole expression
1121   /// tree so that *all* the computations are done on integers, and the only
1122   /// pointer-typed operands in the expression are SCEVUnknown.
1123   class SCEVPtrToIntSinkingRewriter
1124       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1125     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1126 
1127   public:
1128     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1129 
1130     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1131       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1132       return Rewriter.visit(Scev);
1133     }
1134 
1135     const SCEV *visit(const SCEV *S) {
1136       Type *STy = S->getType();
1137       // If the expression is not pointer-typed, just keep it as-is.
1138       if (!STy->isPointerTy())
1139         return S;
1140       // Else, recursively sink the cast down into it.
1141       return Base::visit(S);
1142     }
1143 
1144     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1145       SmallVector<const SCEV *, 2> Operands;
1146       bool Changed = false;
1147       for (auto *Op : Expr->operands()) {
1148         Operands.push_back(visit(Op));
1149         Changed |= Op != Operands.back();
1150       }
1151       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1152     }
1153 
1154     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1155       SmallVector<const SCEV *, 2> Operands;
1156       bool Changed = false;
1157       for (auto *Op : Expr->operands()) {
1158         Operands.push_back(visit(Op));
1159         Changed |= Op != Operands.back();
1160       }
1161       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1162     }
1163 
1164     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1165       assert(Expr->getType()->isPointerTy() &&
1166              "Should only reach pointer-typed SCEVUnknown's.");
1167       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1168     }
1169   };
1170 
1171   // And actually perform the cast sinking.
1172   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1173   assert(IntOp->getType()->isIntegerTy() &&
1174          "We must have succeeded in sinking the cast, "
1175          "and ending up with an integer-typed expression!");
1176   return IntOp;
1177 }
1178 
1179 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1180   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1181 
1182   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1183   if (isa<SCEVCouldNotCompute>(IntOp))
1184     return IntOp;
1185 
1186   return getTruncateOrZeroExtend(IntOp, Ty);
1187 }
1188 
1189 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1190                                              unsigned Depth) {
1191   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1192          "This is not a truncating conversion!");
1193   assert(isSCEVable(Ty) &&
1194          "This is not a conversion to a SCEVable type!");
1195   Ty = getEffectiveSCEVType(Ty);
1196 
1197   FoldingSetNodeID ID;
1198   ID.AddInteger(scTruncate);
1199   ID.AddPointer(Op);
1200   ID.AddPointer(Ty);
1201   void *IP = nullptr;
1202   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1203 
1204   // Fold if the operand is constant.
1205   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1206     return getConstant(
1207       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1208 
1209   // trunc(trunc(x)) --> trunc(x)
1210   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1211     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1212 
1213   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1214   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1215     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1216 
1217   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1218   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1219     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1220 
1221   if (Depth > MaxCastDepth) {
1222     SCEV *S =
1223         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1224     UniqueSCEVs.InsertNode(S, IP);
1225     addToLoopUseLists(S);
1226     return S;
1227   }
1228 
1229   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1230   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1231   // if after transforming we have at most one truncate, not counting truncates
1232   // that replace other casts.
1233   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1234     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1235     SmallVector<const SCEV *, 4> Operands;
1236     unsigned numTruncs = 0;
1237     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1238          ++i) {
1239       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1240       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1241           isa<SCEVTruncateExpr>(S))
1242         numTruncs++;
1243       Operands.push_back(S);
1244     }
1245     if (numTruncs < 2) {
1246       if (isa<SCEVAddExpr>(Op))
1247         return getAddExpr(Operands);
1248       else if (isa<SCEVMulExpr>(Op))
1249         return getMulExpr(Operands);
1250       else
1251         llvm_unreachable("Unexpected SCEV type for Op.");
1252     }
1253     // Although we checked in the beginning that ID is not in the cache, it is
1254     // possible that during recursion and different modification ID was inserted
1255     // into the cache. So if we find it, just return it.
1256     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1257       return S;
1258   }
1259 
1260   // If the input value is a chrec scev, truncate the chrec's operands.
1261   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1262     SmallVector<const SCEV *, 4> Operands;
1263     for (const SCEV *Op : AddRec->operands())
1264       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1265     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1266   }
1267 
1268   // Return zero if truncating to known zeros.
1269   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1270   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1271     return getZero(Ty);
1272 
1273   // The cast wasn't folded; create an explicit cast node. We can reuse
1274   // the existing insert position since if we get here, we won't have
1275   // made any changes which would invalidate it.
1276   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1277                                                  Op, Ty);
1278   UniqueSCEVs.InsertNode(S, IP);
1279   addToLoopUseLists(S);
1280   return S;
1281 }
1282 
1283 // Get the limit of a recurrence such that incrementing by Step cannot cause
1284 // signed overflow as long as the value of the recurrence within the
1285 // loop does not exceed this limit before incrementing.
1286 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1287                                                  ICmpInst::Predicate *Pred,
1288                                                  ScalarEvolution *SE) {
1289   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1290   if (SE->isKnownPositive(Step)) {
1291     *Pred = ICmpInst::ICMP_SLT;
1292     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1293                            SE->getSignedRangeMax(Step));
1294   }
1295   if (SE->isKnownNegative(Step)) {
1296     *Pred = ICmpInst::ICMP_SGT;
1297     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1298                            SE->getSignedRangeMin(Step));
1299   }
1300   return nullptr;
1301 }
1302 
1303 // Get the limit of a recurrence such that incrementing by Step cannot cause
1304 // unsigned overflow as long as the value of the recurrence within the loop does
1305 // not exceed this limit before incrementing.
1306 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1307                                                    ICmpInst::Predicate *Pred,
1308                                                    ScalarEvolution *SE) {
1309   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1310   *Pred = ICmpInst::ICMP_ULT;
1311 
1312   return SE->getConstant(APInt::getMinValue(BitWidth) -
1313                          SE->getUnsignedRangeMax(Step));
1314 }
1315 
1316 namespace {
1317 
1318 struct ExtendOpTraitsBase {
1319   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1320                                                           unsigned);
1321 };
1322 
1323 // Used to make code generic over signed and unsigned overflow.
1324 template <typename ExtendOp> struct ExtendOpTraits {
1325   // Members present:
1326   //
1327   // static const SCEV::NoWrapFlags WrapType;
1328   //
1329   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1330   //
1331   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1332   //                                           ICmpInst::Predicate *Pred,
1333   //                                           ScalarEvolution *SE);
1334 };
1335 
1336 template <>
1337 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1338   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1339 
1340   static const GetExtendExprTy GetExtendExpr;
1341 
1342   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1343                                              ICmpInst::Predicate *Pred,
1344                                              ScalarEvolution *SE) {
1345     return getSignedOverflowLimitForStep(Step, Pred, SE);
1346   }
1347 };
1348 
1349 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1350     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1351 
1352 template <>
1353 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1354   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1355 
1356   static const GetExtendExprTy GetExtendExpr;
1357 
1358   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1359                                              ICmpInst::Predicate *Pred,
1360                                              ScalarEvolution *SE) {
1361     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1362   }
1363 };
1364 
1365 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1366     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1367 
1368 } // end anonymous namespace
1369 
1370 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1371 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1372 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1373 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1374 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1375 // expression "Step + sext/zext(PreIncAR)" is congruent with
1376 // "sext/zext(PostIncAR)"
1377 template <typename ExtendOpTy>
1378 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1379                                         ScalarEvolution *SE, unsigned Depth) {
1380   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1381   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1382 
1383   const Loop *L = AR->getLoop();
1384   const SCEV *Start = AR->getStart();
1385   const SCEV *Step = AR->getStepRecurrence(*SE);
1386 
1387   // Check for a simple looking step prior to loop entry.
1388   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1389   if (!SA)
1390     return nullptr;
1391 
1392   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1393   // subtraction is expensive. For this purpose, perform a quick and dirty
1394   // difference, by checking for Step in the operand list.
1395   SmallVector<const SCEV *, 4> DiffOps;
1396   for (const SCEV *Op : SA->operands())
1397     if (Op != Step)
1398       DiffOps.push_back(Op);
1399 
1400   if (DiffOps.size() == SA->getNumOperands())
1401     return nullptr;
1402 
1403   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1404   // `Step`:
1405 
1406   // 1. NSW/NUW flags on the step increment.
1407   auto PreStartFlags =
1408     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1409   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1410   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1411       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1412 
1413   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1414   // "S+X does not sign/unsign-overflow".
1415   //
1416 
1417   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1418   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1419       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1420     return PreStart;
1421 
1422   // 2. Direct overflow check on the step operation's expression.
1423   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1424   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1425   const SCEV *OperandExtendedStart =
1426       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1427                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1428   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1429     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1430       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1431       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1432       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1433       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1434     }
1435     return PreStart;
1436   }
1437 
1438   // 3. Loop precondition.
1439   ICmpInst::Predicate Pred;
1440   const SCEV *OverflowLimit =
1441       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1442 
1443   if (OverflowLimit &&
1444       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1445     return PreStart;
1446 
1447   return nullptr;
1448 }
1449 
1450 // Get the normalized zero or sign extended expression for this AddRec's Start.
1451 template <typename ExtendOpTy>
1452 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1453                                         ScalarEvolution *SE,
1454                                         unsigned Depth) {
1455   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1456 
1457   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1458   if (!PreStart)
1459     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1460 
1461   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1462                                              Depth),
1463                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1464 }
1465 
1466 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1467 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1468 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1469 //
1470 // Formally:
1471 //
1472 //     {S,+,X} == {S-T,+,X} + T
1473 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1474 //
1475 // If ({S-T,+,X} + T) does not overflow  ... (1)
1476 //
1477 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1478 //
1479 // If {S-T,+,X} does not overflow  ... (2)
1480 //
1481 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1482 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1483 //
1484 // If (S-T)+T does not overflow  ... (3)
1485 //
1486 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1487 //      == {Ext(S),+,Ext(X)} == LHS
1488 //
1489 // Thus, if (1), (2) and (3) are true for some T, then
1490 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1491 //
1492 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1493 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1494 // to check for (1) and (2).
1495 //
1496 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1497 // is `Delta` (defined below).
1498 template <typename ExtendOpTy>
1499 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1500                                                 const SCEV *Step,
1501                                                 const Loop *L) {
1502   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1503 
1504   // We restrict `Start` to a constant to prevent SCEV from spending too much
1505   // time here.  It is correct (but more expensive) to continue with a
1506   // non-constant `Start` and do a general SCEV subtraction to compute
1507   // `PreStart` below.
1508   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1509   if (!StartC)
1510     return false;
1511 
1512   APInt StartAI = StartC->getAPInt();
1513 
1514   for (unsigned Delta : {-2, -1, 1, 2}) {
1515     const SCEV *PreStart = getConstant(StartAI - Delta);
1516 
1517     FoldingSetNodeID ID;
1518     ID.AddInteger(scAddRecExpr);
1519     ID.AddPointer(PreStart);
1520     ID.AddPointer(Step);
1521     ID.AddPointer(L);
1522     void *IP = nullptr;
1523     const auto *PreAR =
1524       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1525 
1526     // Give up if we don't already have the add recurrence we need because
1527     // actually constructing an add recurrence is relatively expensive.
1528     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1529       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1530       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1531       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1532           DeltaS, &Pred, this);
1533       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1534         return true;
1535     }
1536   }
1537 
1538   return false;
1539 }
1540 
1541 // Finds an integer D for an expression (C + x + y + ...) such that the top
1542 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1543 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1544 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1545 // the (C + x + y + ...) expression is \p WholeAddExpr.
1546 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1547                                             const SCEVConstant *ConstantTerm,
1548                                             const SCEVAddExpr *WholeAddExpr) {
1549   const APInt &C = ConstantTerm->getAPInt();
1550   const unsigned BitWidth = C.getBitWidth();
1551   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1552   uint32_t TZ = BitWidth;
1553   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1554     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1555   if (TZ) {
1556     // Set D to be as many least significant bits of C as possible while still
1557     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1558     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1559   }
1560   return APInt(BitWidth, 0);
1561 }
1562 
1563 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1564 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1565 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1566 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1567 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1568                                             const APInt &ConstantStart,
1569                                             const SCEV *Step) {
1570   const unsigned BitWidth = ConstantStart.getBitWidth();
1571   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1572   if (TZ)
1573     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1574                          : ConstantStart;
1575   return APInt(BitWidth, 0);
1576 }
1577 
1578 const SCEV *
1579 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1580   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1581          "This is not an extending conversion!");
1582   assert(isSCEVable(Ty) &&
1583          "This is not a conversion to a SCEVable type!");
1584   Ty = getEffectiveSCEVType(Ty);
1585 
1586   // Fold if the operand is constant.
1587   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1588     return getConstant(
1589       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1590 
1591   // zext(zext(x)) --> zext(x)
1592   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1593     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1594 
1595   // Before doing any expensive analysis, check to see if we've already
1596   // computed a SCEV for this Op and Ty.
1597   FoldingSetNodeID ID;
1598   ID.AddInteger(scZeroExtend);
1599   ID.AddPointer(Op);
1600   ID.AddPointer(Ty);
1601   void *IP = nullptr;
1602   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1603   if (Depth > MaxCastDepth) {
1604     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1605                                                      Op, Ty);
1606     UniqueSCEVs.InsertNode(S, IP);
1607     addToLoopUseLists(S);
1608     return S;
1609   }
1610 
1611   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1612   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1613     // It's possible the bits taken off by the truncate were all zero bits. If
1614     // so, we should be able to simplify this further.
1615     const SCEV *X = ST->getOperand();
1616     ConstantRange CR = getUnsignedRange(X);
1617     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1618     unsigned NewBits = getTypeSizeInBits(Ty);
1619     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1620             CR.zextOrTrunc(NewBits)))
1621       return getTruncateOrZeroExtend(X, Ty, Depth);
1622   }
1623 
1624   // If the input value is a chrec scev, and we can prove that the value
1625   // did not overflow the old, smaller, value, we can zero extend all of the
1626   // operands (often constants).  This allows analysis of something like
1627   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1628   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1629     if (AR->isAffine()) {
1630       const SCEV *Start = AR->getStart();
1631       const SCEV *Step = AR->getStepRecurrence(*this);
1632       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1633       const Loop *L = AR->getLoop();
1634 
1635       if (!AR->hasNoUnsignedWrap()) {
1636         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1637         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1638       }
1639 
1640       // If we have special knowledge that this addrec won't overflow,
1641       // we don't need to do any further analysis.
1642       if (AR->hasNoUnsignedWrap())
1643         return getAddRecExpr(
1644             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1645             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1646 
1647       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1648       // Note that this serves two purposes: It filters out loops that are
1649       // simply not analyzable, and it covers the case where this code is
1650       // being called from within backedge-taken count analysis, such that
1651       // attempting to ask for the backedge-taken count would likely result
1652       // in infinite recursion. In the later case, the analysis code will
1653       // cope with a conservative value, and it will take care to purge
1654       // that value once it has finished.
1655       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1656       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1657         // Manually compute the final value for AR, checking for overflow.
1658 
1659         // Check whether the backedge-taken count can be losslessly casted to
1660         // the addrec's type. The count is always unsigned.
1661         const SCEV *CastedMaxBECount =
1662             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1663         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1664             CastedMaxBECount, MaxBECount->getType(), Depth);
1665         if (MaxBECount == RecastedMaxBECount) {
1666           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1667           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1668           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1669                                         SCEV::FlagAnyWrap, Depth + 1);
1670           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1671                                                           SCEV::FlagAnyWrap,
1672                                                           Depth + 1),
1673                                                WideTy, Depth + 1);
1674           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1675           const SCEV *WideMaxBECount =
1676             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1677           const SCEV *OperandExtendedAdd =
1678             getAddExpr(WideStart,
1679                        getMulExpr(WideMaxBECount,
1680                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1681                                   SCEV::FlagAnyWrap, Depth + 1),
1682                        SCEV::FlagAnyWrap, Depth + 1);
1683           if (ZAdd == OperandExtendedAdd) {
1684             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1685             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1686             // Return the expression with the addrec on the outside.
1687             return getAddRecExpr(
1688                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1689                                                          Depth + 1),
1690                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1691                 AR->getNoWrapFlags());
1692           }
1693           // Similar to above, only this time treat the step value as signed.
1694           // This covers loops that count down.
1695           OperandExtendedAdd =
1696             getAddExpr(WideStart,
1697                        getMulExpr(WideMaxBECount,
1698                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1699                                   SCEV::FlagAnyWrap, Depth + 1),
1700                        SCEV::FlagAnyWrap, Depth + 1);
1701           if (ZAdd == OperandExtendedAdd) {
1702             // Cache knowledge of AR NW, which is propagated to this AddRec.
1703             // Negative step causes unsigned wrap, but it still can't self-wrap.
1704             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1705             // Return the expression with the addrec on the outside.
1706             return getAddRecExpr(
1707                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1708                                                          Depth + 1),
1709                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1710                 AR->getNoWrapFlags());
1711           }
1712         }
1713       }
1714 
1715       // Normally, in the cases we can prove no-overflow via a
1716       // backedge guarding condition, we can also compute a backedge
1717       // taken count for the loop.  The exceptions are assumptions and
1718       // guards present in the loop -- SCEV is not great at exploiting
1719       // these to compute max backedge taken counts, but can still use
1720       // these to prove lack of overflow.  Use this fact to avoid
1721       // doing extra work that may not pay off.
1722       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1723           !AC.assumptions().empty()) {
1724 
1725         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1726         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1727         if (AR->hasNoUnsignedWrap()) {
1728           // Same as nuw case above - duplicated here to avoid a compile time
1729           // issue.  It's not clear that the order of checks does matter, but
1730           // it's one of two issue possible causes for a change which was
1731           // reverted.  Be conservative for the moment.
1732           return getAddRecExpr(
1733                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1734                                                          Depth + 1),
1735                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1736                 AR->getNoWrapFlags());
1737         }
1738 
1739         // For a negative step, we can extend the operands iff doing so only
1740         // traverses values in the range zext([0,UINT_MAX]).
1741         if (isKnownNegative(Step)) {
1742           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1743                                       getSignedRangeMin(Step));
1744           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1745               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1746             // Cache knowledge of AR NW, which is propagated to this
1747             // AddRec.  Negative step causes unsigned wrap, but it
1748             // still can't self-wrap.
1749             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1750             // Return the expression with the addrec on the outside.
1751             return getAddRecExpr(
1752                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1753                                                          Depth + 1),
1754                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1755                 AR->getNoWrapFlags());
1756           }
1757         }
1758       }
1759 
1760       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1761       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1762       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1763       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1764         const APInt &C = SC->getAPInt();
1765         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1766         if (D != 0) {
1767           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1768           const SCEV *SResidual =
1769               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1770           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1771           return getAddExpr(SZExtD, SZExtR,
1772                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1773                             Depth + 1);
1774         }
1775       }
1776 
1777       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1778         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1779         return getAddRecExpr(
1780             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1781             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1782       }
1783     }
1784 
1785   // zext(A % B) --> zext(A) % zext(B)
1786   {
1787     const SCEV *LHS;
1788     const SCEV *RHS;
1789     if (matchURem(Op, LHS, RHS))
1790       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1791                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1792   }
1793 
1794   // zext(A / B) --> zext(A) / zext(B).
1795   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1796     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1797                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1798 
1799   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1800     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1801     if (SA->hasNoUnsignedWrap()) {
1802       // If the addition does not unsign overflow then we can, by definition,
1803       // commute the zero extension with the addition operation.
1804       SmallVector<const SCEV *, 4> Ops;
1805       for (const auto *Op : SA->operands())
1806         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1807       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1808     }
1809 
1810     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1811     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1812     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1813     //
1814     // Often address arithmetics contain expressions like
1815     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1816     // This transformation is useful while proving that such expressions are
1817     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1818     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1819       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1820       if (D != 0) {
1821         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1822         const SCEV *SResidual =
1823             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1824         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1825         return getAddExpr(SZExtD, SZExtR,
1826                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1827                           Depth + 1);
1828       }
1829     }
1830   }
1831 
1832   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1833     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1834     if (SM->hasNoUnsignedWrap()) {
1835       // If the multiply does not unsign overflow then we can, by definition,
1836       // commute the zero extension with the multiply operation.
1837       SmallVector<const SCEV *, 4> Ops;
1838       for (const auto *Op : SM->operands())
1839         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1840       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1841     }
1842 
1843     // zext(2^K * (trunc X to iN)) to iM ->
1844     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1845     //
1846     // Proof:
1847     //
1848     //     zext(2^K * (trunc X to iN)) to iM
1849     //   = zext((trunc X to iN) << K) to iM
1850     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1851     //     (because shl removes the top K bits)
1852     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1853     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1854     //
1855     if (SM->getNumOperands() == 2)
1856       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1857         if (MulLHS->getAPInt().isPowerOf2())
1858           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1859             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1860                                MulLHS->getAPInt().logBase2();
1861             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1862             return getMulExpr(
1863                 getZeroExtendExpr(MulLHS, Ty),
1864                 getZeroExtendExpr(
1865                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1866                 SCEV::FlagNUW, Depth + 1);
1867           }
1868   }
1869 
1870   // The cast wasn't folded; create an explicit cast node.
1871   // Recompute the insert position, as it may have been invalidated.
1872   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1873   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1874                                                    Op, Ty);
1875   UniqueSCEVs.InsertNode(S, IP);
1876   addToLoopUseLists(S);
1877   return S;
1878 }
1879 
1880 const SCEV *
1881 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1882   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1883          "This is not an extending conversion!");
1884   assert(isSCEVable(Ty) &&
1885          "This is not a conversion to a SCEVable type!");
1886   Ty = getEffectiveSCEVType(Ty);
1887 
1888   // Fold if the operand is constant.
1889   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1890     return getConstant(
1891       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1892 
1893   // sext(sext(x)) --> sext(x)
1894   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1895     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1896 
1897   // sext(zext(x)) --> zext(x)
1898   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1899     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1900 
1901   // Before doing any expensive analysis, check to see if we've already
1902   // computed a SCEV for this Op and Ty.
1903   FoldingSetNodeID ID;
1904   ID.AddInteger(scSignExtend);
1905   ID.AddPointer(Op);
1906   ID.AddPointer(Ty);
1907   void *IP = nullptr;
1908   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1909   // Limit recursion depth.
1910   if (Depth > MaxCastDepth) {
1911     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1912                                                      Op, Ty);
1913     UniqueSCEVs.InsertNode(S, IP);
1914     addToLoopUseLists(S);
1915     return S;
1916   }
1917 
1918   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1919   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1920     // It's possible the bits taken off by the truncate were all sign bits. If
1921     // so, we should be able to simplify this further.
1922     const SCEV *X = ST->getOperand();
1923     ConstantRange CR = getSignedRange(X);
1924     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1925     unsigned NewBits = getTypeSizeInBits(Ty);
1926     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1927             CR.sextOrTrunc(NewBits)))
1928       return getTruncateOrSignExtend(X, Ty, Depth);
1929   }
1930 
1931   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1932     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1933     if (SA->hasNoSignedWrap()) {
1934       // If the addition does not sign overflow then we can, by definition,
1935       // commute the sign extension with the addition operation.
1936       SmallVector<const SCEV *, 4> Ops;
1937       for (const auto *Op : SA->operands())
1938         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1939       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1940     }
1941 
1942     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1943     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1944     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1945     //
1946     // For instance, this will bring two seemingly different expressions:
1947     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1948     //         sext(6 + 20 * %x + 24 * %y)
1949     // to the same form:
1950     //     2 + sext(4 + 20 * %x + 24 * %y)
1951     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1952       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1953       if (D != 0) {
1954         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1955         const SCEV *SResidual =
1956             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1957         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1958         return getAddExpr(SSExtD, SSExtR,
1959                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1960                           Depth + 1);
1961       }
1962     }
1963   }
1964   // If the input value is a chrec scev, and we can prove that the value
1965   // did not overflow the old, smaller, value, we can sign extend all of the
1966   // operands (often constants).  This allows analysis of something like
1967   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1968   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1969     if (AR->isAffine()) {
1970       const SCEV *Start = AR->getStart();
1971       const SCEV *Step = AR->getStepRecurrence(*this);
1972       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1973       const Loop *L = AR->getLoop();
1974 
1975       if (!AR->hasNoSignedWrap()) {
1976         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1977         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1978       }
1979 
1980       // If we have special knowledge that this addrec won't overflow,
1981       // we don't need to do any further analysis.
1982       if (AR->hasNoSignedWrap())
1983         return getAddRecExpr(
1984             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1985             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1986 
1987       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1988       // Note that this serves two purposes: It filters out loops that are
1989       // simply not analyzable, and it covers the case where this code is
1990       // being called from within backedge-taken count analysis, such that
1991       // attempting to ask for the backedge-taken count would likely result
1992       // in infinite recursion. In the later case, the analysis code will
1993       // cope with a conservative value, and it will take care to purge
1994       // that value once it has finished.
1995       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1996       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1997         // Manually compute the final value for AR, checking for
1998         // overflow.
1999 
2000         // Check whether the backedge-taken count can be losslessly casted to
2001         // the addrec's type. The count is always unsigned.
2002         const SCEV *CastedMaxBECount =
2003             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2004         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2005             CastedMaxBECount, MaxBECount->getType(), Depth);
2006         if (MaxBECount == RecastedMaxBECount) {
2007           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2008           // Check whether Start+Step*MaxBECount has no signed overflow.
2009           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2010                                         SCEV::FlagAnyWrap, Depth + 1);
2011           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2012                                                           SCEV::FlagAnyWrap,
2013                                                           Depth + 1),
2014                                                WideTy, Depth + 1);
2015           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2016           const SCEV *WideMaxBECount =
2017             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2018           const SCEV *OperandExtendedAdd =
2019             getAddExpr(WideStart,
2020                        getMulExpr(WideMaxBECount,
2021                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2022                                   SCEV::FlagAnyWrap, Depth + 1),
2023                        SCEV::FlagAnyWrap, Depth + 1);
2024           if (SAdd == OperandExtendedAdd) {
2025             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2026             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2027             // Return the expression with the addrec on the outside.
2028             return getAddRecExpr(
2029                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2030                                                          Depth + 1),
2031                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2032                 AR->getNoWrapFlags());
2033           }
2034           // Similar to above, only this time treat the step value as unsigned.
2035           // This covers loops that count up with an unsigned step.
2036           OperandExtendedAdd =
2037             getAddExpr(WideStart,
2038                        getMulExpr(WideMaxBECount,
2039                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2040                                   SCEV::FlagAnyWrap, Depth + 1),
2041                        SCEV::FlagAnyWrap, Depth + 1);
2042           if (SAdd == OperandExtendedAdd) {
2043             // If AR wraps around then
2044             //
2045             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2046             // => SAdd != OperandExtendedAdd
2047             //
2048             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2049             // (SAdd == OperandExtendedAdd => AR is NW)
2050 
2051             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2052 
2053             // Return the expression with the addrec on the outside.
2054             return getAddRecExpr(
2055                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2056                                                          Depth + 1),
2057                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2058                 AR->getNoWrapFlags());
2059           }
2060         }
2061       }
2062 
2063       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2064       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2065       if (AR->hasNoSignedWrap()) {
2066         // Same as nsw case above - duplicated here to avoid a compile time
2067         // issue.  It's not clear that the order of checks does matter, but
2068         // it's one of two issue possible causes for a change which was
2069         // reverted.  Be conservative for the moment.
2070         return getAddRecExpr(
2071             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2072             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2073       }
2074 
2075       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2076       // if D + (C - D + Step * n) could be proven to not signed wrap
2077       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2078       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2079         const APInt &C = SC->getAPInt();
2080         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2081         if (D != 0) {
2082           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2083           const SCEV *SResidual =
2084               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2085           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2086           return getAddExpr(SSExtD, SSExtR,
2087                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2088                             Depth + 1);
2089         }
2090       }
2091 
2092       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2093         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2094         return getAddRecExpr(
2095             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2096             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2097       }
2098     }
2099 
2100   // If the input value is provably positive and we could not simplify
2101   // away the sext build a zext instead.
2102   if (isKnownNonNegative(Op))
2103     return getZeroExtendExpr(Op, Ty, Depth + 1);
2104 
2105   // The cast wasn't folded; create an explicit cast node.
2106   // Recompute the insert position, as it may have been invalidated.
2107   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2108   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2109                                                    Op, Ty);
2110   UniqueSCEVs.InsertNode(S, IP);
2111   addToLoopUseLists(S);
2112   return S;
2113 }
2114 
2115 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2116 /// unspecified bits out to the given type.
2117 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2118                                               Type *Ty) {
2119   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2120          "This is not an extending conversion!");
2121   assert(isSCEVable(Ty) &&
2122          "This is not a conversion to a SCEVable type!");
2123   Ty = getEffectiveSCEVType(Ty);
2124 
2125   // Sign-extend negative constants.
2126   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2127     if (SC->getAPInt().isNegative())
2128       return getSignExtendExpr(Op, Ty);
2129 
2130   // Peel off a truncate cast.
2131   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2132     const SCEV *NewOp = T->getOperand();
2133     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2134       return getAnyExtendExpr(NewOp, Ty);
2135     return getTruncateOrNoop(NewOp, Ty);
2136   }
2137 
2138   // Next try a zext cast. If the cast is folded, use it.
2139   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2140   if (!isa<SCEVZeroExtendExpr>(ZExt))
2141     return ZExt;
2142 
2143   // Next try a sext cast. If the cast is folded, use it.
2144   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2145   if (!isa<SCEVSignExtendExpr>(SExt))
2146     return SExt;
2147 
2148   // Force the cast to be folded into the operands of an addrec.
2149   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2150     SmallVector<const SCEV *, 4> Ops;
2151     for (const SCEV *Op : AR->operands())
2152       Ops.push_back(getAnyExtendExpr(Op, Ty));
2153     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2154   }
2155 
2156   // If the expression is obviously signed, use the sext cast value.
2157   if (isa<SCEVSMaxExpr>(Op))
2158     return SExt;
2159 
2160   // Absent any other information, use the zext cast value.
2161   return ZExt;
2162 }
2163 
2164 /// Process the given Ops list, which is a list of operands to be added under
2165 /// the given scale, update the given map. This is a helper function for
2166 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2167 /// that would form an add expression like this:
2168 ///
2169 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2170 ///
2171 /// where A and B are constants, update the map with these values:
2172 ///
2173 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2174 ///
2175 /// and add 13 + A*B*29 to AccumulatedConstant.
2176 /// This will allow getAddRecExpr to produce this:
2177 ///
2178 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2179 ///
2180 /// This form often exposes folding opportunities that are hidden in
2181 /// the original operand list.
2182 ///
2183 /// Return true iff it appears that any interesting folding opportunities
2184 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2185 /// the common case where no interesting opportunities are present, and
2186 /// is also used as a check to avoid infinite recursion.
2187 static bool
2188 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2189                              SmallVectorImpl<const SCEV *> &NewOps,
2190                              APInt &AccumulatedConstant,
2191                              const SCEV *const *Ops, size_t NumOperands,
2192                              const APInt &Scale,
2193                              ScalarEvolution &SE) {
2194   bool Interesting = false;
2195 
2196   // Iterate over the add operands. They are sorted, with constants first.
2197   unsigned i = 0;
2198   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2199     ++i;
2200     // Pull a buried constant out to the outside.
2201     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2202       Interesting = true;
2203     AccumulatedConstant += Scale * C->getAPInt();
2204   }
2205 
2206   // Next comes everything else. We're especially interested in multiplies
2207   // here, but they're in the middle, so just visit the rest with one loop.
2208   for (; i != NumOperands; ++i) {
2209     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2210     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2211       APInt NewScale =
2212           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2213       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2214         // A multiplication of a constant with another add; recurse.
2215         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2216         Interesting |=
2217           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2218                                        Add->op_begin(), Add->getNumOperands(),
2219                                        NewScale, SE);
2220       } else {
2221         // A multiplication of a constant with some other value. Update
2222         // the map.
2223         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2224         const SCEV *Key = SE.getMulExpr(MulOps);
2225         auto Pair = M.insert({Key, NewScale});
2226         if (Pair.second) {
2227           NewOps.push_back(Pair.first->first);
2228         } else {
2229           Pair.first->second += NewScale;
2230           // The map already had an entry for this value, which may indicate
2231           // a folding opportunity.
2232           Interesting = true;
2233         }
2234       }
2235     } else {
2236       // An ordinary operand. Update the map.
2237       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2238           M.insert({Ops[i], Scale});
2239       if (Pair.second) {
2240         NewOps.push_back(Pair.first->first);
2241       } else {
2242         Pair.first->second += Scale;
2243         // The map already had an entry for this value, which may indicate
2244         // a folding opportunity.
2245         Interesting = true;
2246       }
2247     }
2248   }
2249 
2250   return Interesting;
2251 }
2252 
2253 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2254                                       const SCEV *LHS, const SCEV *RHS) {
2255   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2256                                             SCEV::NoWrapFlags, unsigned);
2257   switch (BinOp) {
2258   default:
2259     llvm_unreachable("Unsupported binary op");
2260   case Instruction::Add:
2261     Operation = &ScalarEvolution::getAddExpr;
2262     break;
2263   case Instruction::Sub:
2264     Operation = &ScalarEvolution::getMinusSCEV;
2265     break;
2266   case Instruction::Mul:
2267     Operation = &ScalarEvolution::getMulExpr;
2268     break;
2269   }
2270 
2271   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2272       Signed ? &ScalarEvolution::getSignExtendExpr
2273              : &ScalarEvolution::getZeroExtendExpr;
2274 
2275   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2276   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2277   auto *WideTy =
2278       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2279 
2280   const SCEV *A = (this->*Extension)(
2281       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2282   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2283                                      (this->*Extension)(RHS, WideTy, 0),
2284                                      SCEV::FlagAnyWrap, 0);
2285   return A == B;
2286 }
2287 
2288 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2289 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2290     const OverflowingBinaryOperator *OBO) {
2291   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2292 
2293   if (OBO->hasNoUnsignedWrap())
2294     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2295   if (OBO->hasNoSignedWrap())
2296     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2297 
2298   bool Deduced = false;
2299 
2300   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2301     return {Flags, Deduced};
2302 
2303   if (OBO->getOpcode() != Instruction::Add &&
2304       OBO->getOpcode() != Instruction::Sub &&
2305       OBO->getOpcode() != Instruction::Mul)
2306     return {Flags, Deduced};
2307 
2308   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2309   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2310 
2311   if (!OBO->hasNoUnsignedWrap() &&
2312       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2313                       /* Signed */ false, LHS, RHS)) {
2314     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2315     Deduced = true;
2316   }
2317 
2318   if (!OBO->hasNoSignedWrap() &&
2319       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2320                       /* Signed */ true, LHS, RHS)) {
2321     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2322     Deduced = true;
2323   }
2324 
2325   return {Flags, Deduced};
2326 }
2327 
2328 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2329 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2330 // can't-overflow flags for the operation if possible.
2331 static SCEV::NoWrapFlags
2332 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2333                       const ArrayRef<const SCEV *> Ops,
2334                       SCEV::NoWrapFlags Flags) {
2335   using namespace std::placeholders;
2336 
2337   using OBO = OverflowingBinaryOperator;
2338 
2339   bool CanAnalyze =
2340       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2341   (void)CanAnalyze;
2342   assert(CanAnalyze && "don't call from other places!");
2343 
2344   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2345   SCEV::NoWrapFlags SignOrUnsignWrap =
2346       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2347 
2348   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2349   auto IsKnownNonNegative = [&](const SCEV *S) {
2350     return SE->isKnownNonNegative(S);
2351   };
2352 
2353   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2354     Flags =
2355         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2356 
2357   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2358 
2359   if (SignOrUnsignWrap != SignOrUnsignMask &&
2360       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2361       isa<SCEVConstant>(Ops[0])) {
2362 
2363     auto Opcode = [&] {
2364       switch (Type) {
2365       case scAddExpr:
2366         return Instruction::Add;
2367       case scMulExpr:
2368         return Instruction::Mul;
2369       default:
2370         llvm_unreachable("Unexpected SCEV op.");
2371       }
2372     }();
2373 
2374     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2375 
2376     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2377     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2378       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2379           Opcode, C, OBO::NoSignedWrap);
2380       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2381         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2382     }
2383 
2384     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2385     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2386       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2387           Opcode, C, OBO::NoUnsignedWrap);
2388       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2389         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2390     }
2391   }
2392 
2393   return Flags;
2394 }
2395 
2396 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2397   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2398 }
2399 
2400 /// Get a canonical add expression, or something simpler if possible.
2401 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2402                                         SCEV::NoWrapFlags OrigFlags,
2403                                         unsigned Depth) {
2404   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2405          "only nuw or nsw allowed");
2406   assert(!Ops.empty() && "Cannot get empty add!");
2407   if (Ops.size() == 1) return Ops[0];
2408 #ifndef NDEBUG
2409   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2410   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2411     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2412            "SCEVAddExpr operand types don't match!");
2413 #endif
2414 
2415   // Sort by complexity, this groups all similar expression types together.
2416   GroupByComplexity(Ops, &LI, DT);
2417 
2418   // If there are any constants, fold them together.
2419   unsigned Idx = 0;
2420   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2421     ++Idx;
2422     assert(Idx < Ops.size());
2423     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2424       // We found two constants, fold them together!
2425       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2426       if (Ops.size() == 2) return Ops[0];
2427       Ops.erase(Ops.begin()+1);  // Erase the folded element
2428       LHSC = cast<SCEVConstant>(Ops[0]);
2429     }
2430 
2431     // If we are left with a constant zero being added, strip it off.
2432     if (LHSC->getValue()->isZero()) {
2433       Ops.erase(Ops.begin());
2434       --Idx;
2435     }
2436 
2437     if (Ops.size() == 1) return Ops[0];
2438   }
2439 
2440   // Delay expensive flag strengthening until necessary.
2441   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2442     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2443   };
2444 
2445   // Limit recursion calls depth.
2446   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2447     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2448 
2449   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2450     // Don't strengthen flags if we have no new information.
2451     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2452     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2453       Add->setNoWrapFlags(ComputeFlags(Ops));
2454     return S;
2455   }
2456 
2457   // Okay, check to see if the same value occurs in the operand list more than
2458   // once.  If so, merge them together into an multiply expression.  Since we
2459   // sorted the list, these values are required to be adjacent.
2460   Type *Ty = Ops[0]->getType();
2461   bool FoundMatch = false;
2462   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2463     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2464       // Scan ahead to count how many equal operands there are.
2465       unsigned Count = 2;
2466       while (i+Count != e && Ops[i+Count] == Ops[i])
2467         ++Count;
2468       // Merge the values into a multiply.
2469       const SCEV *Scale = getConstant(Ty, Count);
2470       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2471       if (Ops.size() == Count)
2472         return Mul;
2473       Ops[i] = Mul;
2474       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2475       --i; e -= Count - 1;
2476       FoundMatch = true;
2477     }
2478   if (FoundMatch)
2479     return getAddExpr(Ops, OrigFlags, Depth + 1);
2480 
2481   // Check for truncates. If all the operands are truncated from the same
2482   // type, see if factoring out the truncate would permit the result to be
2483   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2484   // if the contents of the resulting outer trunc fold to something simple.
2485   auto FindTruncSrcType = [&]() -> Type * {
2486     // We're ultimately looking to fold an addrec of truncs and muls of only
2487     // constants and truncs, so if we find any other types of SCEV
2488     // as operands of the addrec then we bail and return nullptr here.
2489     // Otherwise, we return the type of the operand of a trunc that we find.
2490     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2491       return T->getOperand()->getType();
2492     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2493       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2494       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2495         return T->getOperand()->getType();
2496     }
2497     return nullptr;
2498   };
2499   if (auto *SrcType = FindTruncSrcType()) {
2500     SmallVector<const SCEV *, 8> LargeOps;
2501     bool Ok = true;
2502     // Check all the operands to see if they can be represented in the
2503     // source type of the truncate.
2504     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2505       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2506         if (T->getOperand()->getType() != SrcType) {
2507           Ok = false;
2508           break;
2509         }
2510         LargeOps.push_back(T->getOperand());
2511       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2512         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2513       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2514         SmallVector<const SCEV *, 8> LargeMulOps;
2515         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2516           if (const SCEVTruncateExpr *T =
2517                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2518             if (T->getOperand()->getType() != SrcType) {
2519               Ok = false;
2520               break;
2521             }
2522             LargeMulOps.push_back(T->getOperand());
2523           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2524             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2525           } else {
2526             Ok = false;
2527             break;
2528           }
2529         }
2530         if (Ok)
2531           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2532       } else {
2533         Ok = false;
2534         break;
2535       }
2536     }
2537     if (Ok) {
2538       // Evaluate the expression in the larger type.
2539       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2540       // If it folds to something simple, use it. Otherwise, don't.
2541       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2542         return getTruncateExpr(Fold, Ty);
2543     }
2544   }
2545 
2546   if (Ops.size() == 2) {
2547     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2548     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2549     // C1).
2550     const SCEV *A = Ops[0];
2551     const SCEV *B = Ops[1];
2552     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2553     auto *C = dyn_cast<SCEVConstant>(A);
2554     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2555       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2556       auto C2 = C->getAPInt();
2557       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2558 
2559       APInt ConstAdd = C1 + C2;
2560       auto AddFlags = AddExpr->getNoWrapFlags();
2561       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2562       if (ScalarEvolution::maskFlags(AddFlags, SCEV::FlagNUW) ==
2563               SCEV::FlagNUW &&
2564           ConstAdd.ule(C1)) {
2565         PreservedFlags =
2566             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2567       }
2568 
2569       // Adding a constant with the same sign and small magnitude is NSW, if the
2570       // original AddExpr was NSW.
2571       if (ScalarEvolution::maskFlags(AddFlags, SCEV::FlagNSW) ==
2572               SCEV::FlagNSW &&
2573           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2574           ConstAdd.abs().ule(C1.abs())) {
2575         PreservedFlags =
2576             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2577       }
2578 
2579       if (PreservedFlags != SCEV::FlagAnyWrap) {
2580         SmallVector<const SCEV *, 4> NewOps(AddExpr->op_begin(),
2581                                             AddExpr->op_end());
2582         NewOps[0] = getConstant(ConstAdd);
2583         return getAddExpr(NewOps, PreservedFlags);
2584       }
2585     }
2586   }
2587 
2588   // Skip past any other cast SCEVs.
2589   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2590     ++Idx;
2591 
2592   // If there are add operands they would be next.
2593   if (Idx < Ops.size()) {
2594     bool DeletedAdd = false;
2595     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2596     // common NUW flag for expression after inlining. Other flags cannot be
2597     // preserved, because they may depend on the original order of operations.
2598     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2599     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2600       if (Ops.size() > AddOpsInlineThreshold ||
2601           Add->getNumOperands() > AddOpsInlineThreshold)
2602         break;
2603       // If we have an add, expand the add operands onto the end of the operands
2604       // list.
2605       Ops.erase(Ops.begin()+Idx);
2606       Ops.append(Add->op_begin(), Add->op_end());
2607       DeletedAdd = true;
2608       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2609     }
2610 
2611     // If we deleted at least one add, we added operands to the end of the list,
2612     // and they are not necessarily sorted.  Recurse to resort and resimplify
2613     // any operands we just acquired.
2614     if (DeletedAdd)
2615       return getAddExpr(Ops, CommonFlags, Depth + 1);
2616   }
2617 
2618   // Skip over the add expression until we get to a multiply.
2619   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2620     ++Idx;
2621 
2622   // Check to see if there are any folding opportunities present with
2623   // operands multiplied by constant values.
2624   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2625     uint64_t BitWidth = getTypeSizeInBits(Ty);
2626     DenseMap<const SCEV *, APInt> M;
2627     SmallVector<const SCEV *, 8> NewOps;
2628     APInt AccumulatedConstant(BitWidth, 0);
2629     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2630                                      Ops.data(), Ops.size(),
2631                                      APInt(BitWidth, 1), *this)) {
2632       struct APIntCompare {
2633         bool operator()(const APInt &LHS, const APInt &RHS) const {
2634           return LHS.ult(RHS);
2635         }
2636       };
2637 
2638       // Some interesting folding opportunity is present, so its worthwhile to
2639       // re-generate the operands list. Group the operands by constant scale,
2640       // to avoid multiplying by the same constant scale multiple times.
2641       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2642       for (const SCEV *NewOp : NewOps)
2643         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2644       // Re-generate the operands list.
2645       Ops.clear();
2646       if (AccumulatedConstant != 0)
2647         Ops.push_back(getConstant(AccumulatedConstant));
2648       for (auto &MulOp : MulOpLists)
2649         if (MulOp.first != 0)
2650           Ops.push_back(getMulExpr(
2651               getConstant(MulOp.first),
2652               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2653               SCEV::FlagAnyWrap, Depth + 1));
2654       if (Ops.empty())
2655         return getZero(Ty);
2656       if (Ops.size() == 1)
2657         return Ops[0];
2658       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2659     }
2660   }
2661 
2662   // If we are adding something to a multiply expression, make sure the
2663   // something is not already an operand of the multiply.  If so, merge it into
2664   // the multiply.
2665   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2666     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2667     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2668       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2669       if (isa<SCEVConstant>(MulOpSCEV))
2670         continue;
2671       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2672         if (MulOpSCEV == Ops[AddOp]) {
2673           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2674           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2675           if (Mul->getNumOperands() != 2) {
2676             // If the multiply has more than two operands, we must get the
2677             // Y*Z term.
2678             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2679                                                 Mul->op_begin()+MulOp);
2680             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2681             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2682           }
2683           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2684           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2685           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2686                                             SCEV::FlagAnyWrap, Depth + 1);
2687           if (Ops.size() == 2) return OuterMul;
2688           if (AddOp < Idx) {
2689             Ops.erase(Ops.begin()+AddOp);
2690             Ops.erase(Ops.begin()+Idx-1);
2691           } else {
2692             Ops.erase(Ops.begin()+Idx);
2693             Ops.erase(Ops.begin()+AddOp-1);
2694           }
2695           Ops.push_back(OuterMul);
2696           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2697         }
2698 
2699       // Check this multiply against other multiplies being added together.
2700       for (unsigned OtherMulIdx = Idx+1;
2701            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2702            ++OtherMulIdx) {
2703         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2704         // If MulOp occurs in OtherMul, we can fold the two multiplies
2705         // together.
2706         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2707              OMulOp != e; ++OMulOp)
2708           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2709             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2710             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2711             if (Mul->getNumOperands() != 2) {
2712               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2713                                                   Mul->op_begin()+MulOp);
2714               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2715               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2716             }
2717             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2718             if (OtherMul->getNumOperands() != 2) {
2719               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2720                                                   OtherMul->op_begin()+OMulOp);
2721               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2722               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2723             }
2724             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2725             const SCEV *InnerMulSum =
2726                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2727             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2728                                               SCEV::FlagAnyWrap, Depth + 1);
2729             if (Ops.size() == 2) return OuterMul;
2730             Ops.erase(Ops.begin()+Idx);
2731             Ops.erase(Ops.begin()+OtherMulIdx-1);
2732             Ops.push_back(OuterMul);
2733             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2734           }
2735       }
2736     }
2737   }
2738 
2739   // If there are any add recurrences in the operands list, see if any other
2740   // added values are loop invariant.  If so, we can fold them into the
2741   // recurrence.
2742   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2743     ++Idx;
2744 
2745   // Scan over all recurrences, trying to fold loop invariants into them.
2746   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2747     // Scan all of the other operands to this add and add them to the vector if
2748     // they are loop invariant w.r.t. the recurrence.
2749     SmallVector<const SCEV *, 8> LIOps;
2750     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2751     const Loop *AddRecLoop = AddRec->getLoop();
2752     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2753       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2754         LIOps.push_back(Ops[i]);
2755         Ops.erase(Ops.begin()+i);
2756         --i; --e;
2757       }
2758 
2759     // If we found some loop invariants, fold them into the recurrence.
2760     if (!LIOps.empty()) {
2761       // Compute nowrap flags for the addition of the loop-invariant ops and
2762       // the addrec. Temporarily push it as an operand for that purpose.
2763       LIOps.push_back(AddRec);
2764       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2765       LIOps.pop_back();
2766 
2767       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2768       LIOps.push_back(AddRec->getStart());
2769 
2770       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2771       // This follows from the fact that the no-wrap flags on the outer add
2772       // expression are applicable on the 0th iteration, when the add recurrence
2773       // will be equal to its start value.
2774       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2775 
2776       // Build the new addrec. Propagate the NUW and NSW flags if both the
2777       // outer add and the inner addrec are guaranteed to have no overflow.
2778       // Always propagate NW.
2779       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2780       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2781 
2782       // If all of the other operands were loop invariant, we are done.
2783       if (Ops.size() == 1) return NewRec;
2784 
2785       // Otherwise, add the folded AddRec by the non-invariant parts.
2786       for (unsigned i = 0;; ++i)
2787         if (Ops[i] == AddRec) {
2788           Ops[i] = NewRec;
2789           break;
2790         }
2791       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2792     }
2793 
2794     // Okay, if there weren't any loop invariants to be folded, check to see if
2795     // there are multiple AddRec's with the same loop induction variable being
2796     // added together.  If so, we can fold them.
2797     for (unsigned OtherIdx = Idx+1;
2798          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2799          ++OtherIdx) {
2800       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2801       // so that the 1st found AddRecExpr is dominated by all others.
2802       assert(DT.dominates(
2803            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2804            AddRec->getLoop()->getHeader()) &&
2805         "AddRecExprs are not sorted in reverse dominance order?");
2806       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2807         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2808         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2809         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2810              ++OtherIdx) {
2811           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2812           if (OtherAddRec->getLoop() == AddRecLoop) {
2813             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2814                  i != e; ++i) {
2815               if (i >= AddRecOps.size()) {
2816                 AddRecOps.append(OtherAddRec->op_begin()+i,
2817                                  OtherAddRec->op_end());
2818                 break;
2819               }
2820               SmallVector<const SCEV *, 2> TwoOps = {
2821                   AddRecOps[i], OtherAddRec->getOperand(i)};
2822               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2823             }
2824             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2825           }
2826         }
2827         // Step size has changed, so we cannot guarantee no self-wraparound.
2828         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2829         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2830       }
2831     }
2832 
2833     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2834     // next one.
2835   }
2836 
2837   // Okay, it looks like we really DO need an add expr.  Check to see if we
2838   // already have one, otherwise create a new one.
2839   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2840 }
2841 
2842 const SCEV *
2843 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2844                                     SCEV::NoWrapFlags Flags) {
2845   FoldingSetNodeID ID;
2846   ID.AddInteger(scAddExpr);
2847   for (const SCEV *Op : Ops)
2848     ID.AddPointer(Op);
2849   void *IP = nullptr;
2850   SCEVAddExpr *S =
2851       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2852   if (!S) {
2853     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2854     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2855     S = new (SCEVAllocator)
2856         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2857     UniqueSCEVs.InsertNode(S, IP);
2858     addToLoopUseLists(S);
2859   }
2860   S->setNoWrapFlags(Flags);
2861   return S;
2862 }
2863 
2864 const SCEV *
2865 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2866                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2867   FoldingSetNodeID ID;
2868   ID.AddInteger(scAddRecExpr);
2869   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2870     ID.AddPointer(Ops[i]);
2871   ID.AddPointer(L);
2872   void *IP = nullptr;
2873   SCEVAddRecExpr *S =
2874       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2875   if (!S) {
2876     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2877     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2878     S = new (SCEVAllocator)
2879         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2880     UniqueSCEVs.InsertNode(S, IP);
2881     addToLoopUseLists(S);
2882   }
2883   setNoWrapFlags(S, Flags);
2884   return S;
2885 }
2886 
2887 const SCEV *
2888 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2889                                     SCEV::NoWrapFlags Flags) {
2890   FoldingSetNodeID ID;
2891   ID.AddInteger(scMulExpr);
2892   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2893     ID.AddPointer(Ops[i]);
2894   void *IP = nullptr;
2895   SCEVMulExpr *S =
2896     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2897   if (!S) {
2898     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2899     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2900     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2901                                         O, Ops.size());
2902     UniqueSCEVs.InsertNode(S, IP);
2903     addToLoopUseLists(S);
2904   }
2905   S->setNoWrapFlags(Flags);
2906   return S;
2907 }
2908 
2909 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2910   uint64_t k = i*j;
2911   if (j > 1 && k / j != i) Overflow = true;
2912   return k;
2913 }
2914 
2915 /// Compute the result of "n choose k", the binomial coefficient.  If an
2916 /// intermediate computation overflows, Overflow will be set and the return will
2917 /// be garbage. Overflow is not cleared on absence of overflow.
2918 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2919   // We use the multiplicative formula:
2920   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2921   // At each iteration, we take the n-th term of the numeral and divide by the
2922   // (k-n)th term of the denominator.  This division will always produce an
2923   // integral result, and helps reduce the chance of overflow in the
2924   // intermediate computations. However, we can still overflow even when the
2925   // final result would fit.
2926 
2927   if (n == 0 || n == k) return 1;
2928   if (k > n) return 0;
2929 
2930   if (k > n/2)
2931     k = n-k;
2932 
2933   uint64_t r = 1;
2934   for (uint64_t i = 1; i <= k; ++i) {
2935     r = umul_ov(r, n-(i-1), Overflow);
2936     r /= i;
2937   }
2938   return r;
2939 }
2940 
2941 /// Determine if any of the operands in this SCEV are a constant or if
2942 /// any of the add or multiply expressions in this SCEV contain a constant.
2943 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2944   struct FindConstantInAddMulChain {
2945     bool FoundConstant = false;
2946 
2947     bool follow(const SCEV *S) {
2948       FoundConstant |= isa<SCEVConstant>(S);
2949       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2950     }
2951 
2952     bool isDone() const {
2953       return FoundConstant;
2954     }
2955   };
2956 
2957   FindConstantInAddMulChain F;
2958   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2959   ST.visitAll(StartExpr);
2960   return F.FoundConstant;
2961 }
2962 
2963 /// Get a canonical multiply expression, or something simpler if possible.
2964 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2965                                         SCEV::NoWrapFlags OrigFlags,
2966                                         unsigned Depth) {
2967   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2968          "only nuw or nsw allowed");
2969   assert(!Ops.empty() && "Cannot get empty mul!");
2970   if (Ops.size() == 1) return Ops[0];
2971 #ifndef NDEBUG
2972   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2973   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2974     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2975            "SCEVMulExpr operand types don't match!");
2976 #endif
2977 
2978   // Sort by complexity, this groups all similar expression types together.
2979   GroupByComplexity(Ops, &LI, DT);
2980 
2981   // If there are any constants, fold them together.
2982   unsigned Idx = 0;
2983   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2984     ++Idx;
2985     assert(Idx < Ops.size());
2986     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2987       // We found two constants, fold them together!
2988       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2989       if (Ops.size() == 2) return Ops[0];
2990       Ops.erase(Ops.begin()+1);  // Erase the folded element
2991       LHSC = cast<SCEVConstant>(Ops[0]);
2992     }
2993 
2994     // If we have a multiply of zero, it will always be zero.
2995     if (LHSC->getValue()->isZero())
2996       return LHSC;
2997 
2998     // If we are left with a constant one being multiplied, strip it off.
2999     if (LHSC->getValue()->isOne()) {
3000       Ops.erase(Ops.begin());
3001       --Idx;
3002     }
3003 
3004     if (Ops.size() == 1)
3005       return Ops[0];
3006   }
3007 
3008   // Delay expensive flag strengthening until necessary.
3009   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3010     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3011   };
3012 
3013   // Limit recursion calls depth.
3014   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3015     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3016 
3017   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
3018     // Don't strengthen flags if we have no new information.
3019     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3020     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3021       Mul->setNoWrapFlags(ComputeFlags(Ops));
3022     return S;
3023   }
3024 
3025   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3026     if (Ops.size() == 2) {
3027       // C1*(C2+V) -> C1*C2 + C1*V
3028       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3029         // If any of Add's ops are Adds or Muls with a constant, apply this
3030         // transformation as well.
3031         //
3032         // TODO: There are some cases where this transformation is not
3033         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3034         // this transformation should be narrowed down.
3035         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
3036           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
3037                                        SCEV::FlagAnyWrap, Depth + 1),
3038                             getMulExpr(LHSC, Add->getOperand(1),
3039                                        SCEV::FlagAnyWrap, Depth + 1),
3040                             SCEV::FlagAnyWrap, Depth + 1);
3041 
3042       if (Ops[0]->isAllOnesValue()) {
3043         // If we have a mul by -1 of an add, try distributing the -1 among the
3044         // add operands.
3045         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3046           SmallVector<const SCEV *, 4> NewOps;
3047           bool AnyFolded = false;
3048           for (const SCEV *AddOp : Add->operands()) {
3049             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3050                                          Depth + 1);
3051             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3052             NewOps.push_back(Mul);
3053           }
3054           if (AnyFolded)
3055             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3056         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3057           // Negation preserves a recurrence's no self-wrap property.
3058           SmallVector<const SCEV *, 4> Operands;
3059           for (const SCEV *AddRecOp : AddRec->operands())
3060             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3061                                           Depth + 1));
3062 
3063           return getAddRecExpr(Operands, AddRec->getLoop(),
3064                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3065         }
3066       }
3067     }
3068   }
3069 
3070   // Skip over the add expression until we get to a multiply.
3071   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3072     ++Idx;
3073 
3074   // If there are mul operands inline them all into this expression.
3075   if (Idx < Ops.size()) {
3076     bool DeletedMul = false;
3077     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3078       if (Ops.size() > MulOpsInlineThreshold)
3079         break;
3080       // If we have an mul, expand the mul operands onto the end of the
3081       // operands list.
3082       Ops.erase(Ops.begin()+Idx);
3083       Ops.append(Mul->op_begin(), Mul->op_end());
3084       DeletedMul = true;
3085     }
3086 
3087     // If we deleted at least one mul, we added operands to the end of the
3088     // list, and they are not necessarily sorted.  Recurse to resort and
3089     // resimplify any operands we just acquired.
3090     if (DeletedMul)
3091       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3092   }
3093 
3094   // If there are any add recurrences in the operands list, see if any other
3095   // added values are loop invariant.  If so, we can fold them into the
3096   // recurrence.
3097   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3098     ++Idx;
3099 
3100   // Scan over all recurrences, trying to fold loop invariants into them.
3101   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3102     // Scan all of the other operands to this mul and add them to the vector
3103     // if they are loop invariant w.r.t. the recurrence.
3104     SmallVector<const SCEV *, 8> LIOps;
3105     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3106     const Loop *AddRecLoop = AddRec->getLoop();
3107     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3108       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3109         LIOps.push_back(Ops[i]);
3110         Ops.erase(Ops.begin()+i);
3111         --i; --e;
3112       }
3113 
3114     // If we found some loop invariants, fold them into the recurrence.
3115     if (!LIOps.empty()) {
3116       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3117       SmallVector<const SCEV *, 4> NewOps;
3118       NewOps.reserve(AddRec->getNumOperands());
3119       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3120       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3121         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3122                                     SCEV::FlagAnyWrap, Depth + 1));
3123 
3124       // Build the new addrec. Propagate the NUW and NSW flags if both the
3125       // outer mul and the inner addrec are guaranteed to have no overflow.
3126       //
3127       // No self-wrap cannot be guaranteed after changing the step size, but
3128       // will be inferred if either NUW or NSW is true.
3129       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3130       const SCEV *NewRec = getAddRecExpr(
3131           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3132 
3133       // If all of the other operands were loop invariant, we are done.
3134       if (Ops.size() == 1) return NewRec;
3135 
3136       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3137       for (unsigned i = 0;; ++i)
3138         if (Ops[i] == AddRec) {
3139           Ops[i] = NewRec;
3140           break;
3141         }
3142       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3143     }
3144 
3145     // Okay, if there weren't any loop invariants to be folded, check to see
3146     // if there are multiple AddRec's with the same loop induction variable
3147     // being multiplied together.  If so, we can fold them.
3148 
3149     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3150     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3151     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3152     //   ]]],+,...up to x=2n}.
3153     // Note that the arguments to choose() are always integers with values
3154     // known at compile time, never SCEV objects.
3155     //
3156     // The implementation avoids pointless extra computations when the two
3157     // addrec's are of different length (mathematically, it's equivalent to
3158     // an infinite stream of zeros on the right).
3159     bool OpsModified = false;
3160     for (unsigned OtherIdx = Idx+1;
3161          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3162          ++OtherIdx) {
3163       const SCEVAddRecExpr *OtherAddRec =
3164         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3165       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3166         continue;
3167 
3168       // Limit max number of arguments to avoid creation of unreasonably big
3169       // SCEVAddRecs with very complex operands.
3170       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3171           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3172         continue;
3173 
3174       bool Overflow = false;
3175       Type *Ty = AddRec->getType();
3176       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3177       SmallVector<const SCEV*, 7> AddRecOps;
3178       for (int x = 0, xe = AddRec->getNumOperands() +
3179              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3180         SmallVector <const SCEV *, 7> SumOps;
3181         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3182           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3183           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3184                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3185                z < ze && !Overflow; ++z) {
3186             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3187             uint64_t Coeff;
3188             if (LargerThan64Bits)
3189               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3190             else
3191               Coeff = Coeff1*Coeff2;
3192             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3193             const SCEV *Term1 = AddRec->getOperand(y-z);
3194             const SCEV *Term2 = OtherAddRec->getOperand(z);
3195             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3196                                         SCEV::FlagAnyWrap, Depth + 1));
3197           }
3198         }
3199         if (SumOps.empty())
3200           SumOps.push_back(getZero(Ty));
3201         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3202       }
3203       if (!Overflow) {
3204         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3205                                               SCEV::FlagAnyWrap);
3206         if (Ops.size() == 2) return NewAddRec;
3207         Ops[Idx] = NewAddRec;
3208         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3209         OpsModified = true;
3210         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3211         if (!AddRec)
3212           break;
3213       }
3214     }
3215     if (OpsModified)
3216       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3217 
3218     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3219     // next one.
3220   }
3221 
3222   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3223   // already have one, otherwise create a new one.
3224   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3225 }
3226 
3227 /// Represents an unsigned remainder expression based on unsigned division.
3228 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3229                                          const SCEV *RHS) {
3230   assert(getEffectiveSCEVType(LHS->getType()) ==
3231          getEffectiveSCEVType(RHS->getType()) &&
3232          "SCEVURemExpr operand types don't match!");
3233 
3234   // Short-circuit easy cases
3235   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3236     // If constant is one, the result is trivial
3237     if (RHSC->getValue()->isOne())
3238       return getZero(LHS->getType()); // X urem 1 --> 0
3239 
3240     // If constant is a power of two, fold into a zext(trunc(LHS)).
3241     if (RHSC->getAPInt().isPowerOf2()) {
3242       Type *FullTy = LHS->getType();
3243       Type *TruncTy =
3244           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3245       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3246     }
3247   }
3248 
3249   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3250   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3251   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3252   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3253 }
3254 
3255 /// Get a canonical unsigned division expression, or something simpler if
3256 /// possible.
3257 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3258                                          const SCEV *RHS) {
3259   assert(getEffectiveSCEVType(LHS->getType()) ==
3260          getEffectiveSCEVType(RHS->getType()) &&
3261          "SCEVUDivExpr operand types don't match!");
3262 
3263   FoldingSetNodeID ID;
3264   ID.AddInteger(scUDivExpr);
3265   ID.AddPointer(LHS);
3266   ID.AddPointer(RHS);
3267   void *IP = nullptr;
3268   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3269     return S;
3270 
3271   // 0 udiv Y == 0
3272   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3273     if (LHSC->getValue()->isZero())
3274       return LHS;
3275 
3276   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3277     if (RHSC->getValue()->isOne())
3278       return LHS;                               // X udiv 1 --> x
3279     // If the denominator is zero, the result of the udiv is undefined. Don't
3280     // try to analyze it, because the resolution chosen here may differ from
3281     // the resolution chosen in other parts of the compiler.
3282     if (!RHSC->getValue()->isZero()) {
3283       // Determine if the division can be folded into the operands of
3284       // its operands.
3285       // TODO: Generalize this to non-constants by using known-bits information.
3286       Type *Ty = LHS->getType();
3287       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3288       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3289       // For non-power-of-two values, effectively round the value up to the
3290       // nearest power of two.
3291       if (!RHSC->getAPInt().isPowerOf2())
3292         ++MaxShiftAmt;
3293       IntegerType *ExtTy =
3294         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3295       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3296         if (const SCEVConstant *Step =
3297             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3298           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3299           const APInt &StepInt = Step->getAPInt();
3300           const APInt &DivInt = RHSC->getAPInt();
3301           if (!StepInt.urem(DivInt) &&
3302               getZeroExtendExpr(AR, ExtTy) ==
3303               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3304                             getZeroExtendExpr(Step, ExtTy),
3305                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3306             SmallVector<const SCEV *, 4> Operands;
3307             for (const SCEV *Op : AR->operands())
3308               Operands.push_back(getUDivExpr(Op, RHS));
3309             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3310           }
3311           /// Get a canonical UDivExpr for a recurrence.
3312           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3313           // We can currently only fold X%N if X is constant.
3314           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3315           if (StartC && !DivInt.urem(StepInt) &&
3316               getZeroExtendExpr(AR, ExtTy) ==
3317               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3318                             getZeroExtendExpr(Step, ExtTy),
3319                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3320             const APInt &StartInt = StartC->getAPInt();
3321             const APInt &StartRem = StartInt.urem(StepInt);
3322             if (StartRem != 0) {
3323               const SCEV *NewLHS =
3324                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3325                                 AR->getLoop(), SCEV::FlagNW);
3326               if (LHS != NewLHS) {
3327                 LHS = NewLHS;
3328 
3329                 // Reset the ID to include the new LHS, and check if it is
3330                 // already cached.
3331                 ID.clear();
3332                 ID.AddInteger(scUDivExpr);
3333                 ID.AddPointer(LHS);
3334                 ID.AddPointer(RHS);
3335                 IP = nullptr;
3336                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3337                   return S;
3338               }
3339             }
3340           }
3341         }
3342       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3343       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3344         SmallVector<const SCEV *, 4> Operands;
3345         for (const SCEV *Op : M->operands())
3346           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3347         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3348           // Find an operand that's safely divisible.
3349           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3350             const SCEV *Op = M->getOperand(i);
3351             const SCEV *Div = getUDivExpr(Op, RHSC);
3352             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3353               Operands = SmallVector<const SCEV *, 4>(M->operands());
3354               Operands[i] = Div;
3355               return getMulExpr(Operands);
3356             }
3357           }
3358       }
3359 
3360       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3361       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3362         if (auto *DivisorConstant =
3363                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3364           bool Overflow = false;
3365           APInt NewRHS =
3366               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3367           if (Overflow) {
3368             return getConstant(RHSC->getType(), 0, false);
3369           }
3370           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3371         }
3372       }
3373 
3374       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3375       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3376         SmallVector<const SCEV *, 4> Operands;
3377         for (const SCEV *Op : A->operands())
3378           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3379         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3380           Operands.clear();
3381           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3382             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3383             if (isa<SCEVUDivExpr>(Op) ||
3384                 getMulExpr(Op, RHS) != A->getOperand(i))
3385               break;
3386             Operands.push_back(Op);
3387           }
3388           if (Operands.size() == A->getNumOperands())
3389             return getAddExpr(Operands);
3390         }
3391       }
3392 
3393       // Fold if both operands are constant.
3394       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3395         Constant *LHSCV = LHSC->getValue();
3396         Constant *RHSCV = RHSC->getValue();
3397         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3398                                                                    RHSCV)));
3399       }
3400     }
3401   }
3402 
3403   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3404   // changes). Make sure we get a new one.
3405   IP = nullptr;
3406   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3407   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3408                                              LHS, RHS);
3409   UniqueSCEVs.InsertNode(S, IP);
3410   addToLoopUseLists(S);
3411   return S;
3412 }
3413 
3414 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3415   APInt A = C1->getAPInt().abs();
3416   APInt B = C2->getAPInt().abs();
3417   uint32_t ABW = A.getBitWidth();
3418   uint32_t BBW = B.getBitWidth();
3419 
3420   if (ABW > BBW)
3421     B = B.zext(ABW);
3422   else if (ABW < BBW)
3423     A = A.zext(BBW);
3424 
3425   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3426 }
3427 
3428 /// Get a canonical unsigned division expression, or something simpler if
3429 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3430 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3431 /// it's not exact because the udiv may be clearing bits.
3432 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3433                                               const SCEV *RHS) {
3434   // TODO: we could try to find factors in all sorts of things, but for now we
3435   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3436   // end of this file for inspiration.
3437 
3438   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3439   if (!Mul || !Mul->hasNoUnsignedWrap())
3440     return getUDivExpr(LHS, RHS);
3441 
3442   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3443     // If the mulexpr multiplies by a constant, then that constant must be the
3444     // first element of the mulexpr.
3445     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3446       if (LHSCst == RHSCst) {
3447         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3448         return getMulExpr(Operands);
3449       }
3450 
3451       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3452       // that there's a factor provided by one of the other terms. We need to
3453       // check.
3454       APInt Factor = gcd(LHSCst, RHSCst);
3455       if (!Factor.isIntN(1)) {
3456         LHSCst =
3457             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3458         RHSCst =
3459             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3460         SmallVector<const SCEV *, 2> Operands;
3461         Operands.push_back(LHSCst);
3462         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3463         LHS = getMulExpr(Operands);
3464         RHS = RHSCst;
3465         Mul = dyn_cast<SCEVMulExpr>(LHS);
3466         if (!Mul)
3467           return getUDivExactExpr(LHS, RHS);
3468       }
3469     }
3470   }
3471 
3472   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3473     if (Mul->getOperand(i) == RHS) {
3474       SmallVector<const SCEV *, 2> Operands;
3475       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3476       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3477       return getMulExpr(Operands);
3478     }
3479   }
3480 
3481   return getUDivExpr(LHS, RHS);
3482 }
3483 
3484 /// Get an add recurrence expression for the specified loop.  Simplify the
3485 /// expression as much as possible.
3486 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3487                                            const Loop *L,
3488                                            SCEV::NoWrapFlags Flags) {
3489   SmallVector<const SCEV *, 4> Operands;
3490   Operands.push_back(Start);
3491   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3492     if (StepChrec->getLoop() == L) {
3493       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3494       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3495     }
3496 
3497   Operands.push_back(Step);
3498   return getAddRecExpr(Operands, L, Flags);
3499 }
3500 
3501 /// Get an add recurrence expression for the specified loop.  Simplify the
3502 /// expression as much as possible.
3503 const SCEV *
3504 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3505                                const Loop *L, SCEV::NoWrapFlags Flags) {
3506   if (Operands.size() == 1) return Operands[0];
3507 #ifndef NDEBUG
3508   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3509   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3510     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3511            "SCEVAddRecExpr operand types don't match!");
3512   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3513     assert(isLoopInvariant(Operands[i], L) &&
3514            "SCEVAddRecExpr operand is not loop-invariant!");
3515 #endif
3516 
3517   if (Operands.back()->isZero()) {
3518     Operands.pop_back();
3519     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3520   }
3521 
3522   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3523   // use that information to infer NUW and NSW flags. However, computing a
3524   // BE count requires calling getAddRecExpr, so we may not yet have a
3525   // meaningful BE count at this point (and if we don't, we'd be stuck
3526   // with a SCEVCouldNotCompute as the cached BE count).
3527 
3528   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3529 
3530   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3531   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3532     const Loop *NestedLoop = NestedAR->getLoop();
3533     if (L->contains(NestedLoop)
3534             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3535             : (!NestedLoop->contains(L) &&
3536                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3537       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3538       Operands[0] = NestedAR->getStart();
3539       // AddRecs require their operands be loop-invariant with respect to their
3540       // loops. Don't perform this transformation if it would break this
3541       // requirement.
3542       bool AllInvariant = all_of(
3543           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3544 
3545       if (AllInvariant) {
3546         // Create a recurrence for the outer loop with the same step size.
3547         //
3548         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3549         // inner recurrence has the same property.
3550         SCEV::NoWrapFlags OuterFlags =
3551           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3552 
3553         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3554         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3555           return isLoopInvariant(Op, NestedLoop);
3556         });
3557 
3558         if (AllInvariant) {
3559           // Ok, both add recurrences are valid after the transformation.
3560           //
3561           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3562           // the outer recurrence has the same property.
3563           SCEV::NoWrapFlags InnerFlags =
3564             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3565           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3566         }
3567       }
3568       // Reset Operands to its original state.
3569       Operands[0] = NestedAR;
3570     }
3571   }
3572 
3573   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3574   // already have one, otherwise create a new one.
3575   return getOrCreateAddRecExpr(Operands, L, Flags);
3576 }
3577 
3578 const SCEV *
3579 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3580                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3581   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3582   // getSCEV(Base)->getType() has the same address space as Base->getType()
3583   // because SCEV::getType() preserves the address space.
3584   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3585   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3586   // instruction to its SCEV, because the Instruction may be guarded by control
3587   // flow and the no-overflow bits may not be valid for the expression in any
3588   // context. This can be fixed similarly to how these flags are handled for
3589   // adds.
3590   SCEV::NoWrapFlags OffsetWrap =
3591       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3592 
3593   Type *CurTy = GEP->getType();
3594   bool FirstIter = true;
3595   SmallVector<const SCEV *, 4> Offsets;
3596   for (const SCEV *IndexExpr : IndexExprs) {
3597     // Compute the (potentially symbolic) offset in bytes for this index.
3598     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3599       // For a struct, add the member offset.
3600       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3601       unsigned FieldNo = Index->getZExtValue();
3602       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3603       Offsets.push_back(FieldOffset);
3604 
3605       // Update CurTy to the type of the field at Index.
3606       CurTy = STy->getTypeAtIndex(Index);
3607     } else {
3608       // Update CurTy to its element type.
3609       if (FirstIter) {
3610         assert(isa<PointerType>(CurTy) &&
3611                "The first index of a GEP indexes a pointer");
3612         CurTy = GEP->getSourceElementType();
3613         FirstIter = false;
3614       } else {
3615         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3616       }
3617       // For an array, add the element offset, explicitly scaled.
3618       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3619       // Getelementptr indices are signed.
3620       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3621 
3622       // Multiply the index by the element size to compute the element offset.
3623       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3624       Offsets.push_back(LocalOffset);
3625     }
3626   }
3627 
3628   // Handle degenerate case of GEP without offsets.
3629   if (Offsets.empty())
3630     return BaseExpr;
3631 
3632   // Add the offsets together, assuming nsw if inbounds.
3633   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3634   // Add the base address and the offset. We cannot use the nsw flag, as the
3635   // base address is unsigned. However, if we know that the offset is
3636   // non-negative, we can use nuw.
3637   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3638                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3639   return getAddExpr(BaseExpr, Offset, BaseWrap);
3640 }
3641 
3642 std::tuple<SCEV *, FoldingSetNodeID, void *>
3643 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3644                                          ArrayRef<const SCEV *> Ops) {
3645   FoldingSetNodeID ID;
3646   void *IP = nullptr;
3647   ID.AddInteger(SCEVType);
3648   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3649     ID.AddPointer(Ops[i]);
3650   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3651       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3652 }
3653 
3654 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3655   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3656   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3657 }
3658 
3659 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3660                                            SmallVectorImpl<const SCEV *> &Ops) {
3661   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3662   if (Ops.size() == 1) return Ops[0];
3663 #ifndef NDEBUG
3664   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3665   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3666     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3667            "Operand types don't match!");
3668 #endif
3669 
3670   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3671   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3672 
3673   // Sort by complexity, this groups all similar expression types together.
3674   GroupByComplexity(Ops, &LI, DT);
3675 
3676   // Check if we have created the same expression before.
3677   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3678     return S;
3679   }
3680 
3681   // If there are any constants, fold them together.
3682   unsigned Idx = 0;
3683   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3684     ++Idx;
3685     assert(Idx < Ops.size());
3686     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3687       if (Kind == scSMaxExpr)
3688         return APIntOps::smax(LHS, RHS);
3689       else if (Kind == scSMinExpr)
3690         return APIntOps::smin(LHS, RHS);
3691       else if (Kind == scUMaxExpr)
3692         return APIntOps::umax(LHS, RHS);
3693       else if (Kind == scUMinExpr)
3694         return APIntOps::umin(LHS, RHS);
3695       llvm_unreachable("Unknown SCEV min/max opcode");
3696     };
3697 
3698     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3699       // We found two constants, fold them together!
3700       ConstantInt *Fold = ConstantInt::get(
3701           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3702       Ops[0] = getConstant(Fold);
3703       Ops.erase(Ops.begin()+1);  // Erase the folded element
3704       if (Ops.size() == 1) return Ops[0];
3705       LHSC = cast<SCEVConstant>(Ops[0]);
3706     }
3707 
3708     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3709     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3710 
3711     if (IsMax ? IsMinV : IsMaxV) {
3712       // If we are left with a constant minimum(/maximum)-int, strip it off.
3713       Ops.erase(Ops.begin());
3714       --Idx;
3715     } else if (IsMax ? IsMaxV : IsMinV) {
3716       // If we have a max(/min) with a constant maximum(/minimum)-int,
3717       // it will always be the extremum.
3718       return LHSC;
3719     }
3720 
3721     if (Ops.size() == 1) return Ops[0];
3722   }
3723 
3724   // Find the first operation of the same kind
3725   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3726     ++Idx;
3727 
3728   // Check to see if one of the operands is of the same kind. If so, expand its
3729   // operands onto our operand list, and recurse to simplify.
3730   if (Idx < Ops.size()) {
3731     bool DeletedAny = false;
3732     while (Ops[Idx]->getSCEVType() == Kind) {
3733       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3734       Ops.erase(Ops.begin()+Idx);
3735       Ops.append(SMME->op_begin(), SMME->op_end());
3736       DeletedAny = true;
3737     }
3738 
3739     if (DeletedAny)
3740       return getMinMaxExpr(Kind, Ops);
3741   }
3742 
3743   // Okay, check to see if the same value occurs in the operand list twice.  If
3744   // so, delete one.  Since we sorted the list, these values are required to
3745   // be adjacent.
3746   llvm::CmpInst::Predicate GEPred =
3747       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3748   llvm::CmpInst::Predicate LEPred =
3749       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3750   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3751   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3752   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3753     if (Ops[i] == Ops[i + 1] ||
3754         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3755       //  X op Y op Y  -->  X op Y
3756       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3757       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3758       --i;
3759       --e;
3760     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3761                                                Ops[i + 1])) {
3762       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3763       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3764       --i;
3765       --e;
3766     }
3767   }
3768 
3769   if (Ops.size() == 1) return Ops[0];
3770 
3771   assert(!Ops.empty() && "Reduced smax down to nothing!");
3772 
3773   // Okay, it looks like we really DO need an expr.  Check to see if we
3774   // already have one, otherwise create a new one.
3775   const SCEV *ExistingSCEV;
3776   FoldingSetNodeID ID;
3777   void *IP;
3778   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3779   if (ExistingSCEV)
3780     return ExistingSCEV;
3781   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3782   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3783   SCEV *S = new (SCEVAllocator)
3784       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3785 
3786   UniqueSCEVs.InsertNode(S, IP);
3787   addToLoopUseLists(S);
3788   return S;
3789 }
3790 
3791 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3792   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3793   return getSMaxExpr(Ops);
3794 }
3795 
3796 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3797   return getMinMaxExpr(scSMaxExpr, Ops);
3798 }
3799 
3800 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3801   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3802   return getUMaxExpr(Ops);
3803 }
3804 
3805 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3806   return getMinMaxExpr(scUMaxExpr, Ops);
3807 }
3808 
3809 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3810                                          const SCEV *RHS) {
3811   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3812   return getSMinExpr(Ops);
3813 }
3814 
3815 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3816   return getMinMaxExpr(scSMinExpr, Ops);
3817 }
3818 
3819 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3820                                          const SCEV *RHS) {
3821   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3822   return getUMinExpr(Ops);
3823 }
3824 
3825 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3826   return getMinMaxExpr(scUMinExpr, Ops);
3827 }
3828 
3829 const SCEV *
3830 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3831                                              ScalableVectorType *ScalableTy) {
3832   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3833   Constant *One = ConstantInt::get(IntTy, 1);
3834   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3835   // Note that the expression we created is the final expression, we don't
3836   // want to simplify it any further Also, if we call a normal getSCEV(),
3837   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3838   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3839 }
3840 
3841 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3842   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3843     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3844   // We can bypass creating a target-independent constant expression and then
3845   // folding it back into a ConstantInt. This is just a compile-time
3846   // optimization.
3847   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3848 }
3849 
3850 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3851   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3852     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3853   // We can bypass creating a target-independent constant expression and then
3854   // folding it back into a ConstantInt. This is just a compile-time
3855   // optimization.
3856   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3857 }
3858 
3859 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3860                                              StructType *STy,
3861                                              unsigned FieldNo) {
3862   // We can bypass creating a target-independent constant expression and then
3863   // folding it back into a ConstantInt. This is just a compile-time
3864   // optimization.
3865   return getConstant(
3866       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3867 }
3868 
3869 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3870   // Don't attempt to do anything other than create a SCEVUnknown object
3871   // here.  createSCEV only calls getUnknown after checking for all other
3872   // interesting possibilities, and any other code that calls getUnknown
3873   // is doing so in order to hide a value from SCEV canonicalization.
3874 
3875   FoldingSetNodeID ID;
3876   ID.AddInteger(scUnknown);
3877   ID.AddPointer(V);
3878   void *IP = nullptr;
3879   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3880     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3881            "Stale SCEVUnknown in uniquing map!");
3882     return S;
3883   }
3884   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3885                                             FirstUnknown);
3886   FirstUnknown = cast<SCEVUnknown>(S);
3887   UniqueSCEVs.InsertNode(S, IP);
3888   return S;
3889 }
3890 
3891 //===----------------------------------------------------------------------===//
3892 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3893 //
3894 
3895 /// Test if values of the given type are analyzable within the SCEV
3896 /// framework. This primarily includes integer types, and it can optionally
3897 /// include pointer types if the ScalarEvolution class has access to
3898 /// target-specific information.
3899 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3900   // Integers and pointers are always SCEVable.
3901   return Ty->isIntOrPtrTy();
3902 }
3903 
3904 /// Return the size in bits of the specified type, for which isSCEVable must
3905 /// return true.
3906 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3907   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3908   if (Ty->isPointerTy())
3909     return getDataLayout().getIndexTypeSizeInBits(Ty);
3910   return getDataLayout().getTypeSizeInBits(Ty);
3911 }
3912 
3913 /// Return a type with the same bitwidth as the given type and which represents
3914 /// how SCEV will treat the given type, for which isSCEVable must return
3915 /// true. For pointer types, this is the pointer index sized integer type.
3916 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3917   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3918 
3919   if (Ty->isIntegerTy())
3920     return Ty;
3921 
3922   // The only other support type is pointer.
3923   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3924   return getDataLayout().getIndexType(Ty);
3925 }
3926 
3927 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3928   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3929 }
3930 
3931 const SCEV *ScalarEvolution::getCouldNotCompute() {
3932   return CouldNotCompute.get();
3933 }
3934 
3935 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3936   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3937     auto *SU = dyn_cast<SCEVUnknown>(S);
3938     return SU && SU->getValue() == nullptr;
3939   });
3940 
3941   return !ContainsNulls;
3942 }
3943 
3944 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3945   HasRecMapType::iterator I = HasRecMap.find(S);
3946   if (I != HasRecMap.end())
3947     return I->second;
3948 
3949   bool FoundAddRec =
3950       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3951   HasRecMap.insert({S, FoundAddRec});
3952   return FoundAddRec;
3953 }
3954 
3955 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3956 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3957 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3958 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3959   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3960   if (!Add)
3961     return {S, nullptr};
3962 
3963   if (Add->getNumOperands() != 2)
3964     return {S, nullptr};
3965 
3966   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3967   if (!ConstOp)
3968     return {S, nullptr};
3969 
3970   return {Add->getOperand(1), ConstOp->getValue()};
3971 }
3972 
3973 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3974 /// by the value and offset from any ValueOffsetPair in the set.
3975 ScalarEvolution::ValueOffsetPairSetVector *
3976 ScalarEvolution::getSCEVValues(const SCEV *S) {
3977   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3978   if (SI == ExprValueMap.end())
3979     return nullptr;
3980 #ifndef NDEBUG
3981   if (VerifySCEVMap) {
3982     // Check there is no dangling Value in the set returned.
3983     for (const auto &VE : SI->second)
3984       assert(ValueExprMap.count(VE.first));
3985   }
3986 #endif
3987   return &SI->second;
3988 }
3989 
3990 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3991 /// cannot be used separately. eraseValueFromMap should be used to remove
3992 /// V from ValueExprMap and ExprValueMap at the same time.
3993 void ScalarEvolution::eraseValueFromMap(Value *V) {
3994   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3995   if (I != ValueExprMap.end()) {
3996     const SCEV *S = I->second;
3997     // Remove {V, 0} from the set of ExprValueMap[S]
3998     if (auto *SV = getSCEVValues(S))
3999       SV->remove({V, nullptr});
4000 
4001     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
4002     const SCEV *Stripped;
4003     ConstantInt *Offset;
4004     std::tie(Stripped, Offset) = splitAddExpr(S);
4005     if (Offset != nullptr) {
4006       if (auto *SV = getSCEVValues(Stripped))
4007         SV->remove({V, Offset});
4008     }
4009     ValueExprMap.erase(V);
4010   }
4011 }
4012 
4013 /// Check whether value has nuw/nsw/exact set but SCEV does not.
4014 /// TODO: In reality it is better to check the poison recursively
4015 /// but this is better than nothing.
4016 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
4017   if (auto *I = dyn_cast<Instruction>(V)) {
4018     if (isa<OverflowingBinaryOperator>(I)) {
4019       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
4020         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
4021           return true;
4022         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
4023           return true;
4024       }
4025     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
4026       return true;
4027   }
4028   return false;
4029 }
4030 
4031 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4032 /// create a new one.
4033 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4034   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4035 
4036   const SCEV *S = getExistingSCEV(V);
4037   if (S == nullptr) {
4038     S = createSCEV(V);
4039     // During PHI resolution, it is possible to create two SCEVs for the same
4040     // V, so it is needed to double check whether V->S is inserted into
4041     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4042     std::pair<ValueExprMapType::iterator, bool> Pair =
4043         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4044     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
4045       ExprValueMap[S].insert({V, nullptr});
4046 
4047       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
4048       // ExprValueMap.
4049       const SCEV *Stripped = S;
4050       ConstantInt *Offset = nullptr;
4051       std::tie(Stripped, Offset) = splitAddExpr(S);
4052       // If stripped is SCEVUnknown, don't bother to save
4053       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
4054       // increase the complexity of the expansion code.
4055       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
4056       // because it may generate add/sub instead of GEP in SCEV expansion.
4057       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
4058           !isa<GetElementPtrInst>(V))
4059         ExprValueMap[Stripped].insert({V, Offset});
4060     }
4061   }
4062   return S;
4063 }
4064 
4065 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4066   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4067 
4068   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4069   if (I != ValueExprMap.end()) {
4070     const SCEV *S = I->second;
4071     if (checkValidity(S))
4072       return S;
4073     eraseValueFromMap(V);
4074     forgetMemoizedResults(S);
4075   }
4076   return nullptr;
4077 }
4078 
4079 /// Return a SCEV corresponding to -V = -1*V
4080 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4081                                              SCEV::NoWrapFlags Flags) {
4082   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4083     return getConstant(
4084                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4085 
4086   Type *Ty = V->getType();
4087   Ty = getEffectiveSCEVType(Ty);
4088   return getMulExpr(V, getMinusOne(Ty), Flags);
4089 }
4090 
4091 /// If Expr computes ~A, return A else return nullptr
4092 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4093   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4094   if (!Add || Add->getNumOperands() != 2 ||
4095       !Add->getOperand(0)->isAllOnesValue())
4096     return nullptr;
4097 
4098   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4099   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4100       !AddRHS->getOperand(0)->isAllOnesValue())
4101     return nullptr;
4102 
4103   return AddRHS->getOperand(1);
4104 }
4105 
4106 /// Return a SCEV corresponding to ~V = -1-V
4107 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4108   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4109     return getConstant(
4110                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4111 
4112   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4113   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4114     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4115       SmallVector<const SCEV *, 2> MatchedOperands;
4116       for (const SCEV *Operand : MME->operands()) {
4117         const SCEV *Matched = MatchNotExpr(Operand);
4118         if (!Matched)
4119           return (const SCEV *)nullptr;
4120         MatchedOperands.push_back(Matched);
4121       }
4122       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4123                            MatchedOperands);
4124     };
4125     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4126       return Replaced;
4127   }
4128 
4129   Type *Ty = V->getType();
4130   Ty = getEffectiveSCEVType(Ty);
4131   return getMinusSCEV(getMinusOne(Ty), V);
4132 }
4133 
4134 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4135                                           SCEV::NoWrapFlags Flags,
4136                                           unsigned Depth) {
4137   // Fast path: X - X --> 0.
4138   if (LHS == RHS)
4139     return getZero(LHS->getType());
4140 
4141   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4142   // makes it so that we cannot make much use of NUW.
4143   auto AddFlags = SCEV::FlagAnyWrap;
4144   const bool RHSIsNotMinSigned =
4145       !getSignedRangeMin(RHS).isMinSignedValue();
4146   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4147     // Let M be the minimum representable signed value. Then (-1)*RHS
4148     // signed-wraps if and only if RHS is M. That can happen even for
4149     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4150     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4151     // (-1)*RHS, we need to prove that RHS != M.
4152     //
4153     // If LHS is non-negative and we know that LHS - RHS does not
4154     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4155     // either by proving that RHS > M or that LHS >= 0.
4156     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4157       AddFlags = SCEV::FlagNSW;
4158     }
4159   }
4160 
4161   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4162   // RHS is NSW and LHS >= 0.
4163   //
4164   // The difficulty here is that the NSW flag may have been proven
4165   // relative to a loop that is to be found in a recurrence in LHS and
4166   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4167   // larger scope than intended.
4168   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4169 
4170   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4171 }
4172 
4173 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4174                                                      unsigned Depth) {
4175   Type *SrcTy = V->getType();
4176   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4177          "Cannot truncate or zero extend with non-integer arguments!");
4178   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4179     return V;  // No conversion
4180   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4181     return getTruncateExpr(V, Ty, Depth);
4182   return getZeroExtendExpr(V, Ty, Depth);
4183 }
4184 
4185 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4186                                                      unsigned Depth) {
4187   Type *SrcTy = V->getType();
4188   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4189          "Cannot truncate or zero extend with non-integer arguments!");
4190   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4191     return V;  // No conversion
4192   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4193     return getTruncateExpr(V, Ty, Depth);
4194   return getSignExtendExpr(V, Ty, Depth);
4195 }
4196 
4197 const SCEV *
4198 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4199   Type *SrcTy = V->getType();
4200   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4201          "Cannot noop or zero extend with non-integer arguments!");
4202   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4203          "getNoopOrZeroExtend cannot truncate!");
4204   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4205     return V;  // No conversion
4206   return getZeroExtendExpr(V, Ty);
4207 }
4208 
4209 const SCEV *
4210 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4211   Type *SrcTy = V->getType();
4212   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4213          "Cannot noop or sign extend with non-integer arguments!");
4214   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4215          "getNoopOrSignExtend cannot truncate!");
4216   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4217     return V;  // No conversion
4218   return getSignExtendExpr(V, Ty);
4219 }
4220 
4221 const SCEV *
4222 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4223   Type *SrcTy = V->getType();
4224   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4225          "Cannot noop or any extend with non-integer arguments!");
4226   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4227          "getNoopOrAnyExtend cannot truncate!");
4228   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4229     return V;  // No conversion
4230   return getAnyExtendExpr(V, Ty);
4231 }
4232 
4233 const SCEV *
4234 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4235   Type *SrcTy = V->getType();
4236   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4237          "Cannot truncate or noop with non-integer arguments!");
4238   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4239          "getTruncateOrNoop cannot extend!");
4240   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4241     return V;  // No conversion
4242   return getTruncateExpr(V, Ty);
4243 }
4244 
4245 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4246                                                         const SCEV *RHS) {
4247   const SCEV *PromotedLHS = LHS;
4248   const SCEV *PromotedRHS = RHS;
4249 
4250   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4251     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4252   else
4253     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4254 
4255   return getUMaxExpr(PromotedLHS, PromotedRHS);
4256 }
4257 
4258 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4259                                                         const SCEV *RHS) {
4260   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4261   return getUMinFromMismatchedTypes(Ops);
4262 }
4263 
4264 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4265     SmallVectorImpl<const SCEV *> &Ops) {
4266   assert(!Ops.empty() && "At least one operand must be!");
4267   // Trivial case.
4268   if (Ops.size() == 1)
4269     return Ops[0];
4270 
4271   // Find the max type first.
4272   Type *MaxType = nullptr;
4273   for (auto *S : Ops)
4274     if (MaxType)
4275       MaxType = getWiderType(MaxType, S->getType());
4276     else
4277       MaxType = S->getType();
4278   assert(MaxType && "Failed to find maximum type!");
4279 
4280   // Extend all ops to max type.
4281   SmallVector<const SCEV *, 2> PromotedOps;
4282   for (auto *S : Ops)
4283     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4284 
4285   // Generate umin.
4286   return getUMinExpr(PromotedOps);
4287 }
4288 
4289 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4290   // A pointer operand may evaluate to a nonpointer expression, such as null.
4291   if (!V->getType()->isPointerTy())
4292     return V;
4293 
4294   while (true) {
4295     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4296       V = AddRec->getStart();
4297     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4298       const SCEV *PtrOp = nullptr;
4299       for (const SCEV *AddOp : Add->operands()) {
4300         if (AddOp->getType()->isPointerTy()) {
4301           // Cannot find the base of an expression with multiple pointer ops.
4302           if (PtrOp)
4303             return V;
4304           PtrOp = AddOp;
4305         }
4306       }
4307       if (!PtrOp) // All operands were non-pointer.
4308         return V;
4309       V = PtrOp;
4310     } else // Not something we can look further into.
4311       return V;
4312   }
4313 }
4314 
4315 /// Push users of the given Instruction onto the given Worklist.
4316 static void
4317 PushDefUseChildren(Instruction *I,
4318                    SmallVectorImpl<Instruction *> &Worklist) {
4319   // Push the def-use children onto the Worklist stack.
4320   for (User *U : I->users())
4321     Worklist.push_back(cast<Instruction>(U));
4322 }
4323 
4324 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4325   SmallVector<Instruction *, 16> Worklist;
4326   PushDefUseChildren(PN, Worklist);
4327 
4328   SmallPtrSet<Instruction *, 8> Visited;
4329   Visited.insert(PN);
4330   while (!Worklist.empty()) {
4331     Instruction *I = Worklist.pop_back_val();
4332     if (!Visited.insert(I).second)
4333       continue;
4334 
4335     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4336     if (It != ValueExprMap.end()) {
4337       const SCEV *Old = It->second;
4338 
4339       // Short-circuit the def-use traversal if the symbolic name
4340       // ceases to appear in expressions.
4341       if (Old != SymName && !hasOperand(Old, SymName))
4342         continue;
4343 
4344       // SCEVUnknown for a PHI either means that it has an unrecognized
4345       // structure, it's a PHI that's in the progress of being computed
4346       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4347       // additional loop trip count information isn't going to change anything.
4348       // In the second case, createNodeForPHI will perform the necessary
4349       // updates on its own when it gets to that point. In the third, we do
4350       // want to forget the SCEVUnknown.
4351       if (!isa<PHINode>(I) ||
4352           !isa<SCEVUnknown>(Old) ||
4353           (I != PN && Old == SymName)) {
4354         eraseValueFromMap(It->first);
4355         forgetMemoizedResults(Old);
4356       }
4357     }
4358 
4359     PushDefUseChildren(I, Worklist);
4360   }
4361 }
4362 
4363 namespace {
4364 
4365 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4366 /// expression in case its Loop is L. If it is not L then
4367 /// if IgnoreOtherLoops is true then use AddRec itself
4368 /// otherwise rewrite cannot be done.
4369 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4370 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4371 public:
4372   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4373                              bool IgnoreOtherLoops = true) {
4374     SCEVInitRewriter Rewriter(L, SE);
4375     const SCEV *Result = Rewriter.visit(S);
4376     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4377       return SE.getCouldNotCompute();
4378     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4379                ? SE.getCouldNotCompute()
4380                : Result;
4381   }
4382 
4383   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4384     if (!SE.isLoopInvariant(Expr, L))
4385       SeenLoopVariantSCEVUnknown = true;
4386     return Expr;
4387   }
4388 
4389   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4390     // Only re-write AddRecExprs for this loop.
4391     if (Expr->getLoop() == L)
4392       return Expr->getStart();
4393     SeenOtherLoops = true;
4394     return Expr;
4395   }
4396 
4397   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4398 
4399   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4400 
4401 private:
4402   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4403       : SCEVRewriteVisitor(SE), L(L) {}
4404 
4405   const Loop *L;
4406   bool SeenLoopVariantSCEVUnknown = false;
4407   bool SeenOtherLoops = false;
4408 };
4409 
4410 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4411 /// increment expression in case its Loop is L. If it is not L then
4412 /// use AddRec itself.
4413 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4414 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4415 public:
4416   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4417     SCEVPostIncRewriter Rewriter(L, SE);
4418     const SCEV *Result = Rewriter.visit(S);
4419     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4420         ? SE.getCouldNotCompute()
4421         : Result;
4422   }
4423 
4424   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4425     if (!SE.isLoopInvariant(Expr, L))
4426       SeenLoopVariantSCEVUnknown = true;
4427     return Expr;
4428   }
4429 
4430   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4431     // Only re-write AddRecExprs for this loop.
4432     if (Expr->getLoop() == L)
4433       return Expr->getPostIncExpr(SE);
4434     SeenOtherLoops = true;
4435     return Expr;
4436   }
4437 
4438   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4439 
4440   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4441 
4442 private:
4443   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4444       : SCEVRewriteVisitor(SE), L(L) {}
4445 
4446   const Loop *L;
4447   bool SeenLoopVariantSCEVUnknown = false;
4448   bool SeenOtherLoops = false;
4449 };
4450 
4451 /// This class evaluates the compare condition by matching it against the
4452 /// condition of loop latch. If there is a match we assume a true value
4453 /// for the condition while building SCEV nodes.
4454 class SCEVBackedgeConditionFolder
4455     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4456 public:
4457   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4458                              ScalarEvolution &SE) {
4459     bool IsPosBECond = false;
4460     Value *BECond = nullptr;
4461     if (BasicBlock *Latch = L->getLoopLatch()) {
4462       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4463       if (BI && BI->isConditional()) {
4464         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4465                "Both outgoing branches should not target same header!");
4466         BECond = BI->getCondition();
4467         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4468       } else {
4469         return S;
4470       }
4471     }
4472     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4473     return Rewriter.visit(S);
4474   }
4475 
4476   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4477     const SCEV *Result = Expr;
4478     bool InvariantF = SE.isLoopInvariant(Expr, L);
4479 
4480     if (!InvariantF) {
4481       Instruction *I = cast<Instruction>(Expr->getValue());
4482       switch (I->getOpcode()) {
4483       case Instruction::Select: {
4484         SelectInst *SI = cast<SelectInst>(I);
4485         Optional<const SCEV *> Res =
4486             compareWithBackedgeCondition(SI->getCondition());
4487         if (Res.hasValue()) {
4488           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4489           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4490         }
4491         break;
4492       }
4493       default: {
4494         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4495         if (Res.hasValue())
4496           Result = Res.getValue();
4497         break;
4498       }
4499       }
4500     }
4501     return Result;
4502   }
4503 
4504 private:
4505   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4506                                        bool IsPosBECond, ScalarEvolution &SE)
4507       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4508         IsPositiveBECond(IsPosBECond) {}
4509 
4510   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4511 
4512   const Loop *L;
4513   /// Loop back condition.
4514   Value *BackedgeCond = nullptr;
4515   /// Set to true if loop back is on positive branch condition.
4516   bool IsPositiveBECond;
4517 };
4518 
4519 Optional<const SCEV *>
4520 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4521 
4522   // If value matches the backedge condition for loop latch,
4523   // then return a constant evolution node based on loopback
4524   // branch taken.
4525   if (BackedgeCond == IC)
4526     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4527                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4528   return None;
4529 }
4530 
4531 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4532 public:
4533   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4534                              ScalarEvolution &SE) {
4535     SCEVShiftRewriter Rewriter(L, SE);
4536     const SCEV *Result = Rewriter.visit(S);
4537     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4538   }
4539 
4540   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4541     // Only allow AddRecExprs for this loop.
4542     if (!SE.isLoopInvariant(Expr, L))
4543       Valid = false;
4544     return Expr;
4545   }
4546 
4547   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4548     if (Expr->getLoop() == L && Expr->isAffine())
4549       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4550     Valid = false;
4551     return Expr;
4552   }
4553 
4554   bool isValid() { return Valid; }
4555 
4556 private:
4557   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4558       : SCEVRewriteVisitor(SE), L(L) {}
4559 
4560   const Loop *L;
4561   bool Valid = true;
4562 };
4563 
4564 } // end anonymous namespace
4565 
4566 SCEV::NoWrapFlags
4567 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4568   if (!AR->isAffine())
4569     return SCEV::FlagAnyWrap;
4570 
4571   using OBO = OverflowingBinaryOperator;
4572 
4573   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4574 
4575   if (!AR->hasNoSignedWrap()) {
4576     ConstantRange AddRecRange = getSignedRange(AR);
4577     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4578 
4579     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4580         Instruction::Add, IncRange, OBO::NoSignedWrap);
4581     if (NSWRegion.contains(AddRecRange))
4582       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4583   }
4584 
4585   if (!AR->hasNoUnsignedWrap()) {
4586     ConstantRange AddRecRange = getUnsignedRange(AR);
4587     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4588 
4589     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4590         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4591     if (NUWRegion.contains(AddRecRange))
4592       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4593   }
4594 
4595   return Result;
4596 }
4597 
4598 SCEV::NoWrapFlags
4599 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4600   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4601 
4602   if (AR->hasNoSignedWrap())
4603     return Result;
4604 
4605   if (!AR->isAffine())
4606     return Result;
4607 
4608   const SCEV *Step = AR->getStepRecurrence(*this);
4609   const Loop *L = AR->getLoop();
4610 
4611   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4612   // Note that this serves two purposes: It filters out loops that are
4613   // simply not analyzable, and it covers the case where this code is
4614   // being called from within backedge-taken count analysis, such that
4615   // attempting to ask for the backedge-taken count would likely result
4616   // in infinite recursion. In the later case, the analysis code will
4617   // cope with a conservative value, and it will take care to purge
4618   // that value once it has finished.
4619   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4620 
4621   // Normally, in the cases we can prove no-overflow via a
4622   // backedge guarding condition, we can also compute a backedge
4623   // taken count for the loop.  The exceptions are assumptions and
4624   // guards present in the loop -- SCEV is not great at exploiting
4625   // these to compute max backedge taken counts, but can still use
4626   // these to prove lack of overflow.  Use this fact to avoid
4627   // doing extra work that may not pay off.
4628 
4629   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4630       AC.assumptions().empty())
4631     return Result;
4632 
4633   // If the backedge is guarded by a comparison with the pre-inc  value the
4634   // addrec is safe. Also, if the entry is guarded by a comparison with the
4635   // start value and the backedge is guarded by a comparison with the post-inc
4636   // value, the addrec is safe.
4637   ICmpInst::Predicate Pred;
4638   const SCEV *OverflowLimit =
4639     getSignedOverflowLimitForStep(Step, &Pred, this);
4640   if (OverflowLimit &&
4641       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4642        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4643     Result = setFlags(Result, SCEV::FlagNSW);
4644   }
4645   return Result;
4646 }
4647 SCEV::NoWrapFlags
4648 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4649   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4650 
4651   if (AR->hasNoUnsignedWrap())
4652     return Result;
4653 
4654   if (!AR->isAffine())
4655     return Result;
4656 
4657   const SCEV *Step = AR->getStepRecurrence(*this);
4658   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4659   const Loop *L = AR->getLoop();
4660 
4661   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4662   // Note that this serves two purposes: It filters out loops that are
4663   // simply not analyzable, and it covers the case where this code is
4664   // being called from within backedge-taken count analysis, such that
4665   // attempting to ask for the backedge-taken count would likely result
4666   // in infinite recursion. In the later case, the analysis code will
4667   // cope with a conservative value, and it will take care to purge
4668   // that value once it has finished.
4669   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4670 
4671   // Normally, in the cases we can prove no-overflow via a
4672   // backedge guarding condition, we can also compute a backedge
4673   // taken count for the loop.  The exceptions are assumptions and
4674   // guards present in the loop -- SCEV is not great at exploiting
4675   // these to compute max backedge taken counts, but can still use
4676   // these to prove lack of overflow.  Use this fact to avoid
4677   // doing extra work that may not pay off.
4678 
4679   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4680       AC.assumptions().empty())
4681     return Result;
4682 
4683   // If the backedge is guarded by a comparison with the pre-inc  value the
4684   // addrec is safe. Also, if the entry is guarded by a comparison with the
4685   // start value and the backedge is guarded by a comparison with the post-inc
4686   // value, the addrec is safe.
4687   if (isKnownPositive(Step)) {
4688     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4689                                 getUnsignedRangeMax(Step));
4690     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4691         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4692       Result = setFlags(Result, SCEV::FlagNUW);
4693     }
4694   }
4695 
4696   return Result;
4697 }
4698 
4699 namespace {
4700 
4701 /// Represents an abstract binary operation.  This may exist as a
4702 /// normal instruction or constant expression, or may have been
4703 /// derived from an expression tree.
4704 struct BinaryOp {
4705   unsigned Opcode;
4706   Value *LHS;
4707   Value *RHS;
4708   bool IsNSW = false;
4709   bool IsNUW = false;
4710 
4711   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4712   /// constant expression.
4713   Operator *Op = nullptr;
4714 
4715   explicit BinaryOp(Operator *Op)
4716       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4717         Op(Op) {
4718     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4719       IsNSW = OBO->hasNoSignedWrap();
4720       IsNUW = OBO->hasNoUnsignedWrap();
4721     }
4722   }
4723 
4724   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4725                     bool IsNUW = false)
4726       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4727 };
4728 
4729 } // end anonymous namespace
4730 
4731 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4732 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4733   auto *Op = dyn_cast<Operator>(V);
4734   if (!Op)
4735     return None;
4736 
4737   // Implementation detail: all the cleverness here should happen without
4738   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4739   // SCEV expressions when possible, and we should not break that.
4740 
4741   switch (Op->getOpcode()) {
4742   case Instruction::Add:
4743   case Instruction::Sub:
4744   case Instruction::Mul:
4745   case Instruction::UDiv:
4746   case Instruction::URem:
4747   case Instruction::And:
4748   case Instruction::Or:
4749   case Instruction::AShr:
4750   case Instruction::Shl:
4751     return BinaryOp(Op);
4752 
4753   case Instruction::Xor:
4754     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4755       // If the RHS of the xor is a signmask, then this is just an add.
4756       // Instcombine turns add of signmask into xor as a strength reduction step.
4757       if (RHSC->getValue().isSignMask())
4758         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4759     return BinaryOp(Op);
4760 
4761   case Instruction::LShr:
4762     // Turn logical shift right of a constant into a unsigned divide.
4763     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4764       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4765 
4766       // If the shift count is not less than the bitwidth, the result of
4767       // the shift is undefined. Don't try to analyze it, because the
4768       // resolution chosen here may differ from the resolution chosen in
4769       // other parts of the compiler.
4770       if (SA->getValue().ult(BitWidth)) {
4771         Constant *X =
4772             ConstantInt::get(SA->getContext(),
4773                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4774         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4775       }
4776     }
4777     return BinaryOp(Op);
4778 
4779   case Instruction::ExtractValue: {
4780     auto *EVI = cast<ExtractValueInst>(Op);
4781     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4782       break;
4783 
4784     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4785     if (!WO)
4786       break;
4787 
4788     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4789     bool Signed = WO->isSigned();
4790     // TODO: Should add nuw/nsw flags for mul as well.
4791     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4792       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4793 
4794     // Now that we know that all uses of the arithmetic-result component of
4795     // CI are guarded by the overflow check, we can go ahead and pretend
4796     // that the arithmetic is non-overflowing.
4797     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4798                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4799   }
4800 
4801   default:
4802     break;
4803   }
4804 
4805   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4806   // semantics as a Sub, return a binary sub expression.
4807   if (auto *II = dyn_cast<IntrinsicInst>(V))
4808     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4809       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4810 
4811   return None;
4812 }
4813 
4814 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4815 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4816 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4817 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4818 /// follows one of the following patterns:
4819 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4820 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4821 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4822 /// we return the type of the truncation operation, and indicate whether the
4823 /// truncated type should be treated as signed/unsigned by setting
4824 /// \p Signed to true/false, respectively.
4825 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4826                                bool &Signed, ScalarEvolution &SE) {
4827   // The case where Op == SymbolicPHI (that is, with no type conversions on
4828   // the way) is handled by the regular add recurrence creating logic and
4829   // would have already been triggered in createAddRecForPHI. Reaching it here
4830   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4831   // because one of the other operands of the SCEVAddExpr updating this PHI is
4832   // not invariant).
4833   //
4834   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4835   // this case predicates that allow us to prove that Op == SymbolicPHI will
4836   // be added.
4837   if (Op == SymbolicPHI)
4838     return nullptr;
4839 
4840   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4841   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4842   if (SourceBits != NewBits)
4843     return nullptr;
4844 
4845   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4846   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4847   if (!SExt && !ZExt)
4848     return nullptr;
4849   const SCEVTruncateExpr *Trunc =
4850       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4851            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4852   if (!Trunc)
4853     return nullptr;
4854   const SCEV *X = Trunc->getOperand();
4855   if (X != SymbolicPHI)
4856     return nullptr;
4857   Signed = SExt != nullptr;
4858   return Trunc->getType();
4859 }
4860 
4861 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4862   if (!PN->getType()->isIntegerTy())
4863     return nullptr;
4864   const Loop *L = LI.getLoopFor(PN->getParent());
4865   if (!L || L->getHeader() != PN->getParent())
4866     return nullptr;
4867   return L;
4868 }
4869 
4870 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4871 // computation that updates the phi follows the following pattern:
4872 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4873 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4874 // If so, try to see if it can be rewritten as an AddRecExpr under some
4875 // Predicates. If successful, return them as a pair. Also cache the results
4876 // of the analysis.
4877 //
4878 // Example usage scenario:
4879 //    Say the Rewriter is called for the following SCEV:
4880 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4881 //    where:
4882 //         %X = phi i64 (%Start, %BEValue)
4883 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4884 //    and call this function with %SymbolicPHI = %X.
4885 //
4886 //    The analysis will find that the value coming around the backedge has
4887 //    the following SCEV:
4888 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4889 //    Upon concluding that this matches the desired pattern, the function
4890 //    will return the pair {NewAddRec, SmallPredsVec} where:
4891 //         NewAddRec = {%Start,+,%Step}
4892 //         SmallPredsVec = {P1, P2, P3} as follows:
4893 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4894 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4895 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4896 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4897 //    under the predicates {P1,P2,P3}.
4898 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4899 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4900 //
4901 // TODO's:
4902 //
4903 // 1) Extend the Induction descriptor to also support inductions that involve
4904 //    casts: When needed (namely, when we are called in the context of the
4905 //    vectorizer induction analysis), a Set of cast instructions will be
4906 //    populated by this method, and provided back to isInductionPHI. This is
4907 //    needed to allow the vectorizer to properly record them to be ignored by
4908 //    the cost model and to avoid vectorizing them (otherwise these casts,
4909 //    which are redundant under the runtime overflow checks, will be
4910 //    vectorized, which can be costly).
4911 //
4912 // 2) Support additional induction/PHISCEV patterns: We also want to support
4913 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4914 //    after the induction update operation (the induction increment):
4915 //
4916 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4917 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4918 //
4919 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4920 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4921 //
4922 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4923 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4924 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4925   SmallVector<const SCEVPredicate *, 3> Predicates;
4926 
4927   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4928   // return an AddRec expression under some predicate.
4929 
4930   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4931   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4932   assert(L && "Expecting an integer loop header phi");
4933 
4934   // The loop may have multiple entrances or multiple exits; we can analyze
4935   // this phi as an addrec if it has a unique entry value and a unique
4936   // backedge value.
4937   Value *BEValueV = nullptr, *StartValueV = nullptr;
4938   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4939     Value *V = PN->getIncomingValue(i);
4940     if (L->contains(PN->getIncomingBlock(i))) {
4941       if (!BEValueV) {
4942         BEValueV = V;
4943       } else if (BEValueV != V) {
4944         BEValueV = nullptr;
4945         break;
4946       }
4947     } else if (!StartValueV) {
4948       StartValueV = V;
4949     } else if (StartValueV != V) {
4950       StartValueV = nullptr;
4951       break;
4952     }
4953   }
4954   if (!BEValueV || !StartValueV)
4955     return None;
4956 
4957   const SCEV *BEValue = getSCEV(BEValueV);
4958 
4959   // If the value coming around the backedge is an add with the symbolic
4960   // value we just inserted, possibly with casts that we can ignore under
4961   // an appropriate runtime guard, then we found a simple induction variable!
4962   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4963   if (!Add)
4964     return None;
4965 
4966   // If there is a single occurrence of the symbolic value, possibly
4967   // casted, replace it with a recurrence.
4968   unsigned FoundIndex = Add->getNumOperands();
4969   Type *TruncTy = nullptr;
4970   bool Signed;
4971   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4972     if ((TruncTy =
4973              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4974       if (FoundIndex == e) {
4975         FoundIndex = i;
4976         break;
4977       }
4978 
4979   if (FoundIndex == Add->getNumOperands())
4980     return None;
4981 
4982   // Create an add with everything but the specified operand.
4983   SmallVector<const SCEV *, 8> Ops;
4984   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4985     if (i != FoundIndex)
4986       Ops.push_back(Add->getOperand(i));
4987   const SCEV *Accum = getAddExpr(Ops);
4988 
4989   // The runtime checks will not be valid if the step amount is
4990   // varying inside the loop.
4991   if (!isLoopInvariant(Accum, L))
4992     return None;
4993 
4994   // *** Part2: Create the predicates
4995 
4996   // Analysis was successful: we have a phi-with-cast pattern for which we
4997   // can return an AddRec expression under the following predicates:
4998   //
4999   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5000   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5001   // P2: An Equal predicate that guarantees that
5002   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5003   // P3: An Equal predicate that guarantees that
5004   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5005   //
5006   // As we next prove, the above predicates guarantee that:
5007   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5008   //
5009   //
5010   // More formally, we want to prove that:
5011   //     Expr(i+1) = Start + (i+1) * Accum
5012   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5013   //
5014   // Given that:
5015   // 1) Expr(0) = Start
5016   // 2) Expr(1) = Start + Accum
5017   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5018   // 3) Induction hypothesis (step i):
5019   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5020   //
5021   // Proof:
5022   //  Expr(i+1) =
5023   //   = Start + (i+1)*Accum
5024   //   = (Start + i*Accum) + Accum
5025   //   = Expr(i) + Accum
5026   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5027   //                                                             :: from step i
5028   //
5029   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5030   //
5031   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5032   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5033   //     + Accum                                                     :: from P3
5034   //
5035   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5036   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5037   //
5038   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5039   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5040   //
5041   // By induction, the same applies to all iterations 1<=i<n:
5042   //
5043 
5044   // Create a truncated addrec for which we will add a no overflow check (P1).
5045   const SCEV *StartVal = getSCEV(StartValueV);
5046   const SCEV *PHISCEV =
5047       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5048                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5049 
5050   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5051   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5052   // will be constant.
5053   //
5054   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5055   // add P1.
5056   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5057     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5058         Signed ? SCEVWrapPredicate::IncrementNSSW
5059                : SCEVWrapPredicate::IncrementNUSW;
5060     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5061     Predicates.push_back(AddRecPred);
5062   }
5063 
5064   // Create the Equal Predicates P2,P3:
5065 
5066   // It is possible that the predicates P2 and/or P3 are computable at
5067   // compile time due to StartVal and/or Accum being constants.
5068   // If either one is, then we can check that now and escape if either P2
5069   // or P3 is false.
5070 
5071   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5072   // for each of StartVal and Accum
5073   auto getExtendedExpr = [&](const SCEV *Expr,
5074                              bool CreateSignExtend) -> const SCEV * {
5075     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5076     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5077     const SCEV *ExtendedExpr =
5078         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5079                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5080     return ExtendedExpr;
5081   };
5082 
5083   // Given:
5084   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5085   //               = getExtendedExpr(Expr)
5086   // Determine whether the predicate P: Expr == ExtendedExpr
5087   // is known to be false at compile time
5088   auto PredIsKnownFalse = [&](const SCEV *Expr,
5089                               const SCEV *ExtendedExpr) -> bool {
5090     return Expr != ExtendedExpr &&
5091            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5092   };
5093 
5094   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5095   if (PredIsKnownFalse(StartVal, StartExtended)) {
5096     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5097     return None;
5098   }
5099 
5100   // The Step is always Signed (because the overflow checks are either
5101   // NSSW or NUSW)
5102   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5103   if (PredIsKnownFalse(Accum, AccumExtended)) {
5104     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5105     return None;
5106   }
5107 
5108   auto AppendPredicate = [&](const SCEV *Expr,
5109                              const SCEV *ExtendedExpr) -> void {
5110     if (Expr != ExtendedExpr &&
5111         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5112       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5113       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5114       Predicates.push_back(Pred);
5115     }
5116   };
5117 
5118   AppendPredicate(StartVal, StartExtended);
5119   AppendPredicate(Accum, AccumExtended);
5120 
5121   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5122   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5123   // into NewAR if it will also add the runtime overflow checks specified in
5124   // Predicates.
5125   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5126 
5127   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5128       std::make_pair(NewAR, Predicates);
5129   // Remember the result of the analysis for this SCEV at this locayyytion.
5130   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5131   return PredRewrite;
5132 }
5133 
5134 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5135 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5136   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5137   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5138   if (!L)
5139     return None;
5140 
5141   // Check to see if we already analyzed this PHI.
5142   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5143   if (I != PredicatedSCEVRewrites.end()) {
5144     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5145         I->second;
5146     // Analysis was done before and failed to create an AddRec:
5147     if (Rewrite.first == SymbolicPHI)
5148       return None;
5149     // Analysis was done before and succeeded to create an AddRec under
5150     // a predicate:
5151     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5152     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5153     return Rewrite;
5154   }
5155 
5156   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5157     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5158 
5159   // Record in the cache that the analysis failed
5160   if (!Rewrite) {
5161     SmallVector<const SCEVPredicate *, 3> Predicates;
5162     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5163     return None;
5164   }
5165 
5166   return Rewrite;
5167 }
5168 
5169 // FIXME: This utility is currently required because the Rewriter currently
5170 // does not rewrite this expression:
5171 // {0, +, (sext ix (trunc iy to ix) to iy)}
5172 // into {0, +, %step},
5173 // even when the following Equal predicate exists:
5174 // "%step == (sext ix (trunc iy to ix) to iy)".
5175 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5176     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5177   if (AR1 == AR2)
5178     return true;
5179 
5180   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5181     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5182         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5183       return false;
5184     return true;
5185   };
5186 
5187   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5188       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5189     return false;
5190   return true;
5191 }
5192 
5193 /// A helper function for createAddRecFromPHI to handle simple cases.
5194 ///
5195 /// This function tries to find an AddRec expression for the simplest (yet most
5196 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5197 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5198 /// technique for finding the AddRec expression.
5199 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5200                                                       Value *BEValueV,
5201                                                       Value *StartValueV) {
5202   const Loop *L = LI.getLoopFor(PN->getParent());
5203   assert(L && L->getHeader() == PN->getParent());
5204   assert(BEValueV && StartValueV);
5205 
5206   auto BO = MatchBinaryOp(BEValueV, DT);
5207   if (!BO)
5208     return nullptr;
5209 
5210   if (BO->Opcode != Instruction::Add)
5211     return nullptr;
5212 
5213   const SCEV *Accum = nullptr;
5214   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5215     Accum = getSCEV(BO->RHS);
5216   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5217     Accum = getSCEV(BO->LHS);
5218 
5219   if (!Accum)
5220     return nullptr;
5221 
5222   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5223   if (BO->IsNUW)
5224     Flags = setFlags(Flags, SCEV::FlagNUW);
5225   if (BO->IsNSW)
5226     Flags = setFlags(Flags, SCEV::FlagNSW);
5227 
5228   const SCEV *StartVal = getSCEV(StartValueV);
5229   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5230 
5231   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5232 
5233   // We can add Flags to the post-inc expression only if we
5234   // know that it is *undefined behavior* for BEValueV to
5235   // overflow.
5236   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5237     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5238       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5239 
5240   return PHISCEV;
5241 }
5242 
5243 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5244   const Loop *L = LI.getLoopFor(PN->getParent());
5245   if (!L || L->getHeader() != PN->getParent())
5246     return nullptr;
5247 
5248   // The loop may have multiple entrances or multiple exits; we can analyze
5249   // this phi as an addrec if it has a unique entry value and a unique
5250   // backedge value.
5251   Value *BEValueV = nullptr, *StartValueV = nullptr;
5252   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5253     Value *V = PN->getIncomingValue(i);
5254     if (L->contains(PN->getIncomingBlock(i))) {
5255       if (!BEValueV) {
5256         BEValueV = V;
5257       } else if (BEValueV != V) {
5258         BEValueV = nullptr;
5259         break;
5260       }
5261     } else if (!StartValueV) {
5262       StartValueV = V;
5263     } else if (StartValueV != V) {
5264       StartValueV = nullptr;
5265       break;
5266     }
5267   }
5268   if (!BEValueV || !StartValueV)
5269     return nullptr;
5270 
5271   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5272          "PHI node already processed?");
5273 
5274   // First, try to find AddRec expression without creating a fictituos symbolic
5275   // value for PN.
5276   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5277     return S;
5278 
5279   // Handle PHI node value symbolically.
5280   const SCEV *SymbolicName = getUnknown(PN);
5281   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5282 
5283   // Using this symbolic name for the PHI, analyze the value coming around
5284   // the back-edge.
5285   const SCEV *BEValue = getSCEV(BEValueV);
5286 
5287   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5288   // has a special value for the first iteration of the loop.
5289 
5290   // If the value coming around the backedge is an add with the symbolic
5291   // value we just inserted, then we found a simple induction variable!
5292   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5293     // If there is a single occurrence of the symbolic value, replace it
5294     // with a recurrence.
5295     unsigned FoundIndex = Add->getNumOperands();
5296     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5297       if (Add->getOperand(i) == SymbolicName)
5298         if (FoundIndex == e) {
5299           FoundIndex = i;
5300           break;
5301         }
5302 
5303     if (FoundIndex != Add->getNumOperands()) {
5304       // Create an add with everything but the specified operand.
5305       SmallVector<const SCEV *, 8> Ops;
5306       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5307         if (i != FoundIndex)
5308           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5309                                                              L, *this));
5310       const SCEV *Accum = getAddExpr(Ops);
5311 
5312       // This is not a valid addrec if the step amount is varying each
5313       // loop iteration, but is not itself an addrec in this loop.
5314       if (isLoopInvariant(Accum, L) ||
5315           (isa<SCEVAddRecExpr>(Accum) &&
5316            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5317         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5318 
5319         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5320           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5321             if (BO->IsNUW)
5322               Flags = setFlags(Flags, SCEV::FlagNUW);
5323             if (BO->IsNSW)
5324               Flags = setFlags(Flags, SCEV::FlagNSW);
5325           }
5326         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5327           // If the increment is an inbounds GEP, then we know the address
5328           // space cannot be wrapped around. We cannot make any guarantee
5329           // about signed or unsigned overflow because pointers are
5330           // unsigned but we may have a negative index from the base
5331           // pointer. We can guarantee that no unsigned wrap occurs if the
5332           // indices form a positive value.
5333           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5334             Flags = setFlags(Flags, SCEV::FlagNW);
5335 
5336             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5337             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5338               Flags = setFlags(Flags, SCEV::FlagNUW);
5339           }
5340 
5341           // We cannot transfer nuw and nsw flags from subtraction
5342           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5343           // for instance.
5344         }
5345 
5346         const SCEV *StartVal = getSCEV(StartValueV);
5347         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5348 
5349         // Okay, for the entire analysis of this edge we assumed the PHI
5350         // to be symbolic.  We now need to go back and purge all of the
5351         // entries for the scalars that use the symbolic expression.
5352         forgetSymbolicName(PN, SymbolicName);
5353         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5354 
5355         // We can add Flags to the post-inc expression only if we
5356         // know that it is *undefined behavior* for BEValueV to
5357         // overflow.
5358         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5359           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5360             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5361 
5362         return PHISCEV;
5363       }
5364     }
5365   } else {
5366     // Otherwise, this could be a loop like this:
5367     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5368     // In this case, j = {1,+,1}  and BEValue is j.
5369     // Because the other in-value of i (0) fits the evolution of BEValue
5370     // i really is an addrec evolution.
5371     //
5372     // We can generalize this saying that i is the shifted value of BEValue
5373     // by one iteration:
5374     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5375     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5376     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5377     if (Shifted != getCouldNotCompute() &&
5378         Start != getCouldNotCompute()) {
5379       const SCEV *StartVal = getSCEV(StartValueV);
5380       if (Start == StartVal) {
5381         // Okay, for the entire analysis of this edge we assumed the PHI
5382         // to be symbolic.  We now need to go back and purge all of the
5383         // entries for the scalars that use the symbolic expression.
5384         forgetSymbolicName(PN, SymbolicName);
5385         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5386         return Shifted;
5387       }
5388     }
5389   }
5390 
5391   // Remove the temporary PHI node SCEV that has been inserted while intending
5392   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5393   // as it will prevent later (possibly simpler) SCEV expressions to be added
5394   // to the ValueExprMap.
5395   eraseValueFromMap(PN);
5396 
5397   return nullptr;
5398 }
5399 
5400 // Checks if the SCEV S is available at BB.  S is considered available at BB
5401 // if S can be materialized at BB without introducing a fault.
5402 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5403                                BasicBlock *BB) {
5404   struct CheckAvailable {
5405     bool TraversalDone = false;
5406     bool Available = true;
5407 
5408     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5409     BasicBlock *BB = nullptr;
5410     DominatorTree &DT;
5411 
5412     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5413       : L(L), BB(BB), DT(DT) {}
5414 
5415     bool setUnavailable() {
5416       TraversalDone = true;
5417       Available = false;
5418       return false;
5419     }
5420 
5421     bool follow(const SCEV *S) {
5422       switch (S->getSCEVType()) {
5423       case scConstant:
5424       case scPtrToInt:
5425       case scTruncate:
5426       case scZeroExtend:
5427       case scSignExtend:
5428       case scAddExpr:
5429       case scMulExpr:
5430       case scUMaxExpr:
5431       case scSMaxExpr:
5432       case scUMinExpr:
5433       case scSMinExpr:
5434         // These expressions are available if their operand(s) is/are.
5435         return true;
5436 
5437       case scAddRecExpr: {
5438         // We allow add recurrences that are on the loop BB is in, or some
5439         // outer loop.  This guarantees availability because the value of the
5440         // add recurrence at BB is simply the "current" value of the induction
5441         // variable.  We can relax this in the future; for instance an add
5442         // recurrence on a sibling dominating loop is also available at BB.
5443         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5444         if (L && (ARLoop == L || ARLoop->contains(L)))
5445           return true;
5446 
5447         return setUnavailable();
5448       }
5449 
5450       case scUnknown: {
5451         // For SCEVUnknown, we check for simple dominance.
5452         const auto *SU = cast<SCEVUnknown>(S);
5453         Value *V = SU->getValue();
5454 
5455         if (isa<Argument>(V))
5456           return false;
5457 
5458         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5459           return false;
5460 
5461         return setUnavailable();
5462       }
5463 
5464       case scUDivExpr:
5465       case scCouldNotCompute:
5466         // We do not try to smart about these at all.
5467         return setUnavailable();
5468       }
5469       llvm_unreachable("Unknown SCEV kind!");
5470     }
5471 
5472     bool isDone() { return TraversalDone; }
5473   };
5474 
5475   CheckAvailable CA(L, BB, DT);
5476   SCEVTraversal<CheckAvailable> ST(CA);
5477 
5478   ST.visitAll(S);
5479   return CA.Available;
5480 }
5481 
5482 // Try to match a control flow sequence that branches out at BI and merges back
5483 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5484 // match.
5485 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5486                           Value *&C, Value *&LHS, Value *&RHS) {
5487   C = BI->getCondition();
5488 
5489   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5490   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5491 
5492   if (!LeftEdge.isSingleEdge())
5493     return false;
5494 
5495   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5496 
5497   Use &LeftUse = Merge->getOperandUse(0);
5498   Use &RightUse = Merge->getOperandUse(1);
5499 
5500   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5501     LHS = LeftUse;
5502     RHS = RightUse;
5503     return true;
5504   }
5505 
5506   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5507     LHS = RightUse;
5508     RHS = LeftUse;
5509     return true;
5510   }
5511 
5512   return false;
5513 }
5514 
5515 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5516   auto IsReachable =
5517       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5518   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5519     const Loop *L = LI.getLoopFor(PN->getParent());
5520 
5521     // We don't want to break LCSSA, even in a SCEV expression tree.
5522     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5523       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5524         return nullptr;
5525 
5526     // Try to match
5527     //
5528     //  br %cond, label %left, label %right
5529     // left:
5530     //  br label %merge
5531     // right:
5532     //  br label %merge
5533     // merge:
5534     //  V = phi [ %x, %left ], [ %y, %right ]
5535     //
5536     // as "select %cond, %x, %y"
5537 
5538     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5539     assert(IDom && "At least the entry block should dominate PN");
5540 
5541     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5542     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5543 
5544     if (BI && BI->isConditional() &&
5545         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5546         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5547         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5548       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5549   }
5550 
5551   return nullptr;
5552 }
5553 
5554 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5555   if (const SCEV *S = createAddRecFromPHI(PN))
5556     return S;
5557 
5558   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5559     return S;
5560 
5561   // If the PHI has a single incoming value, follow that value, unless the
5562   // PHI's incoming blocks are in a different loop, in which case doing so
5563   // risks breaking LCSSA form. Instcombine would normally zap these, but
5564   // it doesn't have DominatorTree information, so it may miss cases.
5565   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5566     if (LI.replacementPreservesLCSSAForm(PN, V))
5567       return getSCEV(V);
5568 
5569   // If it's not a loop phi, we can't handle it yet.
5570   return getUnknown(PN);
5571 }
5572 
5573 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5574                                                       Value *Cond,
5575                                                       Value *TrueVal,
5576                                                       Value *FalseVal) {
5577   // Handle "constant" branch or select. This can occur for instance when a
5578   // loop pass transforms an inner loop and moves on to process the outer loop.
5579   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5580     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5581 
5582   // Try to match some simple smax or umax patterns.
5583   auto *ICI = dyn_cast<ICmpInst>(Cond);
5584   if (!ICI)
5585     return getUnknown(I);
5586 
5587   Value *LHS = ICI->getOperand(0);
5588   Value *RHS = ICI->getOperand(1);
5589 
5590   switch (ICI->getPredicate()) {
5591   case ICmpInst::ICMP_SLT:
5592   case ICmpInst::ICMP_SLE:
5593   case ICmpInst::ICMP_ULT:
5594   case ICmpInst::ICMP_ULE:
5595     std::swap(LHS, RHS);
5596     LLVM_FALLTHROUGH;
5597   case ICmpInst::ICMP_SGT:
5598   case ICmpInst::ICMP_SGE:
5599   case ICmpInst::ICMP_UGT:
5600   case ICmpInst::ICMP_UGE:
5601     // a > b ? a+x : b+x  ->  max(a, b)+x
5602     // a > b ? b+x : a+x  ->  min(a, b)+x
5603     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5604       bool Signed = ICI->isSigned();
5605       const SCEV *LA = getSCEV(TrueVal);
5606       const SCEV *RA = getSCEV(FalseVal);
5607       const SCEV *LS = getSCEV(LHS);
5608       const SCEV *RS = getSCEV(RHS);
5609       if (LA->getType()->isPointerTy()) {
5610         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5611         // Need to make sure we can't produce weird expressions involving
5612         // negated pointers.
5613         if (LA == LS && RA == RS)
5614           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5615         if (LA == RS && RA == LS)
5616           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5617       }
5618       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5619         if (Op->getType()->isPointerTy()) {
5620           Op = getLosslessPtrToIntExpr(Op);
5621           if (isa<SCEVCouldNotCompute>(Op))
5622             return Op;
5623         }
5624         if (Signed)
5625           Op = getNoopOrSignExtend(Op, I->getType());
5626         else
5627           Op = getNoopOrZeroExtend(Op, I->getType());
5628         return Op;
5629       };
5630       LS = CoerceOperand(LS);
5631       RS = CoerceOperand(RS);
5632       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
5633         break;
5634       const SCEV *LDiff = getMinusSCEV(LA, LS);
5635       const SCEV *RDiff = getMinusSCEV(RA, RS);
5636       if (LDiff == RDiff)
5637         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
5638                           LDiff);
5639       LDiff = getMinusSCEV(LA, RS);
5640       RDiff = getMinusSCEV(RA, LS);
5641       if (LDiff == RDiff)
5642         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
5643                           LDiff);
5644     }
5645     break;
5646   case ICmpInst::ICMP_NE:
5647     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5648     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5649         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5650       const SCEV *One = getOne(I->getType());
5651       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5652       const SCEV *LA = getSCEV(TrueVal);
5653       const SCEV *RA = getSCEV(FalseVal);
5654       const SCEV *LDiff = getMinusSCEV(LA, LS);
5655       const SCEV *RDiff = getMinusSCEV(RA, One);
5656       if (LDiff == RDiff)
5657         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5658     }
5659     break;
5660   case ICmpInst::ICMP_EQ:
5661     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5662     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5663         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5664       const SCEV *One = getOne(I->getType());
5665       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5666       const SCEV *LA = getSCEV(TrueVal);
5667       const SCEV *RA = getSCEV(FalseVal);
5668       const SCEV *LDiff = getMinusSCEV(LA, One);
5669       const SCEV *RDiff = getMinusSCEV(RA, LS);
5670       if (LDiff == RDiff)
5671         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5672     }
5673     break;
5674   default:
5675     break;
5676   }
5677 
5678   return getUnknown(I);
5679 }
5680 
5681 /// Expand GEP instructions into add and multiply operations. This allows them
5682 /// to be analyzed by regular SCEV code.
5683 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5684   // Don't attempt to analyze GEPs over unsized objects.
5685   if (!GEP->getSourceElementType()->isSized())
5686     return getUnknown(GEP);
5687 
5688   SmallVector<const SCEV *, 4> IndexExprs;
5689   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5690     IndexExprs.push_back(getSCEV(*Index));
5691   return getGEPExpr(GEP, IndexExprs);
5692 }
5693 
5694 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5695   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5696     return C->getAPInt().countTrailingZeros();
5697 
5698   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5699     return GetMinTrailingZeros(I->getOperand());
5700 
5701   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5702     return std::min(GetMinTrailingZeros(T->getOperand()),
5703                     (uint32_t)getTypeSizeInBits(T->getType()));
5704 
5705   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5706     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5707     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5708                ? getTypeSizeInBits(E->getType())
5709                : OpRes;
5710   }
5711 
5712   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5713     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5714     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5715                ? getTypeSizeInBits(E->getType())
5716                : OpRes;
5717   }
5718 
5719   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5720     // The result is the min of all operands results.
5721     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5722     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5723       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5724     return MinOpRes;
5725   }
5726 
5727   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5728     // The result is the sum of all operands results.
5729     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5730     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5731     for (unsigned i = 1, e = M->getNumOperands();
5732          SumOpRes != BitWidth && i != e; ++i)
5733       SumOpRes =
5734           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5735     return SumOpRes;
5736   }
5737 
5738   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5739     // The result is the min of all operands results.
5740     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5741     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5742       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5743     return MinOpRes;
5744   }
5745 
5746   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5747     // The result is the min of all operands results.
5748     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5749     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5750       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5751     return MinOpRes;
5752   }
5753 
5754   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5755     // The result is the min of all operands results.
5756     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5757     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5758       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5759     return MinOpRes;
5760   }
5761 
5762   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5763     // For a SCEVUnknown, ask ValueTracking.
5764     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5765     return Known.countMinTrailingZeros();
5766   }
5767 
5768   // SCEVUDivExpr
5769   return 0;
5770 }
5771 
5772 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5773   auto I = MinTrailingZerosCache.find(S);
5774   if (I != MinTrailingZerosCache.end())
5775     return I->second;
5776 
5777   uint32_t Result = GetMinTrailingZerosImpl(S);
5778   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5779   assert(InsertPair.second && "Should insert a new key");
5780   return InsertPair.first->second;
5781 }
5782 
5783 /// Helper method to assign a range to V from metadata present in the IR.
5784 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5785   if (Instruction *I = dyn_cast<Instruction>(V))
5786     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5787       return getConstantRangeFromMetadata(*MD);
5788 
5789   return None;
5790 }
5791 
5792 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5793                                      SCEV::NoWrapFlags Flags) {
5794   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5795     AddRec->setNoWrapFlags(Flags);
5796     UnsignedRanges.erase(AddRec);
5797     SignedRanges.erase(AddRec);
5798   }
5799 }
5800 
5801 ConstantRange ScalarEvolution::
5802 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5803   const DataLayout &DL = getDataLayout();
5804 
5805   unsigned BitWidth = getTypeSizeInBits(U->getType());
5806   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
5807 
5808   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5809   // use information about the trip count to improve our available range.  Note
5810   // that the trip count independent cases are already handled by known bits.
5811   // WARNING: The definition of recurrence used here is subtly different than
5812   // the one used by AddRec (and thus most of this file).  Step is allowed to
5813   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5814   // and other addrecs in the same loop (for non-affine addrecs).  The code
5815   // below intentionally handles the case where step is not loop invariant.
5816   auto *P = dyn_cast<PHINode>(U->getValue());
5817   if (!P)
5818     return FullSet;
5819 
5820   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5821   // even the values that are not available in these blocks may come from them,
5822   // and this leads to false-positive recurrence test.
5823   for (auto *Pred : predecessors(P->getParent()))
5824     if (!DT.isReachableFromEntry(Pred))
5825       return FullSet;
5826 
5827   BinaryOperator *BO;
5828   Value *Start, *Step;
5829   if (!matchSimpleRecurrence(P, BO, Start, Step))
5830     return FullSet;
5831 
5832   // If we found a recurrence in reachable code, we must be in a loop. Note
5833   // that BO might be in some subloop of L, and that's completely okay.
5834   auto *L = LI.getLoopFor(P->getParent());
5835   assert(L && L->getHeader() == P->getParent());
5836   if (!L->contains(BO->getParent()))
5837     // NOTE: This bailout should be an assert instead.  However, asserting
5838     // the condition here exposes a case where LoopFusion is querying SCEV
5839     // with malformed loop information during the midst of the transform.
5840     // There doesn't appear to be an obvious fix, so for the moment bailout
5841     // until the caller issue can be fixed.  PR49566 tracks the bug.
5842     return FullSet;
5843 
5844   // TODO: Extend to other opcodes such as mul, and div
5845   switch (BO->getOpcode()) {
5846   default:
5847     return FullSet;
5848   case Instruction::AShr:
5849   case Instruction::LShr:
5850   case Instruction::Shl:
5851     break;
5852   };
5853 
5854   if (BO->getOperand(0) != P)
5855     // TODO: Handle the power function forms some day.
5856     return FullSet;
5857 
5858   unsigned TC = getSmallConstantMaxTripCount(L);
5859   if (!TC || TC >= BitWidth)
5860     return FullSet;
5861 
5862   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5863   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5864   assert(KnownStart.getBitWidth() == BitWidth &&
5865          KnownStep.getBitWidth() == BitWidth);
5866 
5867   // Compute total shift amount, being careful of overflow and bitwidths.
5868   auto MaxShiftAmt = KnownStep.getMaxValue();
5869   APInt TCAP(BitWidth, TC-1);
5870   bool Overflow = false;
5871   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5872   if (Overflow)
5873     return FullSet;
5874 
5875   switch (BO->getOpcode()) {
5876   default:
5877     llvm_unreachable("filtered out above");
5878   case Instruction::AShr: {
5879     // For each ashr, three cases:
5880     //   shift = 0 => unchanged value
5881     //   saturation => 0 or -1
5882     //   other => a value closer to zero (of the same sign)
5883     // Thus, the end value is closer to zero than the start.
5884     auto KnownEnd = KnownBits::ashr(KnownStart,
5885                                     KnownBits::makeConstant(TotalShift));
5886     if (KnownStart.isNonNegative())
5887       // Analogous to lshr (simply not yet canonicalized)
5888       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5889                                         KnownStart.getMaxValue() + 1);
5890     if (KnownStart.isNegative())
5891       // End >=u Start && End <=s Start
5892       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
5893                                         KnownEnd.getMaxValue() + 1);
5894     break;
5895   }
5896   case Instruction::LShr: {
5897     // For each lshr, three cases:
5898     //   shift = 0 => unchanged value
5899     //   saturation => 0
5900     //   other => a smaller positive number
5901     // Thus, the low end of the unsigned range is the last value produced.
5902     auto KnownEnd = KnownBits::lshr(KnownStart,
5903                                     KnownBits::makeConstant(TotalShift));
5904     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5905                                       KnownStart.getMaxValue() + 1);
5906   }
5907   case Instruction::Shl: {
5908     // Iff no bits are shifted out, value increases on every shift.
5909     auto KnownEnd = KnownBits::shl(KnownStart,
5910                                    KnownBits::makeConstant(TotalShift));
5911     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5912       return ConstantRange(KnownStart.getMinValue(),
5913                            KnownEnd.getMaxValue() + 1);
5914     break;
5915   }
5916   };
5917   return FullSet;
5918 }
5919 
5920 /// Determine the range for a particular SCEV.  If SignHint is
5921 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5922 /// with a "cleaner" unsigned (resp. signed) representation.
5923 const ConstantRange &
5924 ScalarEvolution::getRangeRef(const SCEV *S,
5925                              ScalarEvolution::RangeSignHint SignHint) {
5926   DenseMap<const SCEV *, ConstantRange> &Cache =
5927       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5928                                                        : SignedRanges;
5929   ConstantRange::PreferredRangeType RangeType =
5930       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5931           ? ConstantRange::Unsigned : ConstantRange::Signed;
5932 
5933   // See if we've computed this range already.
5934   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5935   if (I != Cache.end())
5936     return I->second;
5937 
5938   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5939     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5940 
5941   unsigned BitWidth = getTypeSizeInBits(S->getType());
5942   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5943   using OBO = OverflowingBinaryOperator;
5944 
5945   // If the value has known zeros, the maximum value will have those known zeros
5946   // as well.
5947   uint32_t TZ = GetMinTrailingZeros(S);
5948   if (TZ != 0) {
5949     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5950       ConservativeResult =
5951           ConstantRange(APInt::getMinValue(BitWidth),
5952                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5953     else
5954       ConservativeResult = ConstantRange(
5955           APInt::getSignedMinValue(BitWidth),
5956           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5957   }
5958 
5959   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5960     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5961     unsigned WrapType = OBO::AnyWrap;
5962     if (Add->hasNoSignedWrap())
5963       WrapType |= OBO::NoSignedWrap;
5964     if (Add->hasNoUnsignedWrap())
5965       WrapType |= OBO::NoUnsignedWrap;
5966     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5967       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5968                           WrapType, RangeType);
5969     return setRange(Add, SignHint,
5970                     ConservativeResult.intersectWith(X, RangeType));
5971   }
5972 
5973   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5974     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5975     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5976       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5977     return setRange(Mul, SignHint,
5978                     ConservativeResult.intersectWith(X, RangeType));
5979   }
5980 
5981   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5982     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5983     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5984       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5985     return setRange(SMax, SignHint,
5986                     ConservativeResult.intersectWith(X, RangeType));
5987   }
5988 
5989   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5990     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5991     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5992       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5993     return setRange(UMax, SignHint,
5994                     ConservativeResult.intersectWith(X, RangeType));
5995   }
5996 
5997   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5998     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5999     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
6000       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
6001     return setRange(SMin, SignHint,
6002                     ConservativeResult.intersectWith(X, RangeType));
6003   }
6004 
6005   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
6006     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
6007     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
6008       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
6009     return setRange(UMin, SignHint,
6010                     ConservativeResult.intersectWith(X, RangeType));
6011   }
6012 
6013   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6014     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6015     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6016     return setRange(UDiv, SignHint,
6017                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6018   }
6019 
6020   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6021     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6022     return setRange(ZExt, SignHint,
6023                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6024                                                      RangeType));
6025   }
6026 
6027   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6028     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6029     return setRange(SExt, SignHint,
6030                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6031                                                      RangeType));
6032   }
6033 
6034   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6035     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6036     return setRange(PtrToInt, SignHint, X);
6037   }
6038 
6039   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6040     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6041     return setRange(Trunc, SignHint,
6042                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6043                                                      RangeType));
6044   }
6045 
6046   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6047     // If there's no unsigned wrap, the value will never be less than its
6048     // initial value.
6049     if (AddRec->hasNoUnsignedWrap()) {
6050       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6051       if (!UnsignedMinValue.isNullValue())
6052         ConservativeResult = ConservativeResult.intersectWith(
6053             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6054     }
6055 
6056     // If there's no signed wrap, and all the operands except initial value have
6057     // the same sign or zero, the value won't ever be:
6058     // 1: smaller than initial value if operands are non negative,
6059     // 2: bigger than initial value if operands are non positive.
6060     // For both cases, value can not cross signed min/max boundary.
6061     if (AddRec->hasNoSignedWrap()) {
6062       bool AllNonNeg = true;
6063       bool AllNonPos = true;
6064       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6065         if (!isKnownNonNegative(AddRec->getOperand(i)))
6066           AllNonNeg = false;
6067         if (!isKnownNonPositive(AddRec->getOperand(i)))
6068           AllNonPos = false;
6069       }
6070       if (AllNonNeg)
6071         ConservativeResult = ConservativeResult.intersectWith(
6072             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6073                                        APInt::getSignedMinValue(BitWidth)),
6074             RangeType);
6075       else if (AllNonPos)
6076         ConservativeResult = ConservativeResult.intersectWith(
6077             ConstantRange::getNonEmpty(
6078                 APInt::getSignedMinValue(BitWidth),
6079                 getSignedRangeMax(AddRec->getStart()) + 1),
6080             RangeType);
6081     }
6082 
6083     // TODO: non-affine addrec
6084     if (AddRec->isAffine()) {
6085       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6086       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6087           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6088         auto RangeFromAffine = getRangeForAffineAR(
6089             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6090             BitWidth);
6091         ConservativeResult =
6092             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6093 
6094         auto RangeFromFactoring = getRangeViaFactoring(
6095             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6096             BitWidth);
6097         ConservativeResult =
6098             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6099       }
6100 
6101       // Now try symbolic BE count and more powerful methods.
6102       if (UseExpensiveRangeSharpening) {
6103         const SCEV *SymbolicMaxBECount =
6104             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6105         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6106             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6107             AddRec->hasNoSelfWrap()) {
6108           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6109               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6110           ConservativeResult =
6111               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6112         }
6113       }
6114     }
6115 
6116     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6117   }
6118 
6119   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6120 
6121     // Check if the IR explicitly contains !range metadata.
6122     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6123     if (MDRange.hasValue())
6124       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6125                                                             RangeType);
6126 
6127     // Use facts about recurrences in the underlying IR.  Note that add
6128     // recurrences are AddRecExprs and thus don't hit this path.  This
6129     // primarily handles shift recurrences.
6130     auto CR = getRangeForUnknownRecurrence(U);
6131     ConservativeResult = ConservativeResult.intersectWith(CR);
6132 
6133     // See if ValueTracking can give us a useful range.
6134     const DataLayout &DL = getDataLayout();
6135     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6136     if (Known.getBitWidth() != BitWidth)
6137       Known = Known.zextOrTrunc(BitWidth);
6138 
6139     // ValueTracking may be able to compute a tighter result for the number of
6140     // sign bits than for the value of those sign bits.
6141     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6142     if (U->getType()->isPointerTy()) {
6143       // If the pointer size is larger than the index size type, this can cause
6144       // NS to be larger than BitWidth. So compensate for this.
6145       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6146       int ptrIdxDiff = ptrSize - BitWidth;
6147       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6148         NS -= ptrIdxDiff;
6149     }
6150 
6151     if (NS > 1) {
6152       // If we know any of the sign bits, we know all of the sign bits.
6153       if (!Known.Zero.getHiBits(NS).isNullValue())
6154         Known.Zero.setHighBits(NS);
6155       if (!Known.One.getHiBits(NS).isNullValue())
6156         Known.One.setHighBits(NS);
6157     }
6158 
6159     if (Known.getMinValue() != Known.getMaxValue() + 1)
6160       ConservativeResult = ConservativeResult.intersectWith(
6161           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6162           RangeType);
6163     if (NS > 1)
6164       ConservativeResult = ConservativeResult.intersectWith(
6165           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6166                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6167           RangeType);
6168 
6169     // A range of Phi is a subset of union of all ranges of its input.
6170     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6171       // Make sure that we do not run over cycled Phis.
6172       if (PendingPhiRanges.insert(Phi).second) {
6173         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6174         for (auto &Op : Phi->operands()) {
6175           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6176           RangeFromOps = RangeFromOps.unionWith(OpRange);
6177           // No point to continue if we already have a full set.
6178           if (RangeFromOps.isFullSet())
6179             break;
6180         }
6181         ConservativeResult =
6182             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6183         bool Erased = PendingPhiRanges.erase(Phi);
6184         assert(Erased && "Failed to erase Phi properly?");
6185         (void) Erased;
6186       }
6187     }
6188 
6189     return setRange(U, SignHint, std::move(ConservativeResult));
6190   }
6191 
6192   return setRange(S, SignHint, std::move(ConservativeResult));
6193 }
6194 
6195 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6196 // values that the expression can take. Initially, the expression has a value
6197 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6198 // argument defines if we treat Step as signed or unsigned.
6199 static ConstantRange getRangeForAffineARHelper(APInt Step,
6200                                                const ConstantRange &StartRange,
6201                                                const APInt &MaxBECount,
6202                                                unsigned BitWidth, bool Signed) {
6203   // If either Step or MaxBECount is 0, then the expression won't change, and we
6204   // just need to return the initial range.
6205   if (Step == 0 || MaxBECount == 0)
6206     return StartRange;
6207 
6208   // If we don't know anything about the initial value (i.e. StartRange is
6209   // FullRange), then we don't know anything about the final range either.
6210   // Return FullRange.
6211   if (StartRange.isFullSet())
6212     return ConstantRange::getFull(BitWidth);
6213 
6214   // If Step is signed and negative, then we use its absolute value, but we also
6215   // note that we're moving in the opposite direction.
6216   bool Descending = Signed && Step.isNegative();
6217 
6218   if (Signed)
6219     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6220     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6221     // This equations hold true due to the well-defined wrap-around behavior of
6222     // APInt.
6223     Step = Step.abs();
6224 
6225   // Check if Offset is more than full span of BitWidth. If it is, the
6226   // expression is guaranteed to overflow.
6227   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6228     return ConstantRange::getFull(BitWidth);
6229 
6230   // Offset is by how much the expression can change. Checks above guarantee no
6231   // overflow here.
6232   APInt Offset = Step * MaxBECount;
6233 
6234   // Minimum value of the final range will match the minimal value of StartRange
6235   // if the expression is increasing and will be decreased by Offset otherwise.
6236   // Maximum value of the final range will match the maximal value of StartRange
6237   // if the expression is decreasing and will be increased by Offset otherwise.
6238   APInt StartLower = StartRange.getLower();
6239   APInt StartUpper = StartRange.getUpper() - 1;
6240   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6241                                    : (StartUpper + std::move(Offset));
6242 
6243   // It's possible that the new minimum/maximum value will fall into the initial
6244   // range (due to wrap around). This means that the expression can take any
6245   // value in this bitwidth, and we have to return full range.
6246   if (StartRange.contains(MovedBoundary))
6247     return ConstantRange::getFull(BitWidth);
6248 
6249   APInt NewLower =
6250       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6251   APInt NewUpper =
6252       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6253   NewUpper += 1;
6254 
6255   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6256   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6257 }
6258 
6259 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6260                                                    const SCEV *Step,
6261                                                    const SCEV *MaxBECount,
6262                                                    unsigned BitWidth) {
6263   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6264          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6265          "Precondition!");
6266 
6267   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6268   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6269 
6270   // First, consider step signed.
6271   ConstantRange StartSRange = getSignedRange(Start);
6272   ConstantRange StepSRange = getSignedRange(Step);
6273 
6274   // If Step can be both positive and negative, we need to find ranges for the
6275   // maximum absolute step values in both directions and union them.
6276   ConstantRange SR =
6277       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6278                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6279   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6280                                               StartSRange, MaxBECountValue,
6281                                               BitWidth, /* Signed = */ true));
6282 
6283   // Next, consider step unsigned.
6284   ConstantRange UR = getRangeForAffineARHelper(
6285       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6286       MaxBECountValue, BitWidth, /* Signed = */ false);
6287 
6288   // Finally, intersect signed and unsigned ranges.
6289   return SR.intersectWith(UR, ConstantRange::Smallest);
6290 }
6291 
6292 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6293     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6294     ScalarEvolution::RangeSignHint SignHint) {
6295   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6296   assert(AddRec->hasNoSelfWrap() &&
6297          "This only works for non-self-wrapping AddRecs!");
6298   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6299   const SCEV *Step = AddRec->getStepRecurrence(*this);
6300   // Only deal with constant step to save compile time.
6301   if (!isa<SCEVConstant>(Step))
6302     return ConstantRange::getFull(BitWidth);
6303   // Let's make sure that we can prove that we do not self-wrap during
6304   // MaxBECount iterations. We need this because MaxBECount is a maximum
6305   // iteration count estimate, and we might infer nw from some exit for which we
6306   // do not know max exit count (or any other side reasoning).
6307   // TODO: Turn into assert at some point.
6308   if (getTypeSizeInBits(MaxBECount->getType()) >
6309       getTypeSizeInBits(AddRec->getType()))
6310     return ConstantRange::getFull(BitWidth);
6311   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6312   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6313   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6314   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6315   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6316                                          MaxItersWithoutWrap))
6317     return ConstantRange::getFull(BitWidth);
6318 
6319   ICmpInst::Predicate LEPred =
6320       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6321   ICmpInst::Predicate GEPred =
6322       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6323   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6324 
6325   // We know that there is no self-wrap. Let's take Start and End values and
6326   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6327   // the iteration. They either lie inside the range [Min(Start, End),
6328   // Max(Start, End)] or outside it:
6329   //
6330   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6331   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6332   //
6333   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6334   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6335   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6336   // Start <= End and step is positive, or Start >= End and step is negative.
6337   const SCEV *Start = AddRec->getStart();
6338   ConstantRange StartRange = getRangeRef(Start, SignHint);
6339   ConstantRange EndRange = getRangeRef(End, SignHint);
6340   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6341   // If they already cover full iteration space, we will know nothing useful
6342   // even if we prove what we want to prove.
6343   if (RangeBetween.isFullSet())
6344     return RangeBetween;
6345   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6346   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6347                                : RangeBetween.isWrappedSet();
6348   if (IsWrappedSet)
6349     return ConstantRange::getFull(BitWidth);
6350 
6351   if (isKnownPositive(Step) &&
6352       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6353     return RangeBetween;
6354   else if (isKnownNegative(Step) &&
6355            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6356     return RangeBetween;
6357   return ConstantRange::getFull(BitWidth);
6358 }
6359 
6360 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6361                                                     const SCEV *Step,
6362                                                     const SCEV *MaxBECount,
6363                                                     unsigned BitWidth) {
6364   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6365   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6366 
6367   struct SelectPattern {
6368     Value *Condition = nullptr;
6369     APInt TrueValue;
6370     APInt FalseValue;
6371 
6372     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6373                            const SCEV *S) {
6374       Optional<unsigned> CastOp;
6375       APInt Offset(BitWidth, 0);
6376 
6377       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6378              "Should be!");
6379 
6380       // Peel off a constant offset:
6381       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6382         // In the future we could consider being smarter here and handle
6383         // {Start+Step,+,Step} too.
6384         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6385           return;
6386 
6387         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6388         S = SA->getOperand(1);
6389       }
6390 
6391       // Peel off a cast operation
6392       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6393         CastOp = SCast->getSCEVType();
6394         S = SCast->getOperand();
6395       }
6396 
6397       using namespace llvm::PatternMatch;
6398 
6399       auto *SU = dyn_cast<SCEVUnknown>(S);
6400       const APInt *TrueVal, *FalseVal;
6401       if (!SU ||
6402           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6403                                           m_APInt(FalseVal)))) {
6404         Condition = nullptr;
6405         return;
6406       }
6407 
6408       TrueValue = *TrueVal;
6409       FalseValue = *FalseVal;
6410 
6411       // Re-apply the cast we peeled off earlier
6412       if (CastOp.hasValue())
6413         switch (*CastOp) {
6414         default:
6415           llvm_unreachable("Unknown SCEV cast type!");
6416 
6417         case scTruncate:
6418           TrueValue = TrueValue.trunc(BitWidth);
6419           FalseValue = FalseValue.trunc(BitWidth);
6420           break;
6421         case scZeroExtend:
6422           TrueValue = TrueValue.zext(BitWidth);
6423           FalseValue = FalseValue.zext(BitWidth);
6424           break;
6425         case scSignExtend:
6426           TrueValue = TrueValue.sext(BitWidth);
6427           FalseValue = FalseValue.sext(BitWidth);
6428           break;
6429         }
6430 
6431       // Re-apply the constant offset we peeled off earlier
6432       TrueValue += Offset;
6433       FalseValue += Offset;
6434     }
6435 
6436     bool isRecognized() { return Condition != nullptr; }
6437   };
6438 
6439   SelectPattern StartPattern(*this, BitWidth, Start);
6440   if (!StartPattern.isRecognized())
6441     return ConstantRange::getFull(BitWidth);
6442 
6443   SelectPattern StepPattern(*this, BitWidth, Step);
6444   if (!StepPattern.isRecognized())
6445     return ConstantRange::getFull(BitWidth);
6446 
6447   if (StartPattern.Condition != StepPattern.Condition) {
6448     // We don't handle this case today; but we could, by considering four
6449     // possibilities below instead of two. I'm not sure if there are cases where
6450     // that will help over what getRange already does, though.
6451     return ConstantRange::getFull(BitWidth);
6452   }
6453 
6454   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6455   // construct arbitrary general SCEV expressions here.  This function is called
6456   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6457   // say) can end up caching a suboptimal value.
6458 
6459   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6460   // C2352 and C2512 (otherwise it isn't needed).
6461 
6462   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6463   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6464   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6465   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6466 
6467   ConstantRange TrueRange =
6468       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6469   ConstantRange FalseRange =
6470       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6471 
6472   return TrueRange.unionWith(FalseRange);
6473 }
6474 
6475 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6476   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6477   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6478 
6479   // Return early if there are no flags to propagate to the SCEV.
6480   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6481   if (BinOp->hasNoUnsignedWrap())
6482     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6483   if (BinOp->hasNoSignedWrap())
6484     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6485   if (Flags == SCEV::FlagAnyWrap)
6486     return SCEV::FlagAnyWrap;
6487 
6488   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6489 }
6490 
6491 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6492   // Here we check that I is in the header of the innermost loop containing I,
6493   // since we only deal with instructions in the loop header. The actual loop we
6494   // need to check later will come from an add recurrence, but getting that
6495   // requires computing the SCEV of the operands, which can be expensive. This
6496   // check we can do cheaply to rule out some cases early.
6497   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6498   if (InnermostContainingLoop == nullptr ||
6499       InnermostContainingLoop->getHeader() != I->getParent())
6500     return false;
6501 
6502   // Only proceed if we can prove that I does not yield poison.
6503   if (!programUndefinedIfPoison(I))
6504     return false;
6505 
6506   // At this point we know that if I is executed, then it does not wrap
6507   // according to at least one of NSW or NUW. If I is not executed, then we do
6508   // not know if the calculation that I represents would wrap. Multiple
6509   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6510   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6511   // derived from other instructions that map to the same SCEV. We cannot make
6512   // that guarantee for cases where I is not executed. So we need to find the
6513   // loop that I is considered in relation to and prove that I is executed for
6514   // every iteration of that loop. That implies that the value that I
6515   // calculates does not wrap anywhere in the loop, so then we can apply the
6516   // flags to the SCEV.
6517   //
6518   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6519   // from different loops, so that we know which loop to prove that I is
6520   // executed in.
6521   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6522     // I could be an extractvalue from a call to an overflow intrinsic.
6523     // TODO: We can do better here in some cases.
6524     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6525       return false;
6526     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6527     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6528       bool AllOtherOpsLoopInvariant = true;
6529       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6530            ++OtherOpIndex) {
6531         if (OtherOpIndex != OpIndex) {
6532           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6533           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6534             AllOtherOpsLoopInvariant = false;
6535             break;
6536           }
6537         }
6538       }
6539       if (AllOtherOpsLoopInvariant &&
6540           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6541         return true;
6542     }
6543   }
6544   return false;
6545 }
6546 
6547 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6548   // If we know that \c I can never be poison period, then that's enough.
6549   if (isSCEVExprNeverPoison(I))
6550     return true;
6551 
6552   // For an add recurrence specifically, we assume that infinite loops without
6553   // side effects are undefined behavior, and then reason as follows:
6554   //
6555   // If the add recurrence is poison in any iteration, it is poison on all
6556   // future iterations (since incrementing poison yields poison). If the result
6557   // of the add recurrence is fed into the loop latch condition and the loop
6558   // does not contain any throws or exiting blocks other than the latch, we now
6559   // have the ability to "choose" whether the backedge is taken or not (by
6560   // choosing a sufficiently evil value for the poison feeding into the branch)
6561   // for every iteration including and after the one in which \p I first became
6562   // poison.  There are two possibilities (let's call the iteration in which \p
6563   // I first became poison as K):
6564   //
6565   //  1. In the set of iterations including and after K, the loop body executes
6566   //     no side effects.  In this case executing the backege an infinte number
6567   //     of times will yield undefined behavior.
6568   //
6569   //  2. In the set of iterations including and after K, the loop body executes
6570   //     at least one side effect.  In this case, that specific instance of side
6571   //     effect is control dependent on poison, which also yields undefined
6572   //     behavior.
6573 
6574   auto *ExitingBB = L->getExitingBlock();
6575   auto *LatchBB = L->getLoopLatch();
6576   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6577     return false;
6578 
6579   SmallPtrSet<const Instruction *, 16> Pushed;
6580   SmallVector<const Instruction *, 8> PoisonStack;
6581 
6582   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6583   // things that are known to be poison under that assumption go on the
6584   // PoisonStack.
6585   Pushed.insert(I);
6586   PoisonStack.push_back(I);
6587 
6588   bool LatchControlDependentOnPoison = false;
6589   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6590     const Instruction *Poison = PoisonStack.pop_back_val();
6591 
6592     for (auto *PoisonUser : Poison->users()) {
6593       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6594         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6595           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6596       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6597         assert(BI->isConditional() && "Only possibility!");
6598         if (BI->getParent() == LatchBB) {
6599           LatchControlDependentOnPoison = true;
6600           break;
6601         }
6602       }
6603     }
6604   }
6605 
6606   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6607 }
6608 
6609 ScalarEvolution::LoopProperties
6610 ScalarEvolution::getLoopProperties(const Loop *L) {
6611   using LoopProperties = ScalarEvolution::LoopProperties;
6612 
6613   auto Itr = LoopPropertiesCache.find(L);
6614   if (Itr == LoopPropertiesCache.end()) {
6615     auto HasSideEffects = [](Instruction *I) {
6616       if (auto *SI = dyn_cast<StoreInst>(I))
6617         return !SI->isSimple();
6618 
6619       return I->mayHaveSideEffects();
6620     };
6621 
6622     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6623                          /*HasNoSideEffects*/ true};
6624 
6625     for (auto *BB : L->getBlocks())
6626       for (auto &I : *BB) {
6627         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6628           LP.HasNoAbnormalExits = false;
6629         if (HasSideEffects(&I))
6630           LP.HasNoSideEffects = false;
6631         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6632           break; // We're already as pessimistic as we can get.
6633       }
6634 
6635     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6636     assert(InsertPair.second && "We just checked!");
6637     Itr = InsertPair.first;
6638   }
6639 
6640   return Itr->second;
6641 }
6642 
6643 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
6644   // A mustprogress loop without side effects must be finite.
6645   // TODO: The check used here is very conservative.  It's only *specific*
6646   // side effects which are well defined in infinite loops.
6647   return isMustProgress(L) && loopHasNoSideEffects(L);
6648 }
6649 
6650 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6651   if (!isSCEVable(V->getType()))
6652     return getUnknown(V);
6653 
6654   if (Instruction *I = dyn_cast<Instruction>(V)) {
6655     // Don't attempt to analyze instructions in blocks that aren't
6656     // reachable. Such instructions don't matter, and they aren't required
6657     // to obey basic rules for definitions dominating uses which this
6658     // analysis depends on.
6659     if (!DT.isReachableFromEntry(I->getParent()))
6660       return getUnknown(UndefValue::get(V->getType()));
6661   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6662     return getConstant(CI);
6663   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6664     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6665   else if (!isa<ConstantExpr>(V))
6666     return getUnknown(V);
6667 
6668   Operator *U = cast<Operator>(V);
6669   if (auto BO = MatchBinaryOp(U, DT)) {
6670     switch (BO->Opcode) {
6671     case Instruction::Add: {
6672       // The simple thing to do would be to just call getSCEV on both operands
6673       // and call getAddExpr with the result. However if we're looking at a
6674       // bunch of things all added together, this can be quite inefficient,
6675       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6676       // Instead, gather up all the operands and make a single getAddExpr call.
6677       // LLVM IR canonical form means we need only traverse the left operands.
6678       SmallVector<const SCEV *, 4> AddOps;
6679       do {
6680         if (BO->Op) {
6681           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6682             AddOps.push_back(OpSCEV);
6683             break;
6684           }
6685 
6686           // If a NUW or NSW flag can be applied to the SCEV for this
6687           // addition, then compute the SCEV for this addition by itself
6688           // with a separate call to getAddExpr. We need to do that
6689           // instead of pushing the operands of the addition onto AddOps,
6690           // since the flags are only known to apply to this particular
6691           // addition - they may not apply to other additions that can be
6692           // formed with operands from AddOps.
6693           const SCEV *RHS = getSCEV(BO->RHS);
6694           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6695           if (Flags != SCEV::FlagAnyWrap) {
6696             const SCEV *LHS = getSCEV(BO->LHS);
6697             if (BO->Opcode == Instruction::Sub)
6698               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6699             else
6700               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6701             break;
6702           }
6703         }
6704 
6705         if (BO->Opcode == Instruction::Sub)
6706           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6707         else
6708           AddOps.push_back(getSCEV(BO->RHS));
6709 
6710         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6711         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6712                        NewBO->Opcode != Instruction::Sub)) {
6713           AddOps.push_back(getSCEV(BO->LHS));
6714           break;
6715         }
6716         BO = NewBO;
6717       } while (true);
6718 
6719       return getAddExpr(AddOps);
6720     }
6721 
6722     case Instruction::Mul: {
6723       SmallVector<const SCEV *, 4> MulOps;
6724       do {
6725         if (BO->Op) {
6726           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6727             MulOps.push_back(OpSCEV);
6728             break;
6729           }
6730 
6731           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6732           if (Flags != SCEV::FlagAnyWrap) {
6733             MulOps.push_back(
6734                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6735             break;
6736           }
6737         }
6738 
6739         MulOps.push_back(getSCEV(BO->RHS));
6740         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6741         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6742           MulOps.push_back(getSCEV(BO->LHS));
6743           break;
6744         }
6745         BO = NewBO;
6746       } while (true);
6747 
6748       return getMulExpr(MulOps);
6749     }
6750     case Instruction::UDiv:
6751       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6752     case Instruction::URem:
6753       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6754     case Instruction::Sub: {
6755       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6756       if (BO->Op)
6757         Flags = getNoWrapFlagsFromUB(BO->Op);
6758       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6759     }
6760     case Instruction::And:
6761       // For an expression like x&255 that merely masks off the high bits,
6762       // use zext(trunc(x)) as the SCEV expression.
6763       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6764         if (CI->isZero())
6765           return getSCEV(BO->RHS);
6766         if (CI->isMinusOne())
6767           return getSCEV(BO->LHS);
6768         const APInt &A = CI->getValue();
6769 
6770         // Instcombine's ShrinkDemandedConstant may strip bits out of
6771         // constants, obscuring what would otherwise be a low-bits mask.
6772         // Use computeKnownBits to compute what ShrinkDemandedConstant
6773         // knew about to reconstruct a low-bits mask value.
6774         unsigned LZ = A.countLeadingZeros();
6775         unsigned TZ = A.countTrailingZeros();
6776         unsigned BitWidth = A.getBitWidth();
6777         KnownBits Known(BitWidth);
6778         computeKnownBits(BO->LHS, Known, getDataLayout(),
6779                          0, &AC, nullptr, &DT);
6780 
6781         APInt EffectiveMask =
6782             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6783         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6784           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6785           const SCEV *LHS = getSCEV(BO->LHS);
6786           const SCEV *ShiftedLHS = nullptr;
6787           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6788             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6789               // For an expression like (x * 8) & 8, simplify the multiply.
6790               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6791               unsigned GCD = std::min(MulZeros, TZ);
6792               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6793               SmallVector<const SCEV*, 4> MulOps;
6794               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6795               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6796               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6797               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6798             }
6799           }
6800           if (!ShiftedLHS)
6801             ShiftedLHS = getUDivExpr(LHS, MulCount);
6802           return getMulExpr(
6803               getZeroExtendExpr(
6804                   getTruncateExpr(ShiftedLHS,
6805                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6806                   BO->LHS->getType()),
6807               MulCount);
6808         }
6809       }
6810       break;
6811 
6812     case Instruction::Or:
6813       // If the RHS of the Or is a constant, we may have something like:
6814       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6815       // optimizations will transparently handle this case.
6816       //
6817       // In order for this transformation to be safe, the LHS must be of the
6818       // form X*(2^n) and the Or constant must be less than 2^n.
6819       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6820         const SCEV *LHS = getSCEV(BO->LHS);
6821         const APInt &CIVal = CI->getValue();
6822         if (GetMinTrailingZeros(LHS) >=
6823             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6824           // Build a plain add SCEV.
6825           return getAddExpr(LHS, getSCEV(CI),
6826                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6827         }
6828       }
6829       break;
6830 
6831     case Instruction::Xor:
6832       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6833         // If the RHS of xor is -1, then this is a not operation.
6834         if (CI->isMinusOne())
6835           return getNotSCEV(getSCEV(BO->LHS));
6836 
6837         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6838         // This is a variant of the check for xor with -1, and it handles
6839         // the case where instcombine has trimmed non-demanded bits out
6840         // of an xor with -1.
6841         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6842           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6843             if (LBO->getOpcode() == Instruction::And &&
6844                 LCI->getValue() == CI->getValue())
6845               if (const SCEVZeroExtendExpr *Z =
6846                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6847                 Type *UTy = BO->LHS->getType();
6848                 const SCEV *Z0 = Z->getOperand();
6849                 Type *Z0Ty = Z0->getType();
6850                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6851 
6852                 // If C is a low-bits mask, the zero extend is serving to
6853                 // mask off the high bits. Complement the operand and
6854                 // re-apply the zext.
6855                 if (CI->getValue().isMask(Z0TySize))
6856                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6857 
6858                 // If C is a single bit, it may be in the sign-bit position
6859                 // before the zero-extend. In this case, represent the xor
6860                 // using an add, which is equivalent, and re-apply the zext.
6861                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6862                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6863                     Trunc.isSignMask())
6864                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6865                                            UTy);
6866               }
6867       }
6868       break;
6869 
6870     case Instruction::Shl:
6871       // Turn shift left of a constant amount into a multiply.
6872       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6873         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6874 
6875         // If the shift count is not less than the bitwidth, the result of
6876         // the shift is undefined. Don't try to analyze it, because the
6877         // resolution chosen here may differ from the resolution chosen in
6878         // other parts of the compiler.
6879         if (SA->getValue().uge(BitWidth))
6880           break;
6881 
6882         // We can safely preserve the nuw flag in all cases. It's also safe to
6883         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6884         // requires special handling. It can be preserved as long as we're not
6885         // left shifting by bitwidth - 1.
6886         auto Flags = SCEV::FlagAnyWrap;
6887         if (BO->Op) {
6888           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6889           if ((MulFlags & SCEV::FlagNSW) &&
6890               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6891             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6892           if (MulFlags & SCEV::FlagNUW)
6893             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6894         }
6895 
6896         Constant *X = ConstantInt::get(
6897             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6898         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6899       }
6900       break;
6901 
6902     case Instruction::AShr: {
6903       // AShr X, C, where C is a constant.
6904       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6905       if (!CI)
6906         break;
6907 
6908       Type *OuterTy = BO->LHS->getType();
6909       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6910       // If the shift count is not less than the bitwidth, the result of
6911       // the shift is undefined. Don't try to analyze it, because the
6912       // resolution chosen here may differ from the resolution chosen in
6913       // other parts of the compiler.
6914       if (CI->getValue().uge(BitWidth))
6915         break;
6916 
6917       if (CI->isZero())
6918         return getSCEV(BO->LHS); // shift by zero --> noop
6919 
6920       uint64_t AShrAmt = CI->getZExtValue();
6921       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6922 
6923       Operator *L = dyn_cast<Operator>(BO->LHS);
6924       if (L && L->getOpcode() == Instruction::Shl) {
6925         // X = Shl A, n
6926         // Y = AShr X, m
6927         // Both n and m are constant.
6928 
6929         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6930         if (L->getOperand(1) == BO->RHS)
6931           // For a two-shift sext-inreg, i.e. n = m,
6932           // use sext(trunc(x)) as the SCEV expression.
6933           return getSignExtendExpr(
6934               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6935 
6936         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6937         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6938           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6939           if (ShlAmt > AShrAmt) {
6940             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6941             // expression. We already checked that ShlAmt < BitWidth, so
6942             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6943             // ShlAmt - AShrAmt < Amt.
6944             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6945                                             ShlAmt - AShrAmt);
6946             return getSignExtendExpr(
6947                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6948                 getConstant(Mul)), OuterTy);
6949           }
6950         }
6951       }
6952       break;
6953     }
6954     }
6955   }
6956 
6957   switch (U->getOpcode()) {
6958   case Instruction::Trunc:
6959     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6960 
6961   case Instruction::ZExt:
6962     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6963 
6964   case Instruction::SExt:
6965     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6966       // The NSW flag of a subtract does not always survive the conversion to
6967       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6968       // more likely to preserve NSW and allow later AddRec optimisations.
6969       //
6970       // NOTE: This is effectively duplicating this logic from getSignExtend:
6971       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6972       // but by that point the NSW information has potentially been lost.
6973       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6974         Type *Ty = U->getType();
6975         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6976         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6977         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6978       }
6979     }
6980     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6981 
6982   case Instruction::BitCast:
6983     // BitCasts are no-op casts so we just eliminate the cast.
6984     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6985       return getSCEV(U->getOperand(0));
6986     break;
6987 
6988   case Instruction::PtrToInt: {
6989     // Pointer to integer cast is straight-forward, so do model it.
6990     const SCEV *Op = getSCEV(U->getOperand(0));
6991     Type *DstIntTy = U->getType();
6992     // But only if effective SCEV (integer) type is wide enough to represent
6993     // all possible pointer values.
6994     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
6995     if (isa<SCEVCouldNotCompute>(IntOp))
6996       return getUnknown(V);
6997     return IntOp;
6998   }
6999   case Instruction::IntToPtr:
7000     // Just don't deal with inttoptr casts.
7001     return getUnknown(V);
7002 
7003   case Instruction::SDiv:
7004     // If both operands are non-negative, this is just an udiv.
7005     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7006         isKnownNonNegative(getSCEV(U->getOperand(1))))
7007       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7008     break;
7009 
7010   case Instruction::SRem:
7011     // If both operands are non-negative, this is just an urem.
7012     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7013         isKnownNonNegative(getSCEV(U->getOperand(1))))
7014       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7015     break;
7016 
7017   case Instruction::GetElementPtr:
7018     return createNodeForGEP(cast<GEPOperator>(U));
7019 
7020   case Instruction::PHI:
7021     return createNodeForPHI(cast<PHINode>(U));
7022 
7023   case Instruction::Select:
7024     // U can also be a select constant expr, which let fall through.  Since
7025     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
7026     // constant expressions cannot have instructions as operands, we'd have
7027     // returned getUnknown for a select constant expressions anyway.
7028     if (isa<Instruction>(U))
7029       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
7030                                       U->getOperand(1), U->getOperand(2));
7031     break;
7032 
7033   case Instruction::Call:
7034   case Instruction::Invoke:
7035     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7036       return getSCEV(RV);
7037 
7038     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7039       switch (II->getIntrinsicID()) {
7040       case Intrinsic::abs:
7041         return getAbsExpr(
7042             getSCEV(II->getArgOperand(0)),
7043             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7044       case Intrinsic::umax:
7045         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7046                            getSCEV(II->getArgOperand(1)));
7047       case Intrinsic::umin:
7048         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7049                            getSCEV(II->getArgOperand(1)));
7050       case Intrinsic::smax:
7051         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7052                            getSCEV(II->getArgOperand(1)));
7053       case Intrinsic::smin:
7054         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7055                            getSCEV(II->getArgOperand(1)));
7056       case Intrinsic::usub_sat: {
7057         const SCEV *X = getSCEV(II->getArgOperand(0));
7058         const SCEV *Y = getSCEV(II->getArgOperand(1));
7059         const SCEV *ClampedY = getUMinExpr(X, Y);
7060         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7061       }
7062       case Intrinsic::uadd_sat: {
7063         const SCEV *X = getSCEV(II->getArgOperand(0));
7064         const SCEV *Y = getSCEV(II->getArgOperand(1));
7065         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7066         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7067       }
7068       case Intrinsic::start_loop_iterations:
7069         // A start_loop_iterations is just equivalent to the first operand for
7070         // SCEV purposes.
7071         return getSCEV(II->getArgOperand(0));
7072       default:
7073         break;
7074       }
7075     }
7076     break;
7077   }
7078 
7079   return getUnknown(V);
7080 }
7081 
7082 //===----------------------------------------------------------------------===//
7083 //                   Iteration Count Computation Code
7084 //
7085 
7086 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
7087   // Get the trip count from the BE count by adding 1.  Overflow, results
7088   // in zero which means "unknown".
7089   return getAddExpr(ExitCount, getOne(ExitCount->getType()));
7090 }
7091 
7092 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7093   if (!ExitCount)
7094     return 0;
7095 
7096   ConstantInt *ExitConst = ExitCount->getValue();
7097 
7098   // Guard against huge trip counts.
7099   if (ExitConst->getValue().getActiveBits() > 32)
7100     return 0;
7101 
7102   // In case of integer overflow, this returns 0, which is correct.
7103   return ((unsigned)ExitConst->getZExtValue()) + 1;
7104 }
7105 
7106 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7107   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7108   return getConstantTripCount(ExitCount);
7109 }
7110 
7111 unsigned
7112 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7113                                            const BasicBlock *ExitingBlock) {
7114   assert(ExitingBlock && "Must pass a non-null exiting block!");
7115   assert(L->isLoopExiting(ExitingBlock) &&
7116          "Exiting block must actually branch out of the loop!");
7117   const SCEVConstant *ExitCount =
7118       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7119   return getConstantTripCount(ExitCount);
7120 }
7121 
7122 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7123   const auto *MaxExitCount =
7124       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7125   return getConstantTripCount(MaxExitCount);
7126 }
7127 
7128 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7129   SmallVector<BasicBlock *, 8> ExitingBlocks;
7130   L->getExitingBlocks(ExitingBlocks);
7131 
7132   Optional<unsigned> Res = None;
7133   for (auto *ExitingBB : ExitingBlocks) {
7134     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7135     if (!Res)
7136       Res = Multiple;
7137     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7138   }
7139   return Res.getValueOr(1);
7140 }
7141 
7142 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7143                                                        const SCEV *ExitCount) {
7144   if (ExitCount == getCouldNotCompute())
7145     return 1;
7146 
7147   // Get the trip count
7148   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7149 
7150   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7151   if (!TC)
7152     // Attempt to factor more general cases. Returns the greatest power of
7153     // two divisor. If overflow happens, the trip count expression is still
7154     // divisible by the greatest power of 2 divisor returned.
7155     return 1U << std::min((uint32_t)31,
7156                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7157 
7158   ConstantInt *Result = TC->getValue();
7159 
7160   // Guard against huge trip counts (this requires checking
7161   // for zero to handle the case where the trip count == -1 and the
7162   // addition wraps).
7163   if (!Result || Result->getValue().getActiveBits() > 32 ||
7164       Result->getValue().getActiveBits() == 0)
7165     return 1;
7166 
7167   return (unsigned)Result->getZExtValue();
7168 }
7169 
7170 /// Returns the largest constant divisor of the trip count of this loop as a
7171 /// normal unsigned value, if possible. This means that the actual trip count is
7172 /// always a multiple of the returned value (don't forget the trip count could
7173 /// very well be zero as well!).
7174 ///
7175 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7176 /// multiple of a constant (which is also the case if the trip count is simply
7177 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7178 /// if the trip count is very large (>= 2^32).
7179 ///
7180 /// As explained in the comments for getSmallConstantTripCount, this assumes
7181 /// that control exits the loop via ExitingBlock.
7182 unsigned
7183 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7184                                               const BasicBlock *ExitingBlock) {
7185   assert(ExitingBlock && "Must pass a non-null exiting block!");
7186   assert(L->isLoopExiting(ExitingBlock) &&
7187          "Exiting block must actually branch out of the loop!");
7188   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7189   return getSmallConstantTripMultiple(L, ExitCount);
7190 }
7191 
7192 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7193                                           const BasicBlock *ExitingBlock,
7194                                           ExitCountKind Kind) {
7195   switch (Kind) {
7196   case Exact:
7197   case SymbolicMaximum:
7198     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7199   case ConstantMaximum:
7200     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7201   };
7202   llvm_unreachable("Invalid ExitCountKind!");
7203 }
7204 
7205 const SCEV *
7206 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7207                                                  SCEVUnionPredicate &Preds) {
7208   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7209 }
7210 
7211 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7212                                                    ExitCountKind Kind) {
7213   switch (Kind) {
7214   case Exact:
7215     return getBackedgeTakenInfo(L).getExact(L, this);
7216   case ConstantMaximum:
7217     return getBackedgeTakenInfo(L).getConstantMax(this);
7218   case SymbolicMaximum:
7219     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7220   };
7221   llvm_unreachable("Invalid ExitCountKind!");
7222 }
7223 
7224 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7225   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7226 }
7227 
7228 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7229 static void
7230 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
7231   BasicBlock *Header = L->getHeader();
7232 
7233   // Push all Loop-header PHIs onto the Worklist stack.
7234   for (PHINode &PN : Header->phis())
7235     Worklist.push_back(&PN);
7236 }
7237 
7238 const ScalarEvolution::BackedgeTakenInfo &
7239 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7240   auto &BTI = getBackedgeTakenInfo(L);
7241   if (BTI.hasFullInfo())
7242     return BTI;
7243 
7244   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7245 
7246   if (!Pair.second)
7247     return Pair.first->second;
7248 
7249   BackedgeTakenInfo Result =
7250       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7251 
7252   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7253 }
7254 
7255 ScalarEvolution::BackedgeTakenInfo &
7256 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7257   // Initially insert an invalid entry for this loop. If the insertion
7258   // succeeds, proceed to actually compute a backedge-taken count and
7259   // update the value. The temporary CouldNotCompute value tells SCEV
7260   // code elsewhere that it shouldn't attempt to request a new
7261   // backedge-taken count, which could result in infinite recursion.
7262   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7263       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7264   if (!Pair.second)
7265     return Pair.first->second;
7266 
7267   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7268   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7269   // must be cleared in this scope.
7270   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7271 
7272   // In product build, there are no usage of statistic.
7273   (void)NumTripCountsComputed;
7274   (void)NumTripCountsNotComputed;
7275 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7276   const SCEV *BEExact = Result.getExact(L, this);
7277   if (BEExact != getCouldNotCompute()) {
7278     assert(isLoopInvariant(BEExact, L) &&
7279            isLoopInvariant(Result.getConstantMax(this), L) &&
7280            "Computed backedge-taken count isn't loop invariant for loop!");
7281     ++NumTripCountsComputed;
7282   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7283              isa<PHINode>(L->getHeader()->begin())) {
7284     // Only count loops that have phi nodes as not being computable.
7285     ++NumTripCountsNotComputed;
7286   }
7287 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7288 
7289   // Now that we know more about the trip count for this loop, forget any
7290   // existing SCEV values for PHI nodes in this loop since they are only
7291   // conservative estimates made without the benefit of trip count
7292   // information. This is similar to the code in forgetLoop, except that
7293   // it handles SCEVUnknown PHI nodes specially.
7294   if (Result.hasAnyInfo()) {
7295     SmallVector<Instruction *, 16> Worklist;
7296     PushLoopPHIs(L, Worklist);
7297 
7298     SmallPtrSet<Instruction *, 8> Discovered;
7299     while (!Worklist.empty()) {
7300       Instruction *I = Worklist.pop_back_val();
7301 
7302       ValueExprMapType::iterator It =
7303         ValueExprMap.find_as(static_cast<Value *>(I));
7304       if (It != ValueExprMap.end()) {
7305         const SCEV *Old = It->second;
7306 
7307         // SCEVUnknown for a PHI either means that it has an unrecognized
7308         // structure, or it's a PHI that's in the progress of being computed
7309         // by createNodeForPHI.  In the former case, additional loop trip
7310         // count information isn't going to change anything. In the later
7311         // case, createNodeForPHI will perform the necessary updates on its
7312         // own when it gets to that point.
7313         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7314           eraseValueFromMap(It->first);
7315           forgetMemoizedResults(Old);
7316         }
7317         if (PHINode *PN = dyn_cast<PHINode>(I))
7318           ConstantEvolutionLoopExitValue.erase(PN);
7319       }
7320 
7321       // Since we don't need to invalidate anything for correctness and we're
7322       // only invalidating to make SCEV's results more precise, we get to stop
7323       // early to avoid invalidating too much.  This is especially important in
7324       // cases like:
7325       //
7326       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7327       // loop0:
7328       //   %pn0 = phi
7329       //   ...
7330       // loop1:
7331       //   %pn1 = phi
7332       //   ...
7333       //
7334       // where both loop0 and loop1's backedge taken count uses the SCEV
7335       // expression for %v.  If we don't have the early stop below then in cases
7336       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7337       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7338       // count for loop1, effectively nullifying SCEV's trip count cache.
7339       for (auto *U : I->users())
7340         if (auto *I = dyn_cast<Instruction>(U)) {
7341           auto *LoopForUser = LI.getLoopFor(I->getParent());
7342           if (LoopForUser && L->contains(LoopForUser) &&
7343               Discovered.insert(I).second)
7344             Worklist.push_back(I);
7345         }
7346     }
7347   }
7348 
7349   // Re-lookup the insert position, since the call to
7350   // computeBackedgeTakenCount above could result in a
7351   // recusive call to getBackedgeTakenInfo (on a different
7352   // loop), which would invalidate the iterator computed
7353   // earlier.
7354   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7355 }
7356 
7357 void ScalarEvolution::forgetAllLoops() {
7358   // This method is intended to forget all info about loops. It should
7359   // invalidate caches as if the following happened:
7360   // - The trip counts of all loops have changed arbitrarily
7361   // - Every llvm::Value has been updated in place to produce a different
7362   // result.
7363   BackedgeTakenCounts.clear();
7364   PredicatedBackedgeTakenCounts.clear();
7365   LoopPropertiesCache.clear();
7366   ConstantEvolutionLoopExitValue.clear();
7367   ValueExprMap.clear();
7368   ValuesAtScopes.clear();
7369   LoopDispositions.clear();
7370   BlockDispositions.clear();
7371   UnsignedRanges.clear();
7372   SignedRanges.clear();
7373   ExprValueMap.clear();
7374   HasRecMap.clear();
7375   MinTrailingZerosCache.clear();
7376   PredicatedSCEVRewrites.clear();
7377 }
7378 
7379 void ScalarEvolution::forgetLoop(const Loop *L) {
7380   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7381   SmallVector<Instruction *, 32> Worklist;
7382   SmallPtrSet<Instruction *, 16> Visited;
7383 
7384   // Iterate over all the loops and sub-loops to drop SCEV information.
7385   while (!LoopWorklist.empty()) {
7386     auto *CurrL = LoopWorklist.pop_back_val();
7387 
7388     // Drop any stored trip count value.
7389     BackedgeTakenCounts.erase(CurrL);
7390     PredicatedBackedgeTakenCounts.erase(CurrL);
7391 
7392     // Drop information about predicated SCEV rewrites for this loop.
7393     for (auto I = PredicatedSCEVRewrites.begin();
7394          I != PredicatedSCEVRewrites.end();) {
7395       std::pair<const SCEV *, const Loop *> Entry = I->first;
7396       if (Entry.second == CurrL)
7397         PredicatedSCEVRewrites.erase(I++);
7398       else
7399         ++I;
7400     }
7401 
7402     auto LoopUsersItr = LoopUsers.find(CurrL);
7403     if (LoopUsersItr != LoopUsers.end()) {
7404       for (auto *S : LoopUsersItr->second)
7405         forgetMemoizedResults(S);
7406       LoopUsers.erase(LoopUsersItr);
7407     }
7408 
7409     // Drop information about expressions based on loop-header PHIs.
7410     PushLoopPHIs(CurrL, Worklist);
7411 
7412     while (!Worklist.empty()) {
7413       Instruction *I = Worklist.pop_back_val();
7414       if (!Visited.insert(I).second)
7415         continue;
7416 
7417       ValueExprMapType::iterator It =
7418           ValueExprMap.find_as(static_cast<Value *>(I));
7419       if (It != ValueExprMap.end()) {
7420         eraseValueFromMap(It->first);
7421         forgetMemoizedResults(It->second);
7422         if (PHINode *PN = dyn_cast<PHINode>(I))
7423           ConstantEvolutionLoopExitValue.erase(PN);
7424       }
7425 
7426       PushDefUseChildren(I, Worklist);
7427     }
7428 
7429     LoopPropertiesCache.erase(CurrL);
7430     // Forget all contained loops too, to avoid dangling entries in the
7431     // ValuesAtScopes map.
7432     LoopWorklist.append(CurrL->begin(), CurrL->end());
7433   }
7434 }
7435 
7436 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7437   while (Loop *Parent = L->getParentLoop())
7438     L = Parent;
7439   forgetLoop(L);
7440 }
7441 
7442 void ScalarEvolution::forgetValue(Value *V) {
7443   Instruction *I = dyn_cast<Instruction>(V);
7444   if (!I) return;
7445 
7446   // Drop information about expressions based on loop-header PHIs.
7447   SmallVector<Instruction *, 16> Worklist;
7448   Worklist.push_back(I);
7449 
7450   SmallPtrSet<Instruction *, 8> Visited;
7451   while (!Worklist.empty()) {
7452     I = Worklist.pop_back_val();
7453     if (!Visited.insert(I).second)
7454       continue;
7455 
7456     ValueExprMapType::iterator It =
7457       ValueExprMap.find_as(static_cast<Value *>(I));
7458     if (It != ValueExprMap.end()) {
7459       eraseValueFromMap(It->first);
7460       forgetMemoizedResults(It->second);
7461       if (PHINode *PN = dyn_cast<PHINode>(I))
7462         ConstantEvolutionLoopExitValue.erase(PN);
7463     }
7464 
7465     PushDefUseChildren(I, Worklist);
7466   }
7467 }
7468 
7469 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7470   LoopDispositions.clear();
7471 }
7472 
7473 /// Get the exact loop backedge taken count considering all loop exits. A
7474 /// computable result can only be returned for loops with all exiting blocks
7475 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7476 /// is never skipped. This is a valid assumption as long as the loop exits via
7477 /// that test. For precise results, it is the caller's responsibility to specify
7478 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7479 const SCEV *
7480 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7481                                              SCEVUnionPredicate *Preds) const {
7482   // If any exits were not computable, the loop is not computable.
7483   if (!isComplete() || ExitNotTaken.empty())
7484     return SE->getCouldNotCompute();
7485 
7486   const BasicBlock *Latch = L->getLoopLatch();
7487   // All exiting blocks we have collected must dominate the only backedge.
7488   if (!Latch)
7489     return SE->getCouldNotCompute();
7490 
7491   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7492   // count is simply a minimum out of all these calculated exit counts.
7493   SmallVector<const SCEV *, 2> Ops;
7494   for (auto &ENT : ExitNotTaken) {
7495     const SCEV *BECount = ENT.ExactNotTaken;
7496     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7497     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7498            "We should only have known counts for exiting blocks that dominate "
7499            "latch!");
7500 
7501     Ops.push_back(BECount);
7502 
7503     if (Preds && !ENT.hasAlwaysTruePredicate())
7504       Preds->add(ENT.Predicate.get());
7505 
7506     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7507            "Predicate should be always true!");
7508   }
7509 
7510   return SE->getUMinFromMismatchedTypes(Ops);
7511 }
7512 
7513 /// Get the exact not taken count for this loop exit.
7514 const SCEV *
7515 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7516                                              ScalarEvolution *SE) const {
7517   for (auto &ENT : ExitNotTaken)
7518     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7519       return ENT.ExactNotTaken;
7520 
7521   return SE->getCouldNotCompute();
7522 }
7523 
7524 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7525     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7526   for (auto &ENT : ExitNotTaken)
7527     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7528       return ENT.MaxNotTaken;
7529 
7530   return SE->getCouldNotCompute();
7531 }
7532 
7533 /// getConstantMax - Get the constant max backedge taken count for the loop.
7534 const SCEV *
7535 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7536   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7537     return !ENT.hasAlwaysTruePredicate();
7538   };
7539 
7540   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7541     return SE->getCouldNotCompute();
7542 
7543   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7544           isa<SCEVConstant>(getConstantMax())) &&
7545          "No point in having a non-constant max backedge taken count!");
7546   return getConstantMax();
7547 }
7548 
7549 const SCEV *
7550 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7551                                                    ScalarEvolution *SE) {
7552   if (!SymbolicMax)
7553     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7554   return SymbolicMax;
7555 }
7556 
7557 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7558     ScalarEvolution *SE) const {
7559   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7560     return !ENT.hasAlwaysTruePredicate();
7561   };
7562   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7563 }
7564 
7565 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const {
7566   return Operands.contains(S);
7567 }
7568 
7569 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7570     : ExitLimit(E, E, false, None) {
7571 }
7572 
7573 ScalarEvolution::ExitLimit::ExitLimit(
7574     const SCEV *E, const SCEV *M, bool MaxOrZero,
7575     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7576     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7577   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7578           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7579          "Exact is not allowed to be less precise than Max");
7580   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7581           isa<SCEVConstant>(MaxNotTaken)) &&
7582          "No point in having a non-constant max backedge taken count!");
7583   for (auto *PredSet : PredSetList)
7584     for (auto *P : *PredSet)
7585       addPredicate(P);
7586   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
7587          "Backedge count should be int");
7588   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
7589          "Max backedge count should be int");
7590 }
7591 
7592 ScalarEvolution::ExitLimit::ExitLimit(
7593     const SCEV *E, const SCEV *M, bool MaxOrZero,
7594     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7595     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7596 }
7597 
7598 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7599                                       bool MaxOrZero)
7600     : ExitLimit(E, M, MaxOrZero, None) {
7601 }
7602 
7603 class SCEVRecordOperands {
7604   SmallPtrSetImpl<const SCEV *> &Operands;
7605 
7606 public:
7607   SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands)
7608     : Operands(Operands) {}
7609   bool follow(const SCEV *S) {
7610     Operands.insert(S);
7611     return true;
7612   }
7613   bool isDone() { return false; }
7614 };
7615 
7616 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7617 /// computable exit into a persistent ExitNotTakenInfo array.
7618 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7619     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7620     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7621     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7622   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7623 
7624   ExitNotTaken.reserve(ExitCounts.size());
7625   std::transform(
7626       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7627       [&](const EdgeExitInfo &EEI) {
7628         BasicBlock *ExitBB = EEI.first;
7629         const ExitLimit &EL = EEI.second;
7630         if (EL.Predicates.empty())
7631           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7632                                   nullptr);
7633 
7634         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7635         for (auto *Pred : EL.Predicates)
7636           Predicate->add(Pred);
7637 
7638         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7639                                 std::move(Predicate));
7640       });
7641   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7642           isa<SCEVConstant>(ConstantMax)) &&
7643          "No point in having a non-constant max backedge taken count!");
7644 
7645   SCEVRecordOperands RecordOperands(Operands);
7646   SCEVTraversal<SCEVRecordOperands> ST(RecordOperands);
7647   if (!isa<SCEVCouldNotCompute>(ConstantMax))
7648     ST.visitAll(ConstantMax);
7649   for (auto &ENT : ExitNotTaken)
7650     if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken))
7651       ST.visitAll(ENT.ExactNotTaken);
7652 }
7653 
7654 /// Compute the number of times the backedge of the specified loop will execute.
7655 ScalarEvolution::BackedgeTakenInfo
7656 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7657                                            bool AllowPredicates) {
7658   SmallVector<BasicBlock *, 8> ExitingBlocks;
7659   L->getExitingBlocks(ExitingBlocks);
7660 
7661   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7662 
7663   SmallVector<EdgeExitInfo, 4> ExitCounts;
7664   bool CouldComputeBECount = true;
7665   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7666   const SCEV *MustExitMaxBECount = nullptr;
7667   const SCEV *MayExitMaxBECount = nullptr;
7668   bool MustExitMaxOrZero = false;
7669 
7670   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7671   // and compute maxBECount.
7672   // Do a union of all the predicates here.
7673   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7674     BasicBlock *ExitBB = ExitingBlocks[i];
7675 
7676     // We canonicalize untaken exits to br (constant), ignore them so that
7677     // proving an exit untaken doesn't negatively impact our ability to reason
7678     // about the loop as whole.
7679     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7680       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7681         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7682         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7683           continue;
7684       }
7685 
7686     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7687 
7688     assert((AllowPredicates || EL.Predicates.empty()) &&
7689            "Predicated exit limit when predicates are not allowed!");
7690 
7691     // 1. For each exit that can be computed, add an entry to ExitCounts.
7692     // CouldComputeBECount is true only if all exits can be computed.
7693     if (EL.ExactNotTaken == getCouldNotCompute())
7694       // We couldn't compute an exact value for this exit, so
7695       // we won't be able to compute an exact value for the loop.
7696       CouldComputeBECount = false;
7697     else
7698       ExitCounts.emplace_back(ExitBB, EL);
7699 
7700     // 2. Derive the loop's MaxBECount from each exit's max number of
7701     // non-exiting iterations. Partition the loop exits into two kinds:
7702     // LoopMustExits and LoopMayExits.
7703     //
7704     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7705     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7706     // MaxBECount is the minimum EL.MaxNotTaken of computable
7707     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7708     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7709     // computable EL.MaxNotTaken.
7710     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7711         DT.dominates(ExitBB, Latch)) {
7712       if (!MustExitMaxBECount) {
7713         MustExitMaxBECount = EL.MaxNotTaken;
7714         MustExitMaxOrZero = EL.MaxOrZero;
7715       } else {
7716         MustExitMaxBECount =
7717             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7718       }
7719     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7720       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7721         MayExitMaxBECount = EL.MaxNotTaken;
7722       else {
7723         MayExitMaxBECount =
7724             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7725       }
7726     }
7727   }
7728   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7729     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7730   // The loop backedge will be taken the maximum or zero times if there's
7731   // a single exit that must be taken the maximum or zero times.
7732   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7733   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7734                            MaxBECount, MaxOrZero);
7735 }
7736 
7737 ScalarEvolution::ExitLimit
7738 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7739                                       bool AllowPredicates) {
7740   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7741   // If our exiting block does not dominate the latch, then its connection with
7742   // loop's exit limit may be far from trivial.
7743   const BasicBlock *Latch = L->getLoopLatch();
7744   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7745     return getCouldNotCompute();
7746 
7747   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7748   Instruction *Term = ExitingBlock->getTerminator();
7749   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7750     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7751     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7752     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7753            "It should have one successor in loop and one exit block!");
7754     // Proceed to the next level to examine the exit condition expression.
7755     return computeExitLimitFromCond(
7756         L, BI->getCondition(), ExitIfTrue,
7757         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7758   }
7759 
7760   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7761     // For switch, make sure that there is a single exit from the loop.
7762     BasicBlock *Exit = nullptr;
7763     for (auto *SBB : successors(ExitingBlock))
7764       if (!L->contains(SBB)) {
7765         if (Exit) // Multiple exit successors.
7766           return getCouldNotCompute();
7767         Exit = SBB;
7768       }
7769     assert(Exit && "Exiting block must have at least one exit");
7770     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7771                                                 /*ControlsExit=*/IsOnlyExit);
7772   }
7773 
7774   return getCouldNotCompute();
7775 }
7776 
7777 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7778     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7779     bool ControlsExit, bool AllowPredicates) {
7780   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7781   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7782                                         ControlsExit, AllowPredicates);
7783 }
7784 
7785 Optional<ScalarEvolution::ExitLimit>
7786 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7787                                       bool ExitIfTrue, bool ControlsExit,
7788                                       bool AllowPredicates) {
7789   (void)this->L;
7790   (void)this->ExitIfTrue;
7791   (void)this->AllowPredicates;
7792 
7793   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7794          this->AllowPredicates == AllowPredicates &&
7795          "Variance in assumed invariant key components!");
7796   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7797   if (Itr == TripCountMap.end())
7798     return None;
7799   return Itr->second;
7800 }
7801 
7802 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7803                                              bool ExitIfTrue,
7804                                              bool ControlsExit,
7805                                              bool AllowPredicates,
7806                                              const ExitLimit &EL) {
7807   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7808          this->AllowPredicates == AllowPredicates &&
7809          "Variance in assumed invariant key components!");
7810 
7811   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7812   assert(InsertResult.second && "Expected successful insertion!");
7813   (void)InsertResult;
7814   (void)ExitIfTrue;
7815 }
7816 
7817 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7818     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7819     bool ControlsExit, bool AllowPredicates) {
7820 
7821   if (auto MaybeEL =
7822           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7823     return *MaybeEL;
7824 
7825   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7826                                               ControlsExit, AllowPredicates);
7827   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7828   return EL;
7829 }
7830 
7831 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7832     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7833     bool ControlsExit, bool AllowPredicates) {
7834   // Handle BinOp conditions (And, Or).
7835   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7836           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7837     return *LimitFromBinOp;
7838 
7839   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7840   // Proceed to the next level to examine the icmp.
7841   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7842     ExitLimit EL =
7843         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7844     if (EL.hasFullInfo() || !AllowPredicates)
7845       return EL;
7846 
7847     // Try again, but use SCEV predicates this time.
7848     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7849                                     /*AllowPredicates=*/true);
7850   }
7851 
7852   // Check for a constant condition. These are normally stripped out by
7853   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7854   // preserve the CFG and is temporarily leaving constant conditions
7855   // in place.
7856   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7857     if (ExitIfTrue == !CI->getZExtValue())
7858       // The backedge is always taken.
7859       return getCouldNotCompute();
7860     else
7861       // The backedge is never taken.
7862       return getZero(CI->getType());
7863   }
7864 
7865   // If it's not an integer or pointer comparison then compute it the hard way.
7866   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7867 }
7868 
7869 Optional<ScalarEvolution::ExitLimit>
7870 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7871     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7872     bool ControlsExit, bool AllowPredicates) {
7873   // Check if the controlling expression for this loop is an And or Or.
7874   Value *Op0, *Op1;
7875   bool IsAnd = false;
7876   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7877     IsAnd = true;
7878   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7879     IsAnd = false;
7880   else
7881     return None;
7882 
7883   // EitherMayExit is true in these two cases:
7884   //   br (and Op0 Op1), loop, exit
7885   //   br (or  Op0 Op1), exit, loop
7886   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7887   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7888                                                  ControlsExit && !EitherMayExit,
7889                                                  AllowPredicates);
7890   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7891                                                  ControlsExit && !EitherMayExit,
7892                                                  AllowPredicates);
7893 
7894   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7895   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7896   if (isa<ConstantInt>(Op1))
7897     return Op1 == NeutralElement ? EL0 : EL1;
7898   if (isa<ConstantInt>(Op0))
7899     return Op0 == NeutralElement ? EL1 : EL0;
7900 
7901   const SCEV *BECount = getCouldNotCompute();
7902   const SCEV *MaxBECount = getCouldNotCompute();
7903   if (EitherMayExit) {
7904     // Both conditions must be same for the loop to continue executing.
7905     // Choose the less conservative count.
7906     // If ExitCond is a short-circuit form (select), using
7907     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7908     // To see the detailed examples, please see
7909     // test/Analysis/ScalarEvolution/exit-count-select.ll
7910     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7911     if (!PoisonSafe)
7912       // Even if ExitCond is select, we can safely derive BECount using both
7913       // EL0 and EL1 in these cases:
7914       // (1) EL0.ExactNotTaken is non-zero
7915       // (2) EL1.ExactNotTaken is non-poison
7916       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7917       //     it cannot be umin(0, ..))
7918       // The PoisonSafe assignment below is simplified and the assertion after
7919       // BECount calculation fully guarantees the condition (3).
7920       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7921                    isa<SCEVConstant>(EL1.ExactNotTaken);
7922     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7923         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7924       BECount =
7925           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7926 
7927       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7928       // it should have been simplified to zero (see the condition (3) above)
7929       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7930              BECount->isZero());
7931     }
7932     if (EL0.MaxNotTaken == getCouldNotCompute())
7933       MaxBECount = EL1.MaxNotTaken;
7934     else if (EL1.MaxNotTaken == getCouldNotCompute())
7935       MaxBECount = EL0.MaxNotTaken;
7936     else
7937       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7938   } else {
7939     // Both conditions must be same at the same time for the loop to exit.
7940     // For now, be conservative.
7941     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7942       BECount = EL0.ExactNotTaken;
7943   }
7944 
7945   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7946   // to be more aggressive when computing BECount than when computing
7947   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7948   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7949   // to not.
7950   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7951       !isa<SCEVCouldNotCompute>(BECount))
7952     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7953 
7954   return ExitLimit(BECount, MaxBECount, false,
7955                    { &EL0.Predicates, &EL1.Predicates });
7956 }
7957 
7958 ScalarEvolution::ExitLimit
7959 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7960                                           ICmpInst *ExitCond,
7961                                           bool ExitIfTrue,
7962                                           bool ControlsExit,
7963                                           bool AllowPredicates) {
7964   // If the condition was exit on true, convert the condition to exit on false
7965   ICmpInst::Predicate Pred;
7966   if (!ExitIfTrue)
7967     Pred = ExitCond->getPredicate();
7968   else
7969     Pred = ExitCond->getInversePredicate();
7970   const ICmpInst::Predicate OriginalPred = Pred;
7971 
7972   // Handle common loops like: for (X = "string"; *X; ++X)
7973   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7974     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7975       ExitLimit ItCnt =
7976         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7977       if (ItCnt.hasAnyInfo())
7978         return ItCnt;
7979     }
7980 
7981   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7982   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7983 
7984   // Try to evaluate any dependencies out of the loop.
7985   LHS = getSCEVAtScope(LHS, L);
7986   RHS = getSCEVAtScope(RHS, L);
7987 
7988   // At this point, we would like to compute how many iterations of the
7989   // loop the predicate will return true for these inputs.
7990   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7991     // If there is a loop-invariant, force it into the RHS.
7992     std::swap(LHS, RHS);
7993     Pred = ICmpInst::getSwappedPredicate(Pred);
7994   }
7995 
7996   // Simplify the operands before analyzing them.
7997   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7998 
7999   // If we have a comparison of a chrec against a constant, try to use value
8000   // ranges to answer this query.
8001   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8002     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8003       if (AddRec->getLoop() == L) {
8004         // Form the constant range.
8005         ConstantRange CompRange =
8006             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8007 
8008         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8009         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8010       }
8011 
8012   switch (Pred) {
8013   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8014     // Convert to: while (X-Y != 0)
8015     if (LHS->getType()->isPointerTy()) {
8016       LHS = getLosslessPtrToIntExpr(LHS);
8017       if (isa<SCEVCouldNotCompute>(LHS))
8018         return LHS;
8019     }
8020     if (RHS->getType()->isPointerTy()) {
8021       RHS = getLosslessPtrToIntExpr(RHS);
8022       if (isa<SCEVCouldNotCompute>(RHS))
8023         return RHS;
8024     }
8025     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8026                                 AllowPredicates);
8027     if (EL.hasAnyInfo()) return EL;
8028     break;
8029   }
8030   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8031     // Convert to: while (X-Y == 0)
8032     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8033     if (EL.hasAnyInfo()) return EL;
8034     break;
8035   }
8036   case ICmpInst::ICMP_SLT:
8037   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8038     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8039     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8040                                     AllowPredicates);
8041     if (EL.hasAnyInfo()) return EL;
8042     break;
8043   }
8044   case ICmpInst::ICMP_SGT:
8045   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8046     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8047     ExitLimit EL =
8048         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8049                             AllowPredicates);
8050     if (EL.hasAnyInfo()) return EL;
8051     break;
8052   }
8053   default:
8054     break;
8055   }
8056 
8057   auto *ExhaustiveCount =
8058       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8059 
8060   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8061     return ExhaustiveCount;
8062 
8063   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8064                                       ExitCond->getOperand(1), L, OriginalPred);
8065 }
8066 
8067 ScalarEvolution::ExitLimit
8068 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8069                                                       SwitchInst *Switch,
8070                                                       BasicBlock *ExitingBlock,
8071                                                       bool ControlsExit) {
8072   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8073 
8074   // Give up if the exit is the default dest of a switch.
8075   if (Switch->getDefaultDest() == ExitingBlock)
8076     return getCouldNotCompute();
8077 
8078   assert(L->contains(Switch->getDefaultDest()) &&
8079          "Default case must not exit the loop!");
8080   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8081   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8082 
8083   // while (X != Y) --> while (X-Y != 0)
8084   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8085   if (EL.hasAnyInfo())
8086     return EL;
8087 
8088   return getCouldNotCompute();
8089 }
8090 
8091 static ConstantInt *
8092 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8093                                 ScalarEvolution &SE) {
8094   const SCEV *InVal = SE.getConstant(C);
8095   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8096   assert(isa<SCEVConstant>(Val) &&
8097          "Evaluation of SCEV at constant didn't fold correctly?");
8098   return cast<SCEVConstant>(Val)->getValue();
8099 }
8100 
8101 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
8102 /// compute the backedge execution count.
8103 ScalarEvolution::ExitLimit
8104 ScalarEvolution::computeLoadConstantCompareExitLimit(
8105   LoadInst *LI,
8106   Constant *RHS,
8107   const Loop *L,
8108   ICmpInst::Predicate predicate) {
8109   if (LI->isVolatile()) return getCouldNotCompute();
8110 
8111   // Check to see if the loaded pointer is a getelementptr of a global.
8112   // TODO: Use SCEV instead of manually grubbing with GEPs.
8113   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
8114   if (!GEP) return getCouldNotCompute();
8115 
8116   // Make sure that it is really a constant global we are gepping, with an
8117   // initializer, and make sure the first IDX is really 0.
8118   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
8119   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
8120       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
8121       !cast<Constant>(GEP->getOperand(1))->isNullValue())
8122     return getCouldNotCompute();
8123 
8124   // Okay, we allow one non-constant index into the GEP instruction.
8125   Value *VarIdx = nullptr;
8126   std::vector<Constant*> Indexes;
8127   unsigned VarIdxNum = 0;
8128   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
8129     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
8130       Indexes.push_back(CI);
8131     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
8132       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
8133       VarIdx = GEP->getOperand(i);
8134       VarIdxNum = i-2;
8135       Indexes.push_back(nullptr);
8136     }
8137 
8138   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
8139   if (!VarIdx)
8140     return getCouldNotCompute();
8141 
8142   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
8143   // Check to see if X is a loop variant variable value now.
8144   const SCEV *Idx = getSCEV(VarIdx);
8145   Idx = getSCEVAtScope(Idx, L);
8146 
8147   // We can only recognize very limited forms of loop index expressions, in
8148   // particular, only affine AddRec's like {C1,+,C2}<L>.
8149   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
8150   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
8151       isLoopInvariant(IdxExpr, L) ||
8152       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
8153       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
8154     return getCouldNotCompute();
8155 
8156   unsigned MaxSteps = MaxBruteForceIterations;
8157   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
8158     ConstantInt *ItCst = ConstantInt::get(
8159                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
8160     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
8161 
8162     // Form the GEP offset.
8163     Indexes[VarIdxNum] = Val;
8164 
8165     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
8166                                                          Indexes);
8167     if (!Result) break;  // Cannot compute!
8168 
8169     // Evaluate the condition for this iteration.
8170     Result = ConstantExpr::getICmp(predicate, Result, RHS);
8171     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
8172     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
8173       ++NumArrayLenItCounts;
8174       return getConstant(ItCst);   // Found terminating iteration!
8175     }
8176   }
8177   return getCouldNotCompute();
8178 }
8179 
8180 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8181     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8182   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8183   if (!RHS)
8184     return getCouldNotCompute();
8185 
8186   const BasicBlock *Latch = L->getLoopLatch();
8187   if (!Latch)
8188     return getCouldNotCompute();
8189 
8190   const BasicBlock *Predecessor = L->getLoopPredecessor();
8191   if (!Predecessor)
8192     return getCouldNotCompute();
8193 
8194   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8195   // Return LHS in OutLHS and shift_opt in OutOpCode.
8196   auto MatchPositiveShift =
8197       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8198 
8199     using namespace PatternMatch;
8200 
8201     ConstantInt *ShiftAmt;
8202     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8203       OutOpCode = Instruction::LShr;
8204     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8205       OutOpCode = Instruction::AShr;
8206     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8207       OutOpCode = Instruction::Shl;
8208     else
8209       return false;
8210 
8211     return ShiftAmt->getValue().isStrictlyPositive();
8212   };
8213 
8214   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8215   //
8216   // loop:
8217   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8218   //   %iv.shifted = lshr i32 %iv, <positive constant>
8219   //
8220   // Return true on a successful match.  Return the corresponding PHI node (%iv
8221   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8222   auto MatchShiftRecurrence =
8223       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8224     Optional<Instruction::BinaryOps> PostShiftOpCode;
8225 
8226     {
8227       Instruction::BinaryOps OpC;
8228       Value *V;
8229 
8230       // If we encounter a shift instruction, "peel off" the shift operation,
8231       // and remember that we did so.  Later when we inspect %iv's backedge
8232       // value, we will make sure that the backedge value uses the same
8233       // operation.
8234       //
8235       // Note: the peeled shift operation does not have to be the same
8236       // instruction as the one feeding into the PHI's backedge value.  We only
8237       // really care about it being the same *kind* of shift instruction --
8238       // that's all that is required for our later inferences to hold.
8239       if (MatchPositiveShift(LHS, V, OpC)) {
8240         PostShiftOpCode = OpC;
8241         LHS = V;
8242       }
8243     }
8244 
8245     PNOut = dyn_cast<PHINode>(LHS);
8246     if (!PNOut || PNOut->getParent() != L->getHeader())
8247       return false;
8248 
8249     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8250     Value *OpLHS;
8251 
8252     return
8253         // The backedge value for the PHI node must be a shift by a positive
8254         // amount
8255         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8256 
8257         // of the PHI node itself
8258         OpLHS == PNOut &&
8259 
8260         // and the kind of shift should be match the kind of shift we peeled
8261         // off, if any.
8262         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8263   };
8264 
8265   PHINode *PN;
8266   Instruction::BinaryOps OpCode;
8267   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8268     return getCouldNotCompute();
8269 
8270   const DataLayout &DL = getDataLayout();
8271 
8272   // The key rationale for this optimization is that for some kinds of shift
8273   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8274   // within a finite number of iterations.  If the condition guarding the
8275   // backedge (in the sense that the backedge is taken if the condition is true)
8276   // is false for the value the shift recurrence stabilizes to, then we know
8277   // that the backedge is taken only a finite number of times.
8278 
8279   ConstantInt *StableValue = nullptr;
8280   switch (OpCode) {
8281   default:
8282     llvm_unreachable("Impossible case!");
8283 
8284   case Instruction::AShr: {
8285     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8286     // bitwidth(K) iterations.
8287     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8288     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8289                                        Predecessor->getTerminator(), &DT);
8290     auto *Ty = cast<IntegerType>(RHS->getType());
8291     if (Known.isNonNegative())
8292       StableValue = ConstantInt::get(Ty, 0);
8293     else if (Known.isNegative())
8294       StableValue = ConstantInt::get(Ty, -1, true);
8295     else
8296       return getCouldNotCompute();
8297 
8298     break;
8299   }
8300   case Instruction::LShr:
8301   case Instruction::Shl:
8302     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8303     // stabilize to 0 in at most bitwidth(K) iterations.
8304     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8305     break;
8306   }
8307 
8308   auto *Result =
8309       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8310   assert(Result->getType()->isIntegerTy(1) &&
8311          "Otherwise cannot be an operand to a branch instruction");
8312 
8313   if (Result->isZeroValue()) {
8314     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8315     const SCEV *UpperBound =
8316         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8317     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8318   }
8319 
8320   return getCouldNotCompute();
8321 }
8322 
8323 /// Return true if we can constant fold an instruction of the specified type,
8324 /// assuming that all operands were constants.
8325 static bool CanConstantFold(const Instruction *I) {
8326   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8327       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8328       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8329     return true;
8330 
8331   if (const CallInst *CI = dyn_cast<CallInst>(I))
8332     if (const Function *F = CI->getCalledFunction())
8333       return canConstantFoldCallTo(CI, F);
8334   return false;
8335 }
8336 
8337 /// Determine whether this instruction can constant evolve within this loop
8338 /// assuming its operands can all constant evolve.
8339 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8340   // An instruction outside of the loop can't be derived from a loop PHI.
8341   if (!L->contains(I)) return false;
8342 
8343   if (isa<PHINode>(I)) {
8344     // We don't currently keep track of the control flow needed to evaluate
8345     // PHIs, so we cannot handle PHIs inside of loops.
8346     return L->getHeader() == I->getParent();
8347   }
8348 
8349   // If we won't be able to constant fold this expression even if the operands
8350   // are constants, bail early.
8351   return CanConstantFold(I);
8352 }
8353 
8354 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8355 /// recursing through each instruction operand until reaching a loop header phi.
8356 static PHINode *
8357 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8358                                DenseMap<Instruction *, PHINode *> &PHIMap,
8359                                unsigned Depth) {
8360   if (Depth > MaxConstantEvolvingDepth)
8361     return nullptr;
8362 
8363   // Otherwise, we can evaluate this instruction if all of its operands are
8364   // constant or derived from a PHI node themselves.
8365   PHINode *PHI = nullptr;
8366   for (Value *Op : UseInst->operands()) {
8367     if (isa<Constant>(Op)) continue;
8368 
8369     Instruction *OpInst = dyn_cast<Instruction>(Op);
8370     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8371 
8372     PHINode *P = dyn_cast<PHINode>(OpInst);
8373     if (!P)
8374       // If this operand is already visited, reuse the prior result.
8375       // We may have P != PHI if this is the deepest point at which the
8376       // inconsistent paths meet.
8377       P = PHIMap.lookup(OpInst);
8378     if (!P) {
8379       // Recurse and memoize the results, whether a phi is found or not.
8380       // This recursive call invalidates pointers into PHIMap.
8381       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8382       PHIMap[OpInst] = P;
8383     }
8384     if (!P)
8385       return nullptr;  // Not evolving from PHI
8386     if (PHI && PHI != P)
8387       return nullptr;  // Evolving from multiple different PHIs.
8388     PHI = P;
8389   }
8390   // This is a expression evolving from a constant PHI!
8391   return PHI;
8392 }
8393 
8394 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8395 /// in the loop that V is derived from.  We allow arbitrary operations along the
8396 /// way, but the operands of an operation must either be constants or a value
8397 /// derived from a constant PHI.  If this expression does not fit with these
8398 /// constraints, return null.
8399 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8400   Instruction *I = dyn_cast<Instruction>(V);
8401   if (!I || !canConstantEvolve(I, L)) return nullptr;
8402 
8403   if (PHINode *PN = dyn_cast<PHINode>(I))
8404     return PN;
8405 
8406   // Record non-constant instructions contained by the loop.
8407   DenseMap<Instruction *, PHINode *> PHIMap;
8408   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8409 }
8410 
8411 /// EvaluateExpression - Given an expression that passes the
8412 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8413 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8414 /// reason, return null.
8415 static Constant *EvaluateExpression(Value *V, const Loop *L,
8416                                     DenseMap<Instruction *, Constant *> &Vals,
8417                                     const DataLayout &DL,
8418                                     const TargetLibraryInfo *TLI) {
8419   // Convenient constant check, but redundant for recursive calls.
8420   if (Constant *C = dyn_cast<Constant>(V)) return C;
8421   Instruction *I = dyn_cast<Instruction>(V);
8422   if (!I) return nullptr;
8423 
8424   if (Constant *C = Vals.lookup(I)) return C;
8425 
8426   // An instruction inside the loop depends on a value outside the loop that we
8427   // weren't given a mapping for, or a value such as a call inside the loop.
8428   if (!canConstantEvolve(I, L)) return nullptr;
8429 
8430   // An unmapped PHI can be due to a branch or another loop inside this loop,
8431   // or due to this not being the initial iteration through a loop where we
8432   // couldn't compute the evolution of this particular PHI last time.
8433   if (isa<PHINode>(I)) return nullptr;
8434 
8435   std::vector<Constant*> Operands(I->getNumOperands());
8436 
8437   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8438     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8439     if (!Operand) {
8440       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8441       if (!Operands[i]) return nullptr;
8442       continue;
8443     }
8444     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8445     Vals[Operand] = C;
8446     if (!C) return nullptr;
8447     Operands[i] = C;
8448   }
8449 
8450   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8451     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8452                                            Operands[1], DL, TLI);
8453   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8454     if (!LI->isVolatile())
8455       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8456   }
8457   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8458 }
8459 
8460 
8461 // If every incoming value to PN except the one for BB is a specific Constant,
8462 // return that, else return nullptr.
8463 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8464   Constant *IncomingVal = nullptr;
8465 
8466   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8467     if (PN->getIncomingBlock(i) == BB)
8468       continue;
8469 
8470     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8471     if (!CurrentVal)
8472       return nullptr;
8473 
8474     if (IncomingVal != CurrentVal) {
8475       if (IncomingVal)
8476         return nullptr;
8477       IncomingVal = CurrentVal;
8478     }
8479   }
8480 
8481   return IncomingVal;
8482 }
8483 
8484 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8485 /// in the header of its containing loop, we know the loop executes a
8486 /// constant number of times, and the PHI node is just a recurrence
8487 /// involving constants, fold it.
8488 Constant *
8489 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8490                                                    const APInt &BEs,
8491                                                    const Loop *L) {
8492   auto I = ConstantEvolutionLoopExitValue.find(PN);
8493   if (I != ConstantEvolutionLoopExitValue.end())
8494     return I->second;
8495 
8496   if (BEs.ugt(MaxBruteForceIterations))
8497     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8498 
8499   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8500 
8501   DenseMap<Instruction *, Constant *> CurrentIterVals;
8502   BasicBlock *Header = L->getHeader();
8503   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8504 
8505   BasicBlock *Latch = L->getLoopLatch();
8506   if (!Latch)
8507     return nullptr;
8508 
8509   for (PHINode &PHI : Header->phis()) {
8510     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8511       CurrentIterVals[&PHI] = StartCST;
8512   }
8513   if (!CurrentIterVals.count(PN))
8514     return RetVal = nullptr;
8515 
8516   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8517 
8518   // Execute the loop symbolically to determine the exit value.
8519   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8520          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8521 
8522   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8523   unsigned IterationNum = 0;
8524   const DataLayout &DL = getDataLayout();
8525   for (; ; ++IterationNum) {
8526     if (IterationNum == NumIterations)
8527       return RetVal = CurrentIterVals[PN];  // Got exit value!
8528 
8529     // Compute the value of the PHIs for the next iteration.
8530     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8531     DenseMap<Instruction *, Constant *> NextIterVals;
8532     Constant *NextPHI =
8533         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8534     if (!NextPHI)
8535       return nullptr;        // Couldn't evaluate!
8536     NextIterVals[PN] = NextPHI;
8537 
8538     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8539 
8540     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8541     // cease to be able to evaluate one of them or if they stop evolving,
8542     // because that doesn't necessarily prevent us from computing PN.
8543     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8544     for (const auto &I : CurrentIterVals) {
8545       PHINode *PHI = dyn_cast<PHINode>(I.first);
8546       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8547       PHIsToCompute.emplace_back(PHI, I.second);
8548     }
8549     // We use two distinct loops because EvaluateExpression may invalidate any
8550     // iterators into CurrentIterVals.
8551     for (const auto &I : PHIsToCompute) {
8552       PHINode *PHI = I.first;
8553       Constant *&NextPHI = NextIterVals[PHI];
8554       if (!NextPHI) {   // Not already computed.
8555         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8556         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8557       }
8558       if (NextPHI != I.second)
8559         StoppedEvolving = false;
8560     }
8561 
8562     // If all entries in CurrentIterVals == NextIterVals then we can stop
8563     // iterating, the loop can't continue to change.
8564     if (StoppedEvolving)
8565       return RetVal = CurrentIterVals[PN];
8566 
8567     CurrentIterVals.swap(NextIterVals);
8568   }
8569 }
8570 
8571 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8572                                                           Value *Cond,
8573                                                           bool ExitWhen) {
8574   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8575   if (!PN) return getCouldNotCompute();
8576 
8577   // If the loop is canonicalized, the PHI will have exactly two entries.
8578   // That's the only form we support here.
8579   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8580 
8581   DenseMap<Instruction *, Constant *> CurrentIterVals;
8582   BasicBlock *Header = L->getHeader();
8583   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8584 
8585   BasicBlock *Latch = L->getLoopLatch();
8586   assert(Latch && "Should follow from NumIncomingValues == 2!");
8587 
8588   for (PHINode &PHI : Header->phis()) {
8589     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8590       CurrentIterVals[&PHI] = StartCST;
8591   }
8592   if (!CurrentIterVals.count(PN))
8593     return getCouldNotCompute();
8594 
8595   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8596   // the loop symbolically to determine when the condition gets a value of
8597   // "ExitWhen".
8598   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8599   const DataLayout &DL = getDataLayout();
8600   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8601     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8602         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8603 
8604     // Couldn't symbolically evaluate.
8605     if (!CondVal) return getCouldNotCompute();
8606 
8607     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8608       ++NumBruteForceTripCountsComputed;
8609       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8610     }
8611 
8612     // Update all the PHI nodes for the next iteration.
8613     DenseMap<Instruction *, Constant *> NextIterVals;
8614 
8615     // Create a list of which PHIs we need to compute. We want to do this before
8616     // calling EvaluateExpression on them because that may invalidate iterators
8617     // into CurrentIterVals.
8618     SmallVector<PHINode *, 8> PHIsToCompute;
8619     for (const auto &I : CurrentIterVals) {
8620       PHINode *PHI = dyn_cast<PHINode>(I.first);
8621       if (!PHI || PHI->getParent() != Header) continue;
8622       PHIsToCompute.push_back(PHI);
8623     }
8624     for (PHINode *PHI : PHIsToCompute) {
8625       Constant *&NextPHI = NextIterVals[PHI];
8626       if (NextPHI) continue;    // Already computed!
8627 
8628       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8629       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8630     }
8631     CurrentIterVals.swap(NextIterVals);
8632   }
8633 
8634   // Too many iterations were needed to evaluate.
8635   return getCouldNotCompute();
8636 }
8637 
8638 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8639   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8640       ValuesAtScopes[V];
8641   // Check to see if we've folded this expression at this loop before.
8642   for (auto &LS : Values)
8643     if (LS.first == L)
8644       return LS.second ? LS.second : V;
8645 
8646   Values.emplace_back(L, nullptr);
8647 
8648   // Otherwise compute it.
8649   const SCEV *C = computeSCEVAtScope(V, L);
8650   for (auto &LS : reverse(ValuesAtScopes[V]))
8651     if (LS.first == L) {
8652       LS.second = C;
8653       break;
8654     }
8655   return C;
8656 }
8657 
8658 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8659 /// will return Constants for objects which aren't represented by a
8660 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8661 /// Returns NULL if the SCEV isn't representable as a Constant.
8662 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8663   switch (V->getSCEVType()) {
8664   case scCouldNotCompute:
8665   case scAddRecExpr:
8666     return nullptr;
8667   case scConstant:
8668     return cast<SCEVConstant>(V)->getValue();
8669   case scUnknown:
8670     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8671   case scSignExtend: {
8672     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8673     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8674       return ConstantExpr::getSExt(CastOp, SS->getType());
8675     return nullptr;
8676   }
8677   case scZeroExtend: {
8678     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8679     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8680       return ConstantExpr::getZExt(CastOp, SZ->getType());
8681     return nullptr;
8682   }
8683   case scPtrToInt: {
8684     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8685     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8686       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8687 
8688     return nullptr;
8689   }
8690   case scTruncate: {
8691     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8692     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8693       return ConstantExpr::getTrunc(CastOp, ST->getType());
8694     return nullptr;
8695   }
8696   case scAddExpr: {
8697     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8698     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8699       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8700         unsigned AS = PTy->getAddressSpace();
8701         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8702         C = ConstantExpr::getBitCast(C, DestPtrTy);
8703       }
8704       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8705         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8706         if (!C2)
8707           return nullptr;
8708 
8709         // First pointer!
8710         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8711           unsigned AS = C2->getType()->getPointerAddressSpace();
8712           std::swap(C, C2);
8713           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8714           // The offsets have been converted to bytes.  We can add bytes to an
8715           // i8* by GEP with the byte count in the first index.
8716           C = ConstantExpr::getBitCast(C, DestPtrTy);
8717         }
8718 
8719         // Don't bother trying to sum two pointers. We probably can't
8720         // statically compute a load that results from it anyway.
8721         if (C2->getType()->isPointerTy())
8722           return nullptr;
8723 
8724         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8725           if (PTy->getElementType()->isStructTy())
8726             C2 = ConstantExpr::getIntegerCast(
8727                 C2, Type::getInt32Ty(C->getContext()), true);
8728           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8729         } else
8730           C = ConstantExpr::getAdd(C, C2);
8731       }
8732       return C;
8733     }
8734     return nullptr;
8735   }
8736   case scMulExpr: {
8737     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8738     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8739       // Don't bother with pointers at all.
8740       if (C->getType()->isPointerTy())
8741         return nullptr;
8742       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8743         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8744         if (!C2 || C2->getType()->isPointerTy())
8745           return nullptr;
8746         C = ConstantExpr::getMul(C, C2);
8747       }
8748       return C;
8749     }
8750     return nullptr;
8751   }
8752   case scUDivExpr: {
8753     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8754     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8755       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8756         if (LHS->getType() == RHS->getType())
8757           return ConstantExpr::getUDiv(LHS, RHS);
8758     return nullptr;
8759   }
8760   case scSMaxExpr:
8761   case scUMaxExpr:
8762   case scSMinExpr:
8763   case scUMinExpr:
8764     return nullptr; // TODO: smax, umax, smin, umax.
8765   }
8766   llvm_unreachable("Unknown SCEV kind!");
8767 }
8768 
8769 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8770   if (isa<SCEVConstant>(V)) return V;
8771 
8772   // If this instruction is evolved from a constant-evolving PHI, compute the
8773   // exit value from the loop without using SCEVs.
8774   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8775     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8776       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8777         const Loop *CurrLoop = this->LI[I->getParent()];
8778         // Looking for loop exit value.
8779         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8780             PN->getParent() == CurrLoop->getHeader()) {
8781           // Okay, there is no closed form solution for the PHI node.  Check
8782           // to see if the loop that contains it has a known backedge-taken
8783           // count.  If so, we may be able to force computation of the exit
8784           // value.
8785           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8786           // This trivial case can show up in some degenerate cases where
8787           // the incoming IR has not yet been fully simplified.
8788           if (BackedgeTakenCount->isZero()) {
8789             Value *InitValue = nullptr;
8790             bool MultipleInitValues = false;
8791             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8792               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8793                 if (!InitValue)
8794                   InitValue = PN->getIncomingValue(i);
8795                 else if (InitValue != PN->getIncomingValue(i)) {
8796                   MultipleInitValues = true;
8797                   break;
8798                 }
8799               }
8800             }
8801             if (!MultipleInitValues && InitValue)
8802               return getSCEV(InitValue);
8803           }
8804           // Do we have a loop invariant value flowing around the backedge
8805           // for a loop which must execute the backedge?
8806           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8807               isKnownPositive(BackedgeTakenCount) &&
8808               PN->getNumIncomingValues() == 2) {
8809 
8810             unsigned InLoopPred =
8811                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8812             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8813             if (CurrLoop->isLoopInvariant(BackedgeVal))
8814               return getSCEV(BackedgeVal);
8815           }
8816           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8817             // Okay, we know how many times the containing loop executes.  If
8818             // this is a constant evolving PHI node, get the final value at
8819             // the specified iteration number.
8820             Constant *RV = getConstantEvolutionLoopExitValue(
8821                 PN, BTCC->getAPInt(), CurrLoop);
8822             if (RV) return getSCEV(RV);
8823           }
8824         }
8825 
8826         // If there is a single-input Phi, evaluate it at our scope. If we can
8827         // prove that this replacement does not break LCSSA form, use new value.
8828         if (PN->getNumOperands() == 1) {
8829           const SCEV *Input = getSCEV(PN->getOperand(0));
8830           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8831           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8832           // for the simplest case just support constants.
8833           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8834         }
8835       }
8836 
8837       // Okay, this is an expression that we cannot symbolically evaluate
8838       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8839       // the arguments into constants, and if so, try to constant propagate the
8840       // result.  This is particularly useful for computing loop exit values.
8841       if (CanConstantFold(I)) {
8842         SmallVector<Constant *, 4> Operands;
8843         bool MadeImprovement = false;
8844         for (Value *Op : I->operands()) {
8845           if (Constant *C = dyn_cast<Constant>(Op)) {
8846             Operands.push_back(C);
8847             continue;
8848           }
8849 
8850           // If any of the operands is non-constant and if they are
8851           // non-integer and non-pointer, don't even try to analyze them
8852           // with scev techniques.
8853           if (!isSCEVable(Op->getType()))
8854             return V;
8855 
8856           const SCEV *OrigV = getSCEV(Op);
8857           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8858           MadeImprovement |= OrigV != OpV;
8859 
8860           Constant *C = BuildConstantFromSCEV(OpV);
8861           if (!C) return V;
8862           if (C->getType() != Op->getType())
8863             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8864                                                               Op->getType(),
8865                                                               false),
8866                                       C, Op->getType());
8867           Operands.push_back(C);
8868         }
8869 
8870         // Check to see if getSCEVAtScope actually made an improvement.
8871         if (MadeImprovement) {
8872           Constant *C = nullptr;
8873           const DataLayout &DL = getDataLayout();
8874           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8875             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8876                                                 Operands[1], DL, &TLI);
8877           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8878             if (!Load->isVolatile())
8879               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8880                                                DL);
8881           } else
8882             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8883           if (!C) return V;
8884           return getSCEV(C);
8885         }
8886       }
8887     }
8888 
8889     // This is some other type of SCEVUnknown, just return it.
8890     return V;
8891   }
8892 
8893   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8894     // Avoid performing the look-up in the common case where the specified
8895     // expression has no loop-variant portions.
8896     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8897       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8898       if (OpAtScope != Comm->getOperand(i)) {
8899         // Okay, at least one of these operands is loop variant but might be
8900         // foldable.  Build a new instance of the folded commutative expression.
8901         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8902                                             Comm->op_begin()+i);
8903         NewOps.push_back(OpAtScope);
8904 
8905         for (++i; i != e; ++i) {
8906           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8907           NewOps.push_back(OpAtScope);
8908         }
8909         if (isa<SCEVAddExpr>(Comm))
8910           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8911         if (isa<SCEVMulExpr>(Comm))
8912           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8913         if (isa<SCEVMinMaxExpr>(Comm))
8914           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8915         llvm_unreachable("Unknown commutative SCEV type!");
8916       }
8917     }
8918     // If we got here, all operands are loop invariant.
8919     return Comm;
8920   }
8921 
8922   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8923     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8924     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8925     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8926       return Div;   // must be loop invariant
8927     return getUDivExpr(LHS, RHS);
8928   }
8929 
8930   // If this is a loop recurrence for a loop that does not contain L, then we
8931   // are dealing with the final value computed by the loop.
8932   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8933     // First, attempt to evaluate each operand.
8934     // Avoid performing the look-up in the common case where the specified
8935     // expression has no loop-variant portions.
8936     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8937       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8938       if (OpAtScope == AddRec->getOperand(i))
8939         continue;
8940 
8941       // Okay, at least one of these operands is loop variant but might be
8942       // foldable.  Build a new instance of the folded commutative expression.
8943       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8944                                           AddRec->op_begin()+i);
8945       NewOps.push_back(OpAtScope);
8946       for (++i; i != e; ++i)
8947         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8948 
8949       const SCEV *FoldedRec =
8950         getAddRecExpr(NewOps, AddRec->getLoop(),
8951                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8952       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8953       // The addrec may be folded to a nonrecurrence, for example, if the
8954       // induction variable is multiplied by zero after constant folding. Go
8955       // ahead and return the folded value.
8956       if (!AddRec)
8957         return FoldedRec;
8958       break;
8959     }
8960 
8961     // If the scope is outside the addrec's loop, evaluate it by using the
8962     // loop exit value of the addrec.
8963     if (!AddRec->getLoop()->contains(L)) {
8964       // To evaluate this recurrence, we need to know how many times the AddRec
8965       // loop iterates.  Compute this now.
8966       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8967       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8968 
8969       // Then, evaluate the AddRec.
8970       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8971     }
8972 
8973     return AddRec;
8974   }
8975 
8976   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8977     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8978     if (Op == Cast->getOperand())
8979       return Cast;  // must be loop invariant
8980     return getZeroExtendExpr(Op, Cast->getType());
8981   }
8982 
8983   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8984     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8985     if (Op == Cast->getOperand())
8986       return Cast;  // must be loop invariant
8987     return getSignExtendExpr(Op, Cast->getType());
8988   }
8989 
8990   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8991     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8992     if (Op == Cast->getOperand())
8993       return Cast;  // must be loop invariant
8994     return getTruncateExpr(Op, Cast->getType());
8995   }
8996 
8997   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8998     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8999     if (Op == Cast->getOperand())
9000       return Cast; // must be loop invariant
9001     return getPtrToIntExpr(Op, Cast->getType());
9002   }
9003 
9004   llvm_unreachable("Unknown SCEV type!");
9005 }
9006 
9007 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9008   return getSCEVAtScope(getSCEV(V), L);
9009 }
9010 
9011 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9012   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9013     return stripInjectiveFunctions(ZExt->getOperand());
9014   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9015     return stripInjectiveFunctions(SExt->getOperand());
9016   return S;
9017 }
9018 
9019 /// Finds the minimum unsigned root of the following equation:
9020 ///
9021 ///     A * X = B (mod N)
9022 ///
9023 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9024 /// A and B isn't important.
9025 ///
9026 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9027 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9028                                                ScalarEvolution &SE) {
9029   uint32_t BW = A.getBitWidth();
9030   assert(BW == SE.getTypeSizeInBits(B->getType()));
9031   assert(A != 0 && "A must be non-zero.");
9032 
9033   // 1. D = gcd(A, N)
9034   //
9035   // The gcd of A and N may have only one prime factor: 2. The number of
9036   // trailing zeros in A is its multiplicity
9037   uint32_t Mult2 = A.countTrailingZeros();
9038   // D = 2^Mult2
9039 
9040   // 2. Check if B is divisible by D.
9041   //
9042   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9043   // is not less than multiplicity of this prime factor for D.
9044   if (SE.GetMinTrailingZeros(B) < Mult2)
9045     return SE.getCouldNotCompute();
9046 
9047   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9048   // modulo (N / D).
9049   //
9050   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9051   // (N / D) in general. The inverse itself always fits into BW bits, though,
9052   // so we immediately truncate it.
9053   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9054   APInt Mod(BW + 1, 0);
9055   Mod.setBit(BW - Mult2);  // Mod = N / D
9056   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9057 
9058   // 4. Compute the minimum unsigned root of the equation:
9059   // I * (B / D) mod (N / D)
9060   // To simplify the computation, we factor out the divide by D:
9061   // (I * B mod N) / D
9062   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9063   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9064 }
9065 
9066 /// For a given quadratic addrec, generate coefficients of the corresponding
9067 /// quadratic equation, multiplied by a common value to ensure that they are
9068 /// integers.
9069 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9070 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9071 /// were multiplied by, and BitWidth is the bit width of the original addrec
9072 /// coefficients.
9073 /// This function returns None if the addrec coefficients are not compile-
9074 /// time constants.
9075 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9076 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9077   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9078   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9079   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9080   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9081   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9082                     << *AddRec << '\n');
9083 
9084   // We currently can only solve this if the coefficients are constants.
9085   if (!LC || !MC || !NC) {
9086     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9087     return None;
9088   }
9089 
9090   APInt L = LC->getAPInt();
9091   APInt M = MC->getAPInt();
9092   APInt N = NC->getAPInt();
9093   assert(!N.isNullValue() && "This is not a quadratic addrec");
9094 
9095   unsigned BitWidth = LC->getAPInt().getBitWidth();
9096   unsigned NewWidth = BitWidth + 1;
9097   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9098                     << BitWidth << '\n');
9099   // The sign-extension (as opposed to a zero-extension) here matches the
9100   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9101   N = N.sext(NewWidth);
9102   M = M.sext(NewWidth);
9103   L = L.sext(NewWidth);
9104 
9105   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9106   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9107   //   L+M, L+2M+N, L+3M+3N, ...
9108   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9109   //
9110   // The equation Acc = 0 is then
9111   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9112   // In a quadratic form it becomes:
9113   //   N n^2 + (2M-N) n + 2L = 0.
9114 
9115   APInt A = N;
9116   APInt B = 2 * M - A;
9117   APInt C = 2 * L;
9118   APInt T = APInt(NewWidth, 2);
9119   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9120                     << "x + " << C << ", coeff bw: " << NewWidth
9121                     << ", multiplied by " << T << '\n');
9122   return std::make_tuple(A, B, C, T, BitWidth);
9123 }
9124 
9125 /// Helper function to compare optional APInts:
9126 /// (a) if X and Y both exist, return min(X, Y),
9127 /// (b) if neither X nor Y exist, return None,
9128 /// (c) if exactly one of X and Y exists, return that value.
9129 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9130   if (X.hasValue() && Y.hasValue()) {
9131     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9132     APInt XW = X->sextOrSelf(W);
9133     APInt YW = Y->sextOrSelf(W);
9134     return XW.slt(YW) ? *X : *Y;
9135   }
9136   if (!X.hasValue() && !Y.hasValue())
9137     return None;
9138   return X.hasValue() ? *X : *Y;
9139 }
9140 
9141 /// Helper function to truncate an optional APInt to a given BitWidth.
9142 /// When solving addrec-related equations, it is preferable to return a value
9143 /// that has the same bit width as the original addrec's coefficients. If the
9144 /// solution fits in the original bit width, truncate it (except for i1).
9145 /// Returning a value of a different bit width may inhibit some optimizations.
9146 ///
9147 /// In general, a solution to a quadratic equation generated from an addrec
9148 /// may require BW+1 bits, where BW is the bit width of the addrec's
9149 /// coefficients. The reason is that the coefficients of the quadratic
9150 /// equation are BW+1 bits wide (to avoid truncation when converting from
9151 /// the addrec to the equation).
9152 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9153   if (!X.hasValue())
9154     return None;
9155   unsigned W = X->getBitWidth();
9156   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9157     return X->trunc(BitWidth);
9158   return X;
9159 }
9160 
9161 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9162 /// iterations. The values L, M, N are assumed to be signed, and they
9163 /// should all have the same bit widths.
9164 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9165 /// where BW is the bit width of the addrec's coefficients.
9166 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9167 /// returned as such, otherwise the bit width of the returned value may
9168 /// be greater than BW.
9169 ///
9170 /// This function returns None if
9171 /// (a) the addrec coefficients are not constant, or
9172 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9173 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9174 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9175 static Optional<APInt>
9176 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9177   APInt A, B, C, M;
9178   unsigned BitWidth;
9179   auto T = GetQuadraticEquation(AddRec);
9180   if (!T.hasValue())
9181     return None;
9182 
9183   std::tie(A, B, C, M, BitWidth) = *T;
9184   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9185   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9186   if (!X.hasValue())
9187     return None;
9188 
9189   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9190   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9191   if (!V->isZero())
9192     return None;
9193 
9194   return TruncIfPossible(X, BitWidth);
9195 }
9196 
9197 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9198 /// iterations. The values M, N are assumed to be signed, and they
9199 /// should all have the same bit widths.
9200 /// Find the least n such that c(n) does not belong to the given range,
9201 /// while c(n-1) does.
9202 ///
9203 /// This function returns None if
9204 /// (a) the addrec coefficients are not constant, or
9205 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9206 ///     bounds of the range.
9207 static Optional<APInt>
9208 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9209                           const ConstantRange &Range, ScalarEvolution &SE) {
9210   assert(AddRec->getOperand(0)->isZero() &&
9211          "Starting value of addrec should be 0");
9212   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9213                     << Range << ", addrec " << *AddRec << '\n');
9214   // This case is handled in getNumIterationsInRange. Here we can assume that
9215   // we start in the range.
9216   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9217          "Addrec's initial value should be in range");
9218 
9219   APInt A, B, C, M;
9220   unsigned BitWidth;
9221   auto T = GetQuadraticEquation(AddRec);
9222   if (!T.hasValue())
9223     return None;
9224 
9225   // Be careful about the return value: there can be two reasons for not
9226   // returning an actual number. First, if no solutions to the equations
9227   // were found, and second, if the solutions don't leave the given range.
9228   // The first case means that the actual solution is "unknown", the second
9229   // means that it's known, but not valid. If the solution is unknown, we
9230   // cannot make any conclusions.
9231   // Return a pair: the optional solution and a flag indicating if the
9232   // solution was found.
9233   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9234     // Solve for signed overflow and unsigned overflow, pick the lower
9235     // solution.
9236     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9237                       << Bound << " (before multiplying by " << M << ")\n");
9238     Bound *= M; // The quadratic equation multiplier.
9239 
9240     Optional<APInt> SO = None;
9241     if (BitWidth > 1) {
9242       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9243                            "signed overflow\n");
9244       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9245     }
9246     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9247                          "unsigned overflow\n");
9248     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9249                                                               BitWidth+1);
9250 
9251     auto LeavesRange = [&] (const APInt &X) {
9252       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9253       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9254       if (Range.contains(V0->getValue()))
9255         return false;
9256       // X should be at least 1, so X-1 is non-negative.
9257       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9258       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9259       if (Range.contains(V1->getValue()))
9260         return true;
9261       return false;
9262     };
9263 
9264     // If SolveQuadraticEquationWrap returns None, it means that there can
9265     // be a solution, but the function failed to find it. We cannot treat it
9266     // as "no solution".
9267     if (!SO.hasValue() || !UO.hasValue())
9268       return { None, false };
9269 
9270     // Check the smaller value first to see if it leaves the range.
9271     // At this point, both SO and UO must have values.
9272     Optional<APInt> Min = MinOptional(SO, UO);
9273     if (LeavesRange(*Min))
9274       return { Min, true };
9275     Optional<APInt> Max = Min == SO ? UO : SO;
9276     if (LeavesRange(*Max))
9277       return { Max, true };
9278 
9279     // Solutions were found, but were eliminated, hence the "true".
9280     return { None, true };
9281   };
9282 
9283   std::tie(A, B, C, M, BitWidth) = *T;
9284   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9285   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9286   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9287   auto SL = SolveForBoundary(Lower);
9288   auto SU = SolveForBoundary(Upper);
9289   // If any of the solutions was unknown, no meaninigful conclusions can
9290   // be made.
9291   if (!SL.second || !SU.second)
9292     return None;
9293 
9294   // Claim: The correct solution is not some value between Min and Max.
9295   //
9296   // Justification: Assuming that Min and Max are different values, one of
9297   // them is when the first signed overflow happens, the other is when the
9298   // first unsigned overflow happens. Crossing the range boundary is only
9299   // possible via an overflow (treating 0 as a special case of it, modeling
9300   // an overflow as crossing k*2^W for some k).
9301   //
9302   // The interesting case here is when Min was eliminated as an invalid
9303   // solution, but Max was not. The argument is that if there was another
9304   // overflow between Min and Max, it would also have been eliminated if
9305   // it was considered.
9306   //
9307   // For a given boundary, it is possible to have two overflows of the same
9308   // type (signed/unsigned) without having the other type in between: this
9309   // can happen when the vertex of the parabola is between the iterations
9310   // corresponding to the overflows. This is only possible when the two
9311   // overflows cross k*2^W for the same k. In such case, if the second one
9312   // left the range (and was the first one to do so), the first overflow
9313   // would have to enter the range, which would mean that either we had left
9314   // the range before or that we started outside of it. Both of these cases
9315   // are contradictions.
9316   //
9317   // Claim: In the case where SolveForBoundary returns None, the correct
9318   // solution is not some value between the Max for this boundary and the
9319   // Min of the other boundary.
9320   //
9321   // Justification: Assume that we had such Max_A and Min_B corresponding
9322   // to range boundaries A and B and such that Max_A < Min_B. If there was
9323   // a solution between Max_A and Min_B, it would have to be caused by an
9324   // overflow corresponding to either A or B. It cannot correspond to B,
9325   // since Min_B is the first occurrence of such an overflow. If it
9326   // corresponded to A, it would have to be either a signed or an unsigned
9327   // overflow that is larger than both eliminated overflows for A. But
9328   // between the eliminated overflows and this overflow, the values would
9329   // cover the entire value space, thus crossing the other boundary, which
9330   // is a contradiction.
9331 
9332   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9333 }
9334 
9335 ScalarEvolution::ExitLimit
9336 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9337                               bool AllowPredicates) {
9338 
9339   // This is only used for loops with a "x != y" exit test. The exit condition
9340   // is now expressed as a single expression, V = x-y. So the exit test is
9341   // effectively V != 0.  We know and take advantage of the fact that this
9342   // expression only being used in a comparison by zero context.
9343 
9344   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9345   // If the value is a constant
9346   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9347     // If the value is already zero, the branch will execute zero times.
9348     if (C->getValue()->isZero()) return C;
9349     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9350   }
9351 
9352   const SCEVAddRecExpr *AddRec =
9353       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9354 
9355   if (!AddRec && AllowPredicates)
9356     // Try to make this an AddRec using runtime tests, in the first X
9357     // iterations of this loop, where X is the SCEV expression found by the
9358     // algorithm below.
9359     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9360 
9361   if (!AddRec || AddRec->getLoop() != L)
9362     return getCouldNotCompute();
9363 
9364   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9365   // the quadratic equation to solve it.
9366   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9367     // We can only use this value if the chrec ends up with an exact zero
9368     // value at this index.  When solving for "X*X != 5", for example, we
9369     // should not accept a root of 2.
9370     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9371       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9372       return ExitLimit(R, R, false, Predicates);
9373     }
9374     return getCouldNotCompute();
9375   }
9376 
9377   // Otherwise we can only handle this if it is affine.
9378   if (!AddRec->isAffine())
9379     return getCouldNotCompute();
9380 
9381   // If this is an affine expression, the execution count of this branch is
9382   // the minimum unsigned root of the following equation:
9383   //
9384   //     Start + Step*N = 0 (mod 2^BW)
9385   //
9386   // equivalent to:
9387   //
9388   //             Step*N = -Start (mod 2^BW)
9389   //
9390   // where BW is the common bit width of Start and Step.
9391 
9392   // Get the initial value for the loop.
9393   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9394   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9395 
9396   // For now we handle only constant steps.
9397   //
9398   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9399   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9400   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9401   // We have not yet seen any such cases.
9402   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9403   if (!StepC || StepC->getValue()->isZero())
9404     return getCouldNotCompute();
9405 
9406   // For positive steps (counting up until unsigned overflow):
9407   //   N = -Start/Step (as unsigned)
9408   // For negative steps (counting down to zero):
9409   //   N = Start/-Step
9410   // First compute the unsigned distance from zero in the direction of Step.
9411   bool CountDown = StepC->getAPInt().isNegative();
9412   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9413 
9414   // Handle unitary steps, which cannot wraparound.
9415   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9416   //   N = Distance (as unsigned)
9417   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9418     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9419     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9420     if (MaxBECountBase.ult(MaxBECount))
9421       MaxBECount = MaxBECountBase;
9422 
9423     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9424     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9425     // case, and see if we can improve the bound.
9426     //
9427     // Explicitly handling this here is necessary because getUnsignedRange
9428     // isn't context-sensitive; it doesn't know that we only care about the
9429     // range inside the loop.
9430     const SCEV *Zero = getZero(Distance->getType());
9431     const SCEV *One = getOne(Distance->getType());
9432     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9433     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9434       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9435       // as "unsigned_max(Distance + 1) - 1".
9436       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9437       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9438     }
9439     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9440   }
9441 
9442   // If the condition controls loop exit (the loop exits only if the expression
9443   // is true) and the addition is no-wrap we can use unsigned divide to
9444   // compute the backedge count.  In this case, the step may not divide the
9445   // distance, but we don't care because if the condition is "missed" the loop
9446   // will have undefined behavior due to wrapping.
9447   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9448       loopHasNoAbnormalExits(AddRec->getLoop())) {
9449     const SCEV *Exact =
9450         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9451     const SCEV *Max = getCouldNotCompute();
9452     if (Exact != getCouldNotCompute()) {
9453       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
9454       APInt BaseMaxInt = getUnsignedRangeMax(Exact);
9455       if (BaseMaxInt.ult(MaxInt))
9456         Max = getConstant(BaseMaxInt);
9457       else
9458         Max = getConstant(MaxInt);
9459     }
9460     return ExitLimit(Exact, Max, false, Predicates);
9461   }
9462 
9463   // Solve the general equation.
9464   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9465                                                getNegativeSCEV(Start), *this);
9466   const SCEV *M = E == getCouldNotCompute()
9467                       ? E
9468                       : getConstant(getUnsignedRangeMax(E));
9469   return ExitLimit(E, M, false, Predicates);
9470 }
9471 
9472 ScalarEvolution::ExitLimit
9473 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9474   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9475   // handle them yet except for the trivial case.  This could be expanded in the
9476   // future as needed.
9477 
9478   // If the value is a constant, check to see if it is known to be non-zero
9479   // already.  If so, the backedge will execute zero times.
9480   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9481     if (!C->getValue()->isZero())
9482       return getZero(C->getType());
9483     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9484   }
9485 
9486   // We could implement others, but I really doubt anyone writes loops like
9487   // this, and if they did, they would already be constant folded.
9488   return getCouldNotCompute();
9489 }
9490 
9491 std::pair<const BasicBlock *, const BasicBlock *>
9492 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9493     const {
9494   // If the block has a unique predecessor, then there is no path from the
9495   // predecessor to the block that does not go through the direct edge
9496   // from the predecessor to the block.
9497   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9498     return {Pred, BB};
9499 
9500   // A loop's header is defined to be a block that dominates the loop.
9501   // If the header has a unique predecessor outside the loop, it must be
9502   // a block that has exactly one successor that can reach the loop.
9503   if (const Loop *L = LI.getLoopFor(BB))
9504     return {L->getLoopPredecessor(), L->getHeader()};
9505 
9506   return {nullptr, nullptr};
9507 }
9508 
9509 /// SCEV structural equivalence is usually sufficient for testing whether two
9510 /// expressions are equal, however for the purposes of looking for a condition
9511 /// guarding a loop, it can be useful to be a little more general, since a
9512 /// front-end may have replicated the controlling expression.
9513 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9514   // Quick check to see if they are the same SCEV.
9515   if (A == B) return true;
9516 
9517   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9518     // Not all instructions that are "identical" compute the same value.  For
9519     // instance, two distinct alloca instructions allocating the same type are
9520     // identical and do not read memory; but compute distinct values.
9521     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9522   };
9523 
9524   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9525   // two different instructions with the same value. Check for this case.
9526   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9527     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9528       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9529         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9530           if (ComputesEqualValues(AI, BI))
9531             return true;
9532 
9533   // Otherwise assume they may have a different value.
9534   return false;
9535 }
9536 
9537 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9538                                            const SCEV *&LHS, const SCEV *&RHS,
9539                                            unsigned Depth) {
9540   bool Changed = false;
9541   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9542   // '0 != 0'.
9543   auto TrivialCase = [&](bool TriviallyTrue) {
9544     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9545     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9546     return true;
9547   };
9548   // If we hit the max recursion limit bail out.
9549   if (Depth >= 3)
9550     return false;
9551 
9552   // Canonicalize a constant to the right side.
9553   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9554     // Check for both operands constant.
9555     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9556       if (ConstantExpr::getICmp(Pred,
9557                                 LHSC->getValue(),
9558                                 RHSC->getValue())->isNullValue())
9559         return TrivialCase(false);
9560       else
9561         return TrivialCase(true);
9562     }
9563     // Otherwise swap the operands to put the constant on the right.
9564     std::swap(LHS, RHS);
9565     Pred = ICmpInst::getSwappedPredicate(Pred);
9566     Changed = true;
9567   }
9568 
9569   // If we're comparing an addrec with a value which is loop-invariant in the
9570   // addrec's loop, put the addrec on the left. Also make a dominance check,
9571   // as both operands could be addrecs loop-invariant in each other's loop.
9572   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9573     const Loop *L = AR->getLoop();
9574     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9575       std::swap(LHS, RHS);
9576       Pred = ICmpInst::getSwappedPredicate(Pred);
9577       Changed = true;
9578     }
9579   }
9580 
9581   // If there's a constant operand, canonicalize comparisons with boundary
9582   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9583   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9584     const APInt &RA = RC->getAPInt();
9585 
9586     bool SimplifiedByConstantRange = false;
9587 
9588     if (!ICmpInst::isEquality(Pred)) {
9589       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9590       if (ExactCR.isFullSet())
9591         return TrivialCase(true);
9592       else if (ExactCR.isEmptySet())
9593         return TrivialCase(false);
9594 
9595       APInt NewRHS;
9596       CmpInst::Predicate NewPred;
9597       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9598           ICmpInst::isEquality(NewPred)) {
9599         // We were able to convert an inequality to an equality.
9600         Pred = NewPred;
9601         RHS = getConstant(NewRHS);
9602         Changed = SimplifiedByConstantRange = true;
9603       }
9604     }
9605 
9606     if (!SimplifiedByConstantRange) {
9607       switch (Pred) {
9608       default:
9609         break;
9610       case ICmpInst::ICMP_EQ:
9611       case ICmpInst::ICMP_NE:
9612         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9613         if (!RA)
9614           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9615             if (const SCEVMulExpr *ME =
9616                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9617               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9618                   ME->getOperand(0)->isAllOnesValue()) {
9619                 RHS = AE->getOperand(1);
9620                 LHS = ME->getOperand(1);
9621                 Changed = true;
9622               }
9623         break;
9624 
9625 
9626         // The "Should have been caught earlier!" messages refer to the fact
9627         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9628         // should have fired on the corresponding cases, and canonicalized the
9629         // check to trivial case.
9630 
9631       case ICmpInst::ICMP_UGE:
9632         assert(!RA.isMinValue() && "Should have been caught earlier!");
9633         Pred = ICmpInst::ICMP_UGT;
9634         RHS = getConstant(RA - 1);
9635         Changed = true;
9636         break;
9637       case ICmpInst::ICMP_ULE:
9638         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9639         Pred = ICmpInst::ICMP_ULT;
9640         RHS = getConstant(RA + 1);
9641         Changed = true;
9642         break;
9643       case ICmpInst::ICMP_SGE:
9644         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9645         Pred = ICmpInst::ICMP_SGT;
9646         RHS = getConstant(RA - 1);
9647         Changed = true;
9648         break;
9649       case ICmpInst::ICMP_SLE:
9650         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9651         Pred = ICmpInst::ICMP_SLT;
9652         RHS = getConstant(RA + 1);
9653         Changed = true;
9654         break;
9655       }
9656     }
9657   }
9658 
9659   // Check for obvious equality.
9660   if (HasSameValue(LHS, RHS)) {
9661     if (ICmpInst::isTrueWhenEqual(Pred))
9662       return TrivialCase(true);
9663     if (ICmpInst::isFalseWhenEqual(Pred))
9664       return TrivialCase(false);
9665   }
9666 
9667   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9668   // adding or subtracting 1 from one of the operands.
9669   switch (Pred) {
9670   case ICmpInst::ICMP_SLE:
9671     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9672       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9673                        SCEV::FlagNSW);
9674       Pred = ICmpInst::ICMP_SLT;
9675       Changed = true;
9676     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9677       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9678                        SCEV::FlagNSW);
9679       Pred = ICmpInst::ICMP_SLT;
9680       Changed = true;
9681     }
9682     break;
9683   case ICmpInst::ICMP_SGE:
9684     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9685       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9686                        SCEV::FlagNSW);
9687       Pred = ICmpInst::ICMP_SGT;
9688       Changed = true;
9689     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9690       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9691                        SCEV::FlagNSW);
9692       Pred = ICmpInst::ICMP_SGT;
9693       Changed = true;
9694     }
9695     break;
9696   case ICmpInst::ICMP_ULE:
9697     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9698       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9699                        SCEV::FlagNUW);
9700       Pred = ICmpInst::ICMP_ULT;
9701       Changed = true;
9702     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9703       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9704       Pred = ICmpInst::ICMP_ULT;
9705       Changed = true;
9706     }
9707     break;
9708   case ICmpInst::ICMP_UGE:
9709     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9710       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9711       Pred = ICmpInst::ICMP_UGT;
9712       Changed = true;
9713     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9714       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9715                        SCEV::FlagNUW);
9716       Pred = ICmpInst::ICMP_UGT;
9717       Changed = true;
9718     }
9719     break;
9720   default:
9721     break;
9722   }
9723 
9724   // TODO: More simplifications are possible here.
9725 
9726   // Recursively simplify until we either hit a recursion limit or nothing
9727   // changes.
9728   if (Changed)
9729     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9730 
9731   return Changed;
9732 }
9733 
9734 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9735   return getSignedRangeMax(S).isNegative();
9736 }
9737 
9738 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9739   return getSignedRangeMin(S).isStrictlyPositive();
9740 }
9741 
9742 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9743   return !getSignedRangeMin(S).isNegative();
9744 }
9745 
9746 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9747   return !getSignedRangeMax(S).isStrictlyPositive();
9748 }
9749 
9750 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9751   return isKnownNegative(S) || isKnownPositive(S);
9752 }
9753 
9754 std::pair<const SCEV *, const SCEV *>
9755 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9756   // Compute SCEV on entry of loop L.
9757   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9758   if (Start == getCouldNotCompute())
9759     return { Start, Start };
9760   // Compute post increment SCEV for loop L.
9761   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9762   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9763   return { Start, PostInc };
9764 }
9765 
9766 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9767                                           const SCEV *LHS, const SCEV *RHS) {
9768   // First collect all loops.
9769   SmallPtrSet<const Loop *, 8> LoopsUsed;
9770   getUsedLoops(LHS, LoopsUsed);
9771   getUsedLoops(RHS, LoopsUsed);
9772 
9773   if (LoopsUsed.empty())
9774     return false;
9775 
9776   // Domination relationship must be a linear order on collected loops.
9777 #ifndef NDEBUG
9778   for (auto *L1 : LoopsUsed)
9779     for (auto *L2 : LoopsUsed)
9780       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9781               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9782              "Domination relationship is not a linear order");
9783 #endif
9784 
9785   const Loop *MDL =
9786       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9787                         [&](const Loop *L1, const Loop *L2) {
9788          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9789        });
9790 
9791   // Get init and post increment value for LHS.
9792   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9793   // if LHS contains unknown non-invariant SCEV then bail out.
9794   if (SplitLHS.first == getCouldNotCompute())
9795     return false;
9796   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9797   // Get init and post increment value for RHS.
9798   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9799   // if RHS contains unknown non-invariant SCEV then bail out.
9800   if (SplitRHS.first == getCouldNotCompute())
9801     return false;
9802   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9803   // It is possible that init SCEV contains an invariant load but it does
9804   // not dominate MDL and is not available at MDL loop entry, so we should
9805   // check it here.
9806   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9807       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9808     return false;
9809 
9810   // It seems backedge guard check is faster than entry one so in some cases
9811   // it can speed up whole estimation by short circuit
9812   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9813                                      SplitRHS.second) &&
9814          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9815 }
9816 
9817 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9818                                        const SCEV *LHS, const SCEV *RHS) {
9819   // Canonicalize the inputs first.
9820   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9821 
9822   if (isKnownViaInduction(Pred, LHS, RHS))
9823     return true;
9824 
9825   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9826     return true;
9827 
9828   // Otherwise see what can be done with some simple reasoning.
9829   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9830 }
9831 
9832 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
9833                                                   const SCEV *LHS,
9834                                                   const SCEV *RHS) {
9835   if (isKnownPredicate(Pred, LHS, RHS))
9836     return true;
9837   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
9838     return false;
9839   return None;
9840 }
9841 
9842 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9843                                          const SCEV *LHS, const SCEV *RHS,
9844                                          const Instruction *Context) {
9845   // TODO: Analyze guards and assumes from Context's block.
9846   return isKnownPredicate(Pred, LHS, RHS) ||
9847          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9848 }
9849 
9850 Optional<bool>
9851 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
9852                                      const SCEV *RHS,
9853                                      const Instruction *Context) {
9854   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
9855   if (KnownWithoutContext)
9856     return KnownWithoutContext;
9857 
9858   if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS))
9859     return true;
9860   else if (isBasicBlockEntryGuardedByCond(Context->getParent(),
9861                                           ICmpInst::getInversePredicate(Pred),
9862                                           LHS, RHS))
9863     return false;
9864   return None;
9865 }
9866 
9867 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9868                                               const SCEVAddRecExpr *LHS,
9869                                               const SCEV *RHS) {
9870   const Loop *L = LHS->getLoop();
9871   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9872          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9873 }
9874 
9875 Optional<ScalarEvolution::MonotonicPredicateType>
9876 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9877                                            ICmpInst::Predicate Pred) {
9878   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9879 
9880 #ifndef NDEBUG
9881   // Verify an invariant: inverting the predicate should turn a monotonically
9882   // increasing change to a monotonically decreasing one, and vice versa.
9883   if (Result) {
9884     auto ResultSwapped =
9885         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9886 
9887     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9888     assert(ResultSwapped.getValue() != Result.getValue() &&
9889            "monotonicity should flip as we flip the predicate");
9890   }
9891 #endif
9892 
9893   return Result;
9894 }
9895 
9896 Optional<ScalarEvolution::MonotonicPredicateType>
9897 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9898                                                ICmpInst::Predicate Pred) {
9899   // A zero step value for LHS means the induction variable is essentially a
9900   // loop invariant value. We don't really depend on the predicate actually
9901   // flipping from false to true (for increasing predicates, and the other way
9902   // around for decreasing predicates), all we care about is that *if* the
9903   // predicate changes then it only changes from false to true.
9904   //
9905   // A zero step value in itself is not very useful, but there may be places
9906   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9907   // as general as possible.
9908 
9909   // Only handle LE/LT/GE/GT predicates.
9910   if (!ICmpInst::isRelational(Pred))
9911     return None;
9912 
9913   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9914   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9915          "Should be greater or less!");
9916 
9917   // Check that AR does not wrap.
9918   if (ICmpInst::isUnsigned(Pred)) {
9919     if (!LHS->hasNoUnsignedWrap())
9920       return None;
9921     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9922   } else {
9923     assert(ICmpInst::isSigned(Pred) &&
9924            "Relational predicate is either signed or unsigned!");
9925     if (!LHS->hasNoSignedWrap())
9926       return None;
9927 
9928     const SCEV *Step = LHS->getStepRecurrence(*this);
9929 
9930     if (isKnownNonNegative(Step))
9931       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9932 
9933     if (isKnownNonPositive(Step))
9934       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9935 
9936     return None;
9937   }
9938 }
9939 
9940 Optional<ScalarEvolution::LoopInvariantPredicate>
9941 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9942                                            const SCEV *LHS, const SCEV *RHS,
9943                                            const Loop *L) {
9944 
9945   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9946   if (!isLoopInvariant(RHS, L)) {
9947     if (!isLoopInvariant(LHS, L))
9948       return None;
9949 
9950     std::swap(LHS, RHS);
9951     Pred = ICmpInst::getSwappedPredicate(Pred);
9952   }
9953 
9954   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9955   if (!ArLHS || ArLHS->getLoop() != L)
9956     return None;
9957 
9958   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9959   if (!MonotonicType)
9960     return None;
9961   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9962   // true as the loop iterates, and the backedge is control dependent on
9963   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9964   //
9965   //   * if the predicate was false in the first iteration then the predicate
9966   //     is never evaluated again, since the loop exits without taking the
9967   //     backedge.
9968   //   * if the predicate was true in the first iteration then it will
9969   //     continue to be true for all future iterations since it is
9970   //     monotonically increasing.
9971   //
9972   // For both the above possibilities, we can replace the loop varying
9973   // predicate with its value on the first iteration of the loop (which is
9974   // loop invariant).
9975   //
9976   // A similar reasoning applies for a monotonically decreasing predicate, by
9977   // replacing true with false and false with true in the above two bullets.
9978   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9979   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9980 
9981   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9982     return None;
9983 
9984   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9985 }
9986 
9987 Optional<ScalarEvolution::LoopInvariantPredicate>
9988 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9989     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9990     const Instruction *Context, const SCEV *MaxIter) {
9991   // Try to prove the following set of facts:
9992   // - The predicate is monotonic in the iteration space.
9993   // - If the check does not fail on the 1st iteration:
9994   //   - No overflow will happen during first MaxIter iterations;
9995   //   - It will not fail on the MaxIter'th iteration.
9996   // If the check does fail on the 1st iteration, we leave the loop and no
9997   // other checks matter.
9998 
9999   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10000   if (!isLoopInvariant(RHS, L)) {
10001     if (!isLoopInvariant(LHS, L))
10002       return None;
10003 
10004     std::swap(LHS, RHS);
10005     Pred = ICmpInst::getSwappedPredicate(Pred);
10006   }
10007 
10008   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10009   if (!AR || AR->getLoop() != L)
10010     return None;
10011 
10012   // The predicate must be relational (i.e. <, <=, >=, >).
10013   if (!ICmpInst::isRelational(Pred))
10014     return None;
10015 
10016   // TODO: Support steps other than +/- 1.
10017   const SCEV *Step = AR->getStepRecurrence(*this);
10018   auto *One = getOne(Step->getType());
10019   auto *MinusOne = getNegativeSCEV(One);
10020   if (Step != One && Step != MinusOne)
10021     return None;
10022 
10023   // Type mismatch here means that MaxIter is potentially larger than max
10024   // unsigned value in start type, which mean we cannot prove no wrap for the
10025   // indvar.
10026   if (AR->getType() != MaxIter->getType())
10027     return None;
10028 
10029   // Value of IV on suggested last iteration.
10030   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10031   // Does it still meet the requirement?
10032   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10033     return None;
10034   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10035   // not exceed max unsigned value of this type), this effectively proves
10036   // that there is no wrap during the iteration. To prove that there is no
10037   // signed/unsigned wrap, we need to check that
10038   // Start <= Last for step = 1 or Start >= Last for step = -1.
10039   ICmpInst::Predicate NoOverflowPred =
10040       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10041   if (Step == MinusOne)
10042     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10043   const SCEV *Start = AR->getStart();
10044   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
10045     return None;
10046 
10047   // Everything is fine.
10048   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10049 }
10050 
10051 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10052     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10053   if (HasSameValue(LHS, RHS))
10054     return ICmpInst::isTrueWhenEqual(Pred);
10055 
10056   // This code is split out from isKnownPredicate because it is called from
10057   // within isLoopEntryGuardedByCond.
10058 
10059   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10060                          const ConstantRange &RangeRHS) {
10061     return RangeLHS.icmp(Pred, RangeRHS);
10062   };
10063 
10064   // The check at the top of the function catches the case where the values are
10065   // known to be equal.
10066   if (Pred == CmpInst::ICMP_EQ)
10067     return false;
10068 
10069   if (Pred == CmpInst::ICMP_NE)
10070     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10071            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
10072            isKnownNonZero(getMinusSCEV(LHS, RHS));
10073 
10074   if (CmpInst::isSigned(Pred))
10075     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10076 
10077   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10078 }
10079 
10080 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10081                                                     const SCEV *LHS,
10082                                                     const SCEV *RHS) {
10083   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10084   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10085   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10086   // OutC1 and OutC2.
10087   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10088                                       APInt &OutC1, APInt &OutC2,
10089                                       SCEV::NoWrapFlags ExpectedFlags) {
10090     const SCEV *XNonConstOp, *XConstOp;
10091     const SCEV *YNonConstOp, *YConstOp;
10092     SCEV::NoWrapFlags XFlagsPresent;
10093     SCEV::NoWrapFlags YFlagsPresent;
10094 
10095     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10096       XConstOp = getZero(X->getType());
10097       XNonConstOp = X;
10098       XFlagsPresent = ExpectedFlags;
10099     }
10100     if (!isa<SCEVConstant>(XConstOp) ||
10101         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10102       return false;
10103 
10104     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10105       YConstOp = getZero(Y->getType());
10106       YNonConstOp = Y;
10107       YFlagsPresent = ExpectedFlags;
10108     }
10109 
10110     if (!isa<SCEVConstant>(YConstOp) ||
10111         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10112       return false;
10113 
10114     if (YNonConstOp != XNonConstOp)
10115       return false;
10116 
10117     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10118     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10119 
10120     return true;
10121   };
10122 
10123   APInt C1;
10124   APInt C2;
10125 
10126   switch (Pred) {
10127   default:
10128     break;
10129 
10130   case ICmpInst::ICMP_SGE:
10131     std::swap(LHS, RHS);
10132     LLVM_FALLTHROUGH;
10133   case ICmpInst::ICMP_SLE:
10134     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10135     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10136       return true;
10137 
10138     break;
10139 
10140   case ICmpInst::ICMP_SGT:
10141     std::swap(LHS, RHS);
10142     LLVM_FALLTHROUGH;
10143   case ICmpInst::ICMP_SLT:
10144     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10145     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10146       return true;
10147 
10148     break;
10149 
10150   case ICmpInst::ICMP_UGE:
10151     std::swap(LHS, RHS);
10152     LLVM_FALLTHROUGH;
10153   case ICmpInst::ICMP_ULE:
10154     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10155     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10156       return true;
10157 
10158     break;
10159 
10160   case ICmpInst::ICMP_UGT:
10161     std::swap(LHS, RHS);
10162     LLVM_FALLTHROUGH;
10163   case ICmpInst::ICMP_ULT:
10164     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10165     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10166       return true;
10167     break;
10168   }
10169 
10170   return false;
10171 }
10172 
10173 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10174                                                    const SCEV *LHS,
10175                                                    const SCEV *RHS) {
10176   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10177     return false;
10178 
10179   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10180   // the stack can result in exponential time complexity.
10181   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10182 
10183   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10184   //
10185   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10186   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10187   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10188   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10189   // use isKnownPredicate later if needed.
10190   return isKnownNonNegative(RHS) &&
10191          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10192          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10193 }
10194 
10195 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10196                                         ICmpInst::Predicate Pred,
10197                                         const SCEV *LHS, const SCEV *RHS) {
10198   // No need to even try if we know the module has no guards.
10199   if (!HasGuards)
10200     return false;
10201 
10202   return any_of(*BB, [&](const Instruction &I) {
10203     using namespace llvm::PatternMatch;
10204 
10205     Value *Condition;
10206     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10207                          m_Value(Condition))) &&
10208            isImpliedCond(Pred, LHS, RHS, Condition, false);
10209   });
10210 }
10211 
10212 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10213 /// protected by a conditional between LHS and RHS.  This is used to
10214 /// to eliminate casts.
10215 bool
10216 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10217                                              ICmpInst::Predicate Pred,
10218                                              const SCEV *LHS, const SCEV *RHS) {
10219   // Interpret a null as meaning no loop, where there is obviously no guard
10220   // (interprocedural conditions notwithstanding).
10221   if (!L) return true;
10222 
10223   if (VerifyIR)
10224     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10225            "This cannot be done on broken IR!");
10226 
10227 
10228   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10229     return true;
10230 
10231   BasicBlock *Latch = L->getLoopLatch();
10232   if (!Latch)
10233     return false;
10234 
10235   BranchInst *LoopContinuePredicate =
10236     dyn_cast<BranchInst>(Latch->getTerminator());
10237   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10238       isImpliedCond(Pred, LHS, RHS,
10239                     LoopContinuePredicate->getCondition(),
10240                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10241     return true;
10242 
10243   // We don't want more than one activation of the following loops on the stack
10244   // -- that can lead to O(n!) time complexity.
10245   if (WalkingBEDominatingConds)
10246     return false;
10247 
10248   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10249 
10250   // See if we can exploit a trip count to prove the predicate.
10251   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10252   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10253   if (LatchBECount != getCouldNotCompute()) {
10254     // We know that Latch branches back to the loop header exactly
10255     // LatchBECount times.  This means the backdege condition at Latch is
10256     // equivalent to  "{0,+,1} u< LatchBECount".
10257     Type *Ty = LatchBECount->getType();
10258     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10259     const SCEV *LoopCounter =
10260       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10261     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10262                       LatchBECount))
10263       return true;
10264   }
10265 
10266   // Check conditions due to any @llvm.assume intrinsics.
10267   for (auto &AssumeVH : AC.assumptions()) {
10268     if (!AssumeVH)
10269       continue;
10270     auto *CI = cast<CallInst>(AssumeVH);
10271     if (!DT.dominates(CI, Latch->getTerminator()))
10272       continue;
10273 
10274     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10275       return true;
10276   }
10277 
10278   // If the loop is not reachable from the entry block, we risk running into an
10279   // infinite loop as we walk up into the dom tree.  These loops do not matter
10280   // anyway, so we just return a conservative answer when we see them.
10281   if (!DT.isReachableFromEntry(L->getHeader()))
10282     return false;
10283 
10284   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10285     return true;
10286 
10287   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10288        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10289     assert(DTN && "should reach the loop header before reaching the root!");
10290 
10291     BasicBlock *BB = DTN->getBlock();
10292     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10293       return true;
10294 
10295     BasicBlock *PBB = BB->getSinglePredecessor();
10296     if (!PBB)
10297       continue;
10298 
10299     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10300     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10301       continue;
10302 
10303     Value *Condition = ContinuePredicate->getCondition();
10304 
10305     // If we have an edge `E` within the loop body that dominates the only
10306     // latch, the condition guarding `E` also guards the backedge.  This
10307     // reasoning works only for loops with a single latch.
10308 
10309     BasicBlockEdge DominatingEdge(PBB, BB);
10310     if (DominatingEdge.isSingleEdge()) {
10311       // We're constructively (and conservatively) enumerating edges within the
10312       // loop body that dominate the latch.  The dominator tree better agree
10313       // with us on this:
10314       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10315 
10316       if (isImpliedCond(Pred, LHS, RHS, Condition,
10317                         BB != ContinuePredicate->getSuccessor(0)))
10318         return true;
10319     }
10320   }
10321 
10322   return false;
10323 }
10324 
10325 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10326                                                      ICmpInst::Predicate Pred,
10327                                                      const SCEV *LHS,
10328                                                      const SCEV *RHS) {
10329   if (VerifyIR)
10330     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10331            "This cannot be done on broken IR!");
10332 
10333   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10334   // the facts (a >= b && a != b) separately. A typical situation is when the
10335   // non-strict comparison is known from ranges and non-equality is known from
10336   // dominating predicates. If we are proving strict comparison, we always try
10337   // to prove non-equality and non-strict comparison separately.
10338   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10339   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10340   bool ProvedNonStrictComparison = false;
10341   bool ProvedNonEquality = false;
10342 
10343   auto SplitAndProve =
10344     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10345     if (!ProvedNonStrictComparison)
10346       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10347     if (!ProvedNonEquality)
10348       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10349     if (ProvedNonStrictComparison && ProvedNonEquality)
10350       return true;
10351     return false;
10352   };
10353 
10354   if (ProvingStrictComparison) {
10355     auto ProofFn = [&](ICmpInst::Predicate P) {
10356       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10357     };
10358     if (SplitAndProve(ProofFn))
10359       return true;
10360   }
10361 
10362   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10363   auto ProveViaGuard = [&](const BasicBlock *Block) {
10364     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10365       return true;
10366     if (ProvingStrictComparison) {
10367       auto ProofFn = [&](ICmpInst::Predicate P) {
10368         return isImpliedViaGuard(Block, P, LHS, RHS);
10369       };
10370       if (SplitAndProve(ProofFn))
10371         return true;
10372     }
10373     return false;
10374   };
10375 
10376   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10377   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10378     const Instruction *Context = &BB->front();
10379     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10380       return true;
10381     if (ProvingStrictComparison) {
10382       auto ProofFn = [&](ICmpInst::Predicate P) {
10383         return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context);
10384       };
10385       if (SplitAndProve(ProofFn))
10386         return true;
10387     }
10388     return false;
10389   };
10390 
10391   // Starting at the block's predecessor, climb up the predecessor chain, as long
10392   // as there are predecessors that can be found that have unique successors
10393   // leading to the original block.
10394   const Loop *ContainingLoop = LI.getLoopFor(BB);
10395   const BasicBlock *PredBB;
10396   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10397     PredBB = ContainingLoop->getLoopPredecessor();
10398   else
10399     PredBB = BB->getSinglePredecessor();
10400   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10401        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10402     if (ProveViaGuard(Pair.first))
10403       return true;
10404 
10405     const BranchInst *LoopEntryPredicate =
10406         dyn_cast<BranchInst>(Pair.first->getTerminator());
10407     if (!LoopEntryPredicate ||
10408         LoopEntryPredicate->isUnconditional())
10409       continue;
10410 
10411     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10412                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10413       return true;
10414   }
10415 
10416   // Check conditions due to any @llvm.assume intrinsics.
10417   for (auto &AssumeVH : AC.assumptions()) {
10418     if (!AssumeVH)
10419       continue;
10420     auto *CI = cast<CallInst>(AssumeVH);
10421     if (!DT.dominates(CI, BB))
10422       continue;
10423 
10424     if (ProveViaCond(CI->getArgOperand(0), false))
10425       return true;
10426   }
10427 
10428   return false;
10429 }
10430 
10431 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10432                                                ICmpInst::Predicate Pred,
10433                                                const SCEV *LHS,
10434                                                const SCEV *RHS) {
10435   // Interpret a null as meaning no loop, where there is obviously no guard
10436   // (interprocedural conditions notwithstanding).
10437   if (!L)
10438     return false;
10439 
10440   // Both LHS and RHS must be available at loop entry.
10441   assert(isAvailableAtLoopEntry(LHS, L) &&
10442          "LHS is not available at Loop Entry");
10443   assert(isAvailableAtLoopEntry(RHS, L) &&
10444          "RHS is not available at Loop Entry");
10445 
10446   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10447     return true;
10448 
10449   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10450 }
10451 
10452 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10453                                     const SCEV *RHS,
10454                                     const Value *FoundCondValue, bool Inverse,
10455                                     const Instruction *Context) {
10456   // False conditions implies anything. Do not bother analyzing it further.
10457   if (FoundCondValue ==
10458       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10459     return true;
10460 
10461   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10462     return false;
10463 
10464   auto ClearOnExit =
10465       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10466 
10467   // Recursively handle And and Or conditions.
10468   const Value *Op0, *Op1;
10469   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10470     if (!Inverse)
10471       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10472               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10473   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10474     if (Inverse)
10475       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10476               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10477   }
10478 
10479   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10480   if (!ICI) return false;
10481 
10482   // Now that we found a conditional branch that dominates the loop or controls
10483   // the loop latch. Check to see if it is the comparison we are looking for.
10484   ICmpInst::Predicate FoundPred;
10485   if (Inverse)
10486     FoundPred = ICI->getInversePredicate();
10487   else
10488     FoundPred = ICI->getPredicate();
10489 
10490   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10491   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10492 
10493   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10494 }
10495 
10496 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10497                                     const SCEV *RHS,
10498                                     ICmpInst::Predicate FoundPred,
10499                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10500                                     const Instruction *Context) {
10501   // Balance the types.
10502   if (getTypeSizeInBits(LHS->getType()) <
10503       getTypeSizeInBits(FoundLHS->getType())) {
10504     // For unsigned and equality predicates, try to prove that both found
10505     // operands fit into narrow unsigned range. If so, try to prove facts in
10506     // narrow types.
10507     if (!CmpInst::isSigned(FoundPred)) {
10508       auto *NarrowType = LHS->getType();
10509       auto *WideType = FoundLHS->getType();
10510       auto BitWidth = getTypeSizeInBits(NarrowType);
10511       const SCEV *MaxValue = getZeroExtendExpr(
10512           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10513       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10514           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10515         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10516         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10517         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10518                                        TruncFoundRHS, Context))
10519           return true;
10520       }
10521     }
10522 
10523     if (CmpInst::isSigned(Pred)) {
10524       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10525       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10526     } else {
10527       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10528       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10529     }
10530   } else if (getTypeSizeInBits(LHS->getType()) >
10531       getTypeSizeInBits(FoundLHS->getType())) {
10532     if (CmpInst::isSigned(FoundPred)) {
10533       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10534       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10535     } else {
10536       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10537       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10538     }
10539   }
10540   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10541                                     FoundRHS, Context);
10542 }
10543 
10544 bool ScalarEvolution::isImpliedCondBalancedTypes(
10545     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10546     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10547     const Instruction *Context) {
10548   assert(getTypeSizeInBits(LHS->getType()) ==
10549              getTypeSizeInBits(FoundLHS->getType()) &&
10550          "Types should be balanced!");
10551   // Canonicalize the query to match the way instcombine will have
10552   // canonicalized the comparison.
10553   if (SimplifyICmpOperands(Pred, LHS, RHS))
10554     if (LHS == RHS)
10555       return CmpInst::isTrueWhenEqual(Pred);
10556   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10557     if (FoundLHS == FoundRHS)
10558       return CmpInst::isFalseWhenEqual(FoundPred);
10559 
10560   // Check to see if we can make the LHS or RHS match.
10561   if (LHS == FoundRHS || RHS == FoundLHS) {
10562     if (isa<SCEVConstant>(RHS)) {
10563       std::swap(FoundLHS, FoundRHS);
10564       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10565     } else {
10566       std::swap(LHS, RHS);
10567       Pred = ICmpInst::getSwappedPredicate(Pred);
10568     }
10569   }
10570 
10571   // Check whether the found predicate is the same as the desired predicate.
10572   if (FoundPred == Pred)
10573     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10574 
10575   // Check whether swapping the found predicate makes it the same as the
10576   // desired predicate.
10577   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10578     // We can write the implication
10579     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10580     // using one of the following ways:
10581     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10582     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10583     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10584     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10585     // Forms 1. and 2. require swapping the operands of one condition. Don't
10586     // do this if it would break canonical constant/addrec ordering.
10587     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10588       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10589                                    Context);
10590     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10591       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10592 
10593     // There's no clear preference between forms 3. and 4., try both.
10594     return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10595                                  FoundLHS, FoundRHS, Context) ||
10596            isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10597                                  getNotSCEV(FoundRHS), Context);
10598   }
10599 
10600   // Unsigned comparison is the same as signed comparison when both the operands
10601   // are non-negative.
10602   if (CmpInst::isUnsigned(FoundPred) &&
10603       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10604       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10605     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10606 
10607   // Check if we can make progress by sharpening ranges.
10608   if (FoundPred == ICmpInst::ICMP_NE &&
10609       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10610 
10611     const SCEVConstant *C = nullptr;
10612     const SCEV *V = nullptr;
10613 
10614     if (isa<SCEVConstant>(FoundLHS)) {
10615       C = cast<SCEVConstant>(FoundLHS);
10616       V = FoundRHS;
10617     } else {
10618       C = cast<SCEVConstant>(FoundRHS);
10619       V = FoundLHS;
10620     }
10621 
10622     // The guarding predicate tells us that C != V. If the known range
10623     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10624     // range we consider has to correspond to same signedness as the
10625     // predicate we're interested in folding.
10626 
10627     APInt Min = ICmpInst::isSigned(Pred) ?
10628         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10629 
10630     if (Min == C->getAPInt()) {
10631       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10632       // This is true even if (Min + 1) wraps around -- in case of
10633       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10634 
10635       APInt SharperMin = Min + 1;
10636 
10637       switch (Pred) {
10638         case ICmpInst::ICMP_SGE:
10639         case ICmpInst::ICMP_UGE:
10640           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10641           // RHS, we're done.
10642           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10643                                     Context))
10644             return true;
10645           LLVM_FALLTHROUGH;
10646 
10647         case ICmpInst::ICMP_SGT:
10648         case ICmpInst::ICMP_UGT:
10649           // We know from the range information that (V `Pred` Min ||
10650           // V == Min).  We know from the guarding condition that !(V
10651           // == Min).  This gives us
10652           //
10653           //       V `Pred` Min || V == Min && !(V == Min)
10654           //   =>  V `Pred` Min
10655           //
10656           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10657 
10658           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10659                                     Context))
10660             return true;
10661           break;
10662 
10663         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10664         case ICmpInst::ICMP_SLE:
10665         case ICmpInst::ICMP_ULE:
10666           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10667                                     LHS, V, getConstant(SharperMin), Context))
10668             return true;
10669           LLVM_FALLTHROUGH;
10670 
10671         case ICmpInst::ICMP_SLT:
10672         case ICmpInst::ICMP_ULT:
10673           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10674                                     LHS, V, getConstant(Min), Context))
10675             return true;
10676           break;
10677 
10678         default:
10679           // No change
10680           break;
10681       }
10682     }
10683   }
10684 
10685   // Check whether the actual condition is beyond sufficient.
10686   if (FoundPred == ICmpInst::ICMP_EQ)
10687     if (ICmpInst::isTrueWhenEqual(Pred))
10688       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10689         return true;
10690   if (Pred == ICmpInst::ICMP_NE)
10691     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10692       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10693                                 Context))
10694         return true;
10695 
10696   // Otherwise assume the worst.
10697   return false;
10698 }
10699 
10700 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10701                                      const SCEV *&L, const SCEV *&R,
10702                                      SCEV::NoWrapFlags &Flags) {
10703   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10704   if (!AE || AE->getNumOperands() != 2)
10705     return false;
10706 
10707   L = AE->getOperand(0);
10708   R = AE->getOperand(1);
10709   Flags = AE->getNoWrapFlags();
10710   return true;
10711 }
10712 
10713 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10714                                                            const SCEV *Less) {
10715   // We avoid subtracting expressions here because this function is usually
10716   // fairly deep in the call stack (i.e. is called many times).
10717 
10718   // X - X = 0.
10719   if (More == Less)
10720     return APInt(getTypeSizeInBits(More->getType()), 0);
10721 
10722   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10723     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10724     const auto *MAR = cast<SCEVAddRecExpr>(More);
10725 
10726     if (LAR->getLoop() != MAR->getLoop())
10727       return None;
10728 
10729     // We look at affine expressions only; not for correctness but to keep
10730     // getStepRecurrence cheap.
10731     if (!LAR->isAffine() || !MAR->isAffine())
10732       return None;
10733 
10734     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10735       return None;
10736 
10737     Less = LAR->getStart();
10738     More = MAR->getStart();
10739 
10740     // fall through
10741   }
10742 
10743   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10744     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10745     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10746     return M - L;
10747   }
10748 
10749   SCEV::NoWrapFlags Flags;
10750   const SCEV *LLess = nullptr, *RLess = nullptr;
10751   const SCEV *LMore = nullptr, *RMore = nullptr;
10752   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10753   // Compare (X + C1) vs X.
10754   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10755     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10756       if (RLess == More)
10757         return -(C1->getAPInt());
10758 
10759   // Compare X vs (X + C2).
10760   if (splitBinaryAdd(More, LMore, RMore, Flags))
10761     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10762       if (RMore == Less)
10763         return C2->getAPInt();
10764 
10765   // Compare (X + C1) vs (X + C2).
10766   if (C1 && C2 && RLess == RMore)
10767     return C2->getAPInt() - C1->getAPInt();
10768 
10769   return None;
10770 }
10771 
10772 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10773     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10774     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10775   // Try to recognize the following pattern:
10776   //
10777   //   FoundRHS = ...
10778   // ...
10779   // loop:
10780   //   FoundLHS = {Start,+,W}
10781   // context_bb: // Basic block from the same loop
10782   //   known(Pred, FoundLHS, FoundRHS)
10783   //
10784   // If some predicate is known in the context of a loop, it is also known on
10785   // each iteration of this loop, including the first iteration. Therefore, in
10786   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10787   // prove the original pred using this fact.
10788   if (!Context)
10789     return false;
10790   const BasicBlock *ContextBB = Context->getParent();
10791   // Make sure AR varies in the context block.
10792   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10793     const Loop *L = AR->getLoop();
10794     // Make sure that context belongs to the loop and executes on 1st iteration
10795     // (if it ever executes at all).
10796     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10797       return false;
10798     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10799       return false;
10800     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10801   }
10802 
10803   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10804     const Loop *L = AR->getLoop();
10805     // Make sure that context belongs to the loop and executes on 1st iteration
10806     // (if it ever executes at all).
10807     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10808       return false;
10809     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10810       return false;
10811     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10812   }
10813 
10814   return false;
10815 }
10816 
10817 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10818     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10819     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10820   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10821     return false;
10822 
10823   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10824   if (!AddRecLHS)
10825     return false;
10826 
10827   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10828   if (!AddRecFoundLHS)
10829     return false;
10830 
10831   // We'd like to let SCEV reason about control dependencies, so we constrain
10832   // both the inequalities to be about add recurrences on the same loop.  This
10833   // way we can use isLoopEntryGuardedByCond later.
10834 
10835   const Loop *L = AddRecFoundLHS->getLoop();
10836   if (L != AddRecLHS->getLoop())
10837     return false;
10838 
10839   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10840   //
10841   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10842   //                                                                  ... (2)
10843   //
10844   // Informal proof for (2), assuming (1) [*]:
10845   //
10846   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10847   //
10848   // Then
10849   //
10850   //       FoundLHS s< FoundRHS s< INT_MIN - C
10851   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10852   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10853   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10854   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10855   // <=>  FoundLHS + C s< FoundRHS + C
10856   //
10857   // [*]: (1) can be proved by ruling out overflow.
10858   //
10859   // [**]: This can be proved by analyzing all the four possibilities:
10860   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10861   //    (A s>= 0, B s>= 0).
10862   //
10863   // Note:
10864   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10865   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10866   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10867   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10868   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10869   // C)".
10870 
10871   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10872   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10873   if (!LDiff || !RDiff || *LDiff != *RDiff)
10874     return false;
10875 
10876   if (LDiff->isMinValue())
10877     return true;
10878 
10879   APInt FoundRHSLimit;
10880 
10881   if (Pred == CmpInst::ICMP_ULT) {
10882     FoundRHSLimit = -(*RDiff);
10883   } else {
10884     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10885     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10886   }
10887 
10888   // Try to prove (1) or (2), as needed.
10889   return isAvailableAtLoopEntry(FoundRHS, L) &&
10890          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10891                                   getConstant(FoundRHSLimit));
10892 }
10893 
10894 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10895                                         const SCEV *LHS, const SCEV *RHS,
10896                                         const SCEV *FoundLHS,
10897                                         const SCEV *FoundRHS, unsigned Depth) {
10898   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10899 
10900   auto ClearOnExit = make_scope_exit([&]() {
10901     if (LPhi) {
10902       bool Erased = PendingMerges.erase(LPhi);
10903       assert(Erased && "Failed to erase LPhi!");
10904       (void)Erased;
10905     }
10906     if (RPhi) {
10907       bool Erased = PendingMerges.erase(RPhi);
10908       assert(Erased && "Failed to erase RPhi!");
10909       (void)Erased;
10910     }
10911   });
10912 
10913   // Find respective Phis and check that they are not being pending.
10914   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10915     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10916       if (!PendingMerges.insert(Phi).second)
10917         return false;
10918       LPhi = Phi;
10919     }
10920   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10921     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10922       // If we detect a loop of Phi nodes being processed by this method, for
10923       // example:
10924       //
10925       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10926       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10927       //
10928       // we don't want to deal with a case that complex, so return conservative
10929       // answer false.
10930       if (!PendingMerges.insert(Phi).second)
10931         return false;
10932       RPhi = Phi;
10933     }
10934 
10935   // If none of LHS, RHS is a Phi, nothing to do here.
10936   if (!LPhi && !RPhi)
10937     return false;
10938 
10939   // If there is a SCEVUnknown Phi we are interested in, make it left.
10940   if (!LPhi) {
10941     std::swap(LHS, RHS);
10942     std::swap(FoundLHS, FoundRHS);
10943     std::swap(LPhi, RPhi);
10944     Pred = ICmpInst::getSwappedPredicate(Pred);
10945   }
10946 
10947   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10948   const BasicBlock *LBB = LPhi->getParent();
10949   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10950 
10951   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10952     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10953            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10954            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10955   };
10956 
10957   if (RPhi && RPhi->getParent() == LBB) {
10958     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10959     // If we compare two Phis from the same block, and for each entry block
10960     // the predicate is true for incoming values from this block, then the
10961     // predicate is also true for the Phis.
10962     for (const BasicBlock *IncBB : predecessors(LBB)) {
10963       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10964       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10965       if (!ProvedEasily(L, R))
10966         return false;
10967     }
10968   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10969     // Case two: RHS is also a Phi from the same basic block, and it is an
10970     // AddRec. It means that there is a loop which has both AddRec and Unknown
10971     // PHIs, for it we can compare incoming values of AddRec from above the loop
10972     // and latch with their respective incoming values of LPhi.
10973     // TODO: Generalize to handle loops with many inputs in a header.
10974     if (LPhi->getNumIncomingValues() != 2) return false;
10975 
10976     auto *RLoop = RAR->getLoop();
10977     auto *Predecessor = RLoop->getLoopPredecessor();
10978     assert(Predecessor && "Loop with AddRec with no predecessor?");
10979     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10980     if (!ProvedEasily(L1, RAR->getStart()))
10981       return false;
10982     auto *Latch = RLoop->getLoopLatch();
10983     assert(Latch && "Loop with AddRec with no latch?");
10984     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10985     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10986       return false;
10987   } else {
10988     // In all other cases go over inputs of LHS and compare each of them to RHS,
10989     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10990     // At this point RHS is either a non-Phi, or it is a Phi from some block
10991     // different from LBB.
10992     for (const BasicBlock *IncBB : predecessors(LBB)) {
10993       // Check that RHS is available in this block.
10994       if (!dominates(RHS, IncBB))
10995         return false;
10996       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10997       // Make sure L does not refer to a value from a potentially previous
10998       // iteration of a loop.
10999       if (!properlyDominates(L, IncBB))
11000         return false;
11001       if (!ProvedEasily(L, RHS))
11002         return false;
11003     }
11004   }
11005   return true;
11006 }
11007 
11008 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11009                                             const SCEV *LHS, const SCEV *RHS,
11010                                             const SCEV *FoundLHS,
11011                                             const SCEV *FoundRHS,
11012                                             const Instruction *Context) {
11013   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11014     return true;
11015 
11016   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11017     return true;
11018 
11019   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11020                                           Context))
11021     return true;
11022 
11023   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11024                                      FoundLHS, FoundRHS);
11025 }
11026 
11027 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11028 template <typename MinMaxExprType>
11029 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11030                                  const SCEV *Candidate) {
11031   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11032   if (!MinMaxExpr)
11033     return false;
11034 
11035   return is_contained(MinMaxExpr->operands(), Candidate);
11036 }
11037 
11038 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11039                                            ICmpInst::Predicate Pred,
11040                                            const SCEV *LHS, const SCEV *RHS) {
11041   // If both sides are affine addrecs for the same loop, with equal
11042   // steps, and we know the recurrences don't wrap, then we only
11043   // need to check the predicate on the starting values.
11044 
11045   if (!ICmpInst::isRelational(Pred))
11046     return false;
11047 
11048   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11049   if (!LAR)
11050     return false;
11051   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11052   if (!RAR)
11053     return false;
11054   if (LAR->getLoop() != RAR->getLoop())
11055     return false;
11056   if (!LAR->isAffine() || !RAR->isAffine())
11057     return false;
11058 
11059   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11060     return false;
11061 
11062   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11063                          SCEV::FlagNSW : SCEV::FlagNUW;
11064   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11065     return false;
11066 
11067   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11068 }
11069 
11070 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11071 /// expression?
11072 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11073                                         ICmpInst::Predicate Pred,
11074                                         const SCEV *LHS, const SCEV *RHS) {
11075   switch (Pred) {
11076   default:
11077     return false;
11078 
11079   case ICmpInst::ICMP_SGE:
11080     std::swap(LHS, RHS);
11081     LLVM_FALLTHROUGH;
11082   case ICmpInst::ICMP_SLE:
11083     return
11084         // min(A, ...) <= A
11085         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11086         // A <= max(A, ...)
11087         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11088 
11089   case ICmpInst::ICMP_UGE:
11090     std::swap(LHS, RHS);
11091     LLVM_FALLTHROUGH;
11092   case ICmpInst::ICMP_ULE:
11093     return
11094         // min(A, ...) <= A
11095         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11096         // A <= max(A, ...)
11097         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11098   }
11099 
11100   llvm_unreachable("covered switch fell through?!");
11101 }
11102 
11103 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11104                                              const SCEV *LHS, const SCEV *RHS,
11105                                              const SCEV *FoundLHS,
11106                                              const SCEV *FoundRHS,
11107                                              unsigned Depth) {
11108   assert(getTypeSizeInBits(LHS->getType()) ==
11109              getTypeSizeInBits(RHS->getType()) &&
11110          "LHS and RHS have different sizes?");
11111   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11112              getTypeSizeInBits(FoundRHS->getType()) &&
11113          "FoundLHS and FoundRHS have different sizes?");
11114   // We want to avoid hurting the compile time with analysis of too big trees.
11115   if (Depth > MaxSCEVOperationsImplicationDepth)
11116     return false;
11117 
11118   // We only want to work with GT comparison so far.
11119   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11120     Pred = CmpInst::getSwappedPredicate(Pred);
11121     std::swap(LHS, RHS);
11122     std::swap(FoundLHS, FoundRHS);
11123   }
11124 
11125   // For unsigned, try to reduce it to corresponding signed comparison.
11126   if (Pred == ICmpInst::ICMP_UGT)
11127     // We can replace unsigned predicate with its signed counterpart if all
11128     // involved values are non-negative.
11129     // TODO: We could have better support for unsigned.
11130     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11131       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11132       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11133       // use this fact to prove that LHS and RHS are non-negative.
11134       const SCEV *MinusOne = getMinusOne(LHS->getType());
11135       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11136                                 FoundRHS) &&
11137           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11138                                 FoundRHS))
11139         Pred = ICmpInst::ICMP_SGT;
11140     }
11141 
11142   if (Pred != ICmpInst::ICMP_SGT)
11143     return false;
11144 
11145   auto GetOpFromSExt = [&](const SCEV *S) {
11146     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11147       return Ext->getOperand();
11148     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11149     // the constant in some cases.
11150     return S;
11151   };
11152 
11153   // Acquire values from extensions.
11154   auto *OrigLHS = LHS;
11155   auto *OrigFoundLHS = FoundLHS;
11156   LHS = GetOpFromSExt(LHS);
11157   FoundLHS = GetOpFromSExt(FoundLHS);
11158 
11159   // Is the SGT predicate can be proved trivially or using the found context.
11160   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11161     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11162            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11163                                   FoundRHS, Depth + 1);
11164   };
11165 
11166   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11167     // We want to avoid creation of any new non-constant SCEV. Since we are
11168     // going to compare the operands to RHS, we should be certain that we don't
11169     // need any size extensions for this. So let's decline all cases when the
11170     // sizes of types of LHS and RHS do not match.
11171     // TODO: Maybe try to get RHS from sext to catch more cases?
11172     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11173       return false;
11174 
11175     // Should not overflow.
11176     if (!LHSAddExpr->hasNoSignedWrap())
11177       return false;
11178 
11179     auto *LL = LHSAddExpr->getOperand(0);
11180     auto *LR = LHSAddExpr->getOperand(1);
11181     auto *MinusOne = getMinusOne(RHS->getType());
11182 
11183     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11184     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11185       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11186     };
11187     // Try to prove the following rule:
11188     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11189     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11190     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11191       return true;
11192   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11193     Value *LL, *LR;
11194     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11195 
11196     using namespace llvm::PatternMatch;
11197 
11198     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11199       // Rules for division.
11200       // We are going to perform some comparisons with Denominator and its
11201       // derivative expressions. In general case, creating a SCEV for it may
11202       // lead to a complex analysis of the entire graph, and in particular it
11203       // can request trip count recalculation for the same loop. This would
11204       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11205       // this, we only want to create SCEVs that are constants in this section.
11206       // So we bail if Denominator is not a constant.
11207       if (!isa<ConstantInt>(LR))
11208         return false;
11209 
11210       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11211 
11212       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11213       // then a SCEV for the numerator already exists and matches with FoundLHS.
11214       auto *Numerator = getExistingSCEV(LL);
11215       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11216         return false;
11217 
11218       // Make sure that the numerator matches with FoundLHS and the denominator
11219       // is positive.
11220       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11221         return false;
11222 
11223       auto *DTy = Denominator->getType();
11224       auto *FRHSTy = FoundRHS->getType();
11225       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11226         // One of types is a pointer and another one is not. We cannot extend
11227         // them properly to a wider type, so let us just reject this case.
11228         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11229         // to avoid this check.
11230         return false;
11231 
11232       // Given that:
11233       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11234       auto *WTy = getWiderType(DTy, FRHSTy);
11235       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11236       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11237 
11238       // Try to prove the following rule:
11239       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11240       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11241       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11242       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11243       if (isKnownNonPositive(RHS) &&
11244           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11245         return true;
11246 
11247       // Try to prove the following rule:
11248       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11249       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11250       // If we divide it by Denominator > 2, then:
11251       // 1. If FoundLHS is negative, then the result is 0.
11252       // 2. If FoundLHS is non-negative, then the result is non-negative.
11253       // Anyways, the result is non-negative.
11254       auto *MinusOne = getMinusOne(WTy);
11255       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11256       if (isKnownNegative(RHS) &&
11257           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11258         return true;
11259     }
11260   }
11261 
11262   // If our expression contained SCEVUnknown Phis, and we split it down and now
11263   // need to prove something for them, try to prove the predicate for every
11264   // possible incoming values of those Phis.
11265   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11266     return true;
11267 
11268   return false;
11269 }
11270 
11271 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11272                                         const SCEV *LHS, const SCEV *RHS) {
11273   // zext x u<= sext x, sext x s<= zext x
11274   switch (Pred) {
11275   case ICmpInst::ICMP_SGE:
11276     std::swap(LHS, RHS);
11277     LLVM_FALLTHROUGH;
11278   case ICmpInst::ICMP_SLE: {
11279     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11280     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11281     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11282     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11283       return true;
11284     break;
11285   }
11286   case ICmpInst::ICMP_UGE:
11287     std::swap(LHS, RHS);
11288     LLVM_FALLTHROUGH;
11289   case ICmpInst::ICMP_ULE: {
11290     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11291     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11292     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11293     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11294       return true;
11295     break;
11296   }
11297   default:
11298     break;
11299   };
11300   return false;
11301 }
11302 
11303 bool
11304 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11305                                            const SCEV *LHS, const SCEV *RHS) {
11306   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11307          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11308          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11309          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11310          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11311 }
11312 
11313 bool
11314 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11315                                              const SCEV *LHS, const SCEV *RHS,
11316                                              const SCEV *FoundLHS,
11317                                              const SCEV *FoundRHS) {
11318   switch (Pred) {
11319   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11320   case ICmpInst::ICMP_EQ:
11321   case ICmpInst::ICMP_NE:
11322     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11323       return true;
11324     break;
11325   case ICmpInst::ICMP_SLT:
11326   case ICmpInst::ICMP_SLE:
11327     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11328         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11329       return true;
11330     break;
11331   case ICmpInst::ICMP_SGT:
11332   case ICmpInst::ICMP_SGE:
11333     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11334         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11335       return true;
11336     break;
11337   case ICmpInst::ICMP_ULT:
11338   case ICmpInst::ICMP_ULE:
11339     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11340         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11341       return true;
11342     break;
11343   case ICmpInst::ICMP_UGT:
11344   case ICmpInst::ICMP_UGE:
11345     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11346         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11347       return true;
11348     break;
11349   }
11350 
11351   // Maybe it can be proved via operations?
11352   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11353     return true;
11354 
11355   return false;
11356 }
11357 
11358 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11359                                                      const SCEV *LHS,
11360                                                      const SCEV *RHS,
11361                                                      const SCEV *FoundLHS,
11362                                                      const SCEV *FoundRHS) {
11363   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11364     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11365     // reduce the compile time impact of this optimization.
11366     return false;
11367 
11368   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11369   if (!Addend)
11370     return false;
11371 
11372   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11373 
11374   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11375   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11376   ConstantRange FoundLHSRange =
11377       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
11378 
11379   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11380   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11381 
11382   // We can also compute the range of values for `LHS` that satisfy the
11383   // consequent, "`LHS` `Pred` `RHS`":
11384   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11385   // The antecedent implies the consequent if every value of `LHS` that
11386   // satisfies the antecedent also satisfies the consequent.
11387   return LHSRange.icmp(Pred, ConstRHS);
11388 }
11389 
11390 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11391                                         bool IsSigned) {
11392   assert(isKnownPositive(Stride) && "Positive stride expected!");
11393 
11394   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11395   const SCEV *One = getOne(Stride->getType());
11396 
11397   if (IsSigned) {
11398     APInt MaxRHS = getSignedRangeMax(RHS);
11399     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11400     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11401 
11402     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11403     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11404   }
11405 
11406   APInt MaxRHS = getUnsignedRangeMax(RHS);
11407   APInt MaxValue = APInt::getMaxValue(BitWidth);
11408   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11409 
11410   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11411   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11412 }
11413 
11414 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11415                                         bool IsSigned) {
11416 
11417   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11418   const SCEV *One = getOne(Stride->getType());
11419 
11420   if (IsSigned) {
11421     APInt MinRHS = getSignedRangeMin(RHS);
11422     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11423     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11424 
11425     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11426     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11427   }
11428 
11429   APInt MinRHS = getUnsignedRangeMin(RHS);
11430   APInt MinValue = APInt::getMinValue(BitWidth);
11431   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11432 
11433   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11434   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11435 }
11436 
11437 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta,
11438                                             const SCEV *Step) {
11439   const SCEV *One = getOne(Step->getType());
11440   Delta = getAddExpr(Delta, getMinusSCEV(Step, One));
11441   return getUDivExpr(Delta, Step);
11442 }
11443 
11444 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11445                                                     const SCEV *Stride,
11446                                                     const SCEV *End,
11447                                                     unsigned BitWidth,
11448                                                     bool IsSigned) {
11449 
11450   assert(!isKnownNonPositive(Stride) &&
11451          "Stride is expected strictly positive!");
11452   // Calculate the maximum backedge count based on the range of values
11453   // permitted by Start, End, and Stride.
11454   const SCEV *MaxBECount;
11455   APInt MinStart =
11456       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11457 
11458   APInt StrideForMaxBECount =
11459       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11460 
11461   // We already know that the stride is positive, so we paper over conservatism
11462   // in our range computation by forcing StrideForMaxBECount to be at least one.
11463   // In theory this is unnecessary, but we expect MaxBECount to be a
11464   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11465   // is nothing to constant fold it to).
11466   APInt One(BitWidth, 1, IsSigned);
11467   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11468 
11469   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11470                             : APInt::getMaxValue(BitWidth);
11471   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11472 
11473   // Although End can be a MAX expression we estimate MaxEnd considering only
11474   // the case End = RHS of the loop termination condition. This is safe because
11475   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11476   // taken count.
11477   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11478                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11479 
11480   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11481                               getConstant(StrideForMaxBECount) /* Step */);
11482 
11483   return MaxBECount;
11484 }
11485 
11486 ScalarEvolution::ExitLimit
11487 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11488                                   const Loop *L, bool IsSigned,
11489                                   bool ControlsExit, bool AllowPredicates) {
11490   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11491 
11492   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11493   bool PredicatedIV = false;
11494 
11495   if (!IV && AllowPredicates) {
11496     // Try to make this an AddRec using runtime tests, in the first X
11497     // iterations of this loop, where X is the SCEV expression found by the
11498     // algorithm below.
11499     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11500     PredicatedIV = true;
11501   }
11502 
11503   // Avoid weird loops
11504   if (!IV || IV->getLoop() != L || !IV->isAffine())
11505     return getCouldNotCompute();
11506 
11507   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11508   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11509   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
11510 
11511   const SCEV *Stride = IV->getStepRecurrence(*this);
11512 
11513   bool PositiveStride = isKnownPositive(Stride);
11514 
11515   // Avoid negative or zero stride values.
11516   if (!PositiveStride) {
11517     // We can compute the correct backedge taken count for loops with unknown
11518     // strides if we can prove that the loop is not an infinite loop with side
11519     // effects. Here's the loop structure we are trying to handle -
11520     //
11521     // i = start
11522     // do {
11523     //   A[i] = i;
11524     //   i += s;
11525     // } while (i < end);
11526     //
11527     // The backedge taken count for such loops is evaluated as -
11528     // (max(end, start + stride) - start - 1) /u stride
11529     //
11530     // The additional preconditions that we need to check to prove correctness
11531     // of the above formula is as follows -
11532     //
11533     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11534     //    NoWrap flag).
11535     // b) loop is single exit with no side effects.
11536     //
11537     //
11538     // Precondition a) implies that if the stride is negative, this is a single
11539     // trip loop. The backedge taken count formula reduces to zero in this case.
11540     //
11541     // Precondition b) implies that the unknown stride cannot be zero otherwise
11542     // we have UB.
11543     //
11544     // The positive stride case is the same as isKnownPositive(Stride) returning
11545     // true (original behavior of the function).
11546     //
11547     // We want to make sure that the stride is truly unknown as there are edge
11548     // cases where ScalarEvolution propagates no wrap flags to the
11549     // post-increment/decrement IV even though the increment/decrement operation
11550     // itself is wrapping. The computed backedge taken count may be wrong in
11551     // such cases. This is prevented by checking that the stride is not known to
11552     // be either positive or non-positive. For example, no wrap flags are
11553     // propagated to the post-increment IV of this loop with a trip count of 2 -
11554     //
11555     // unsigned char i;
11556     // for(i=127; i<128; i+=129)
11557     //   A[i] = i;
11558     //
11559     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11560         !loopIsFiniteByAssumption(L))
11561       return getCouldNotCompute();
11562   } else if (!Stride->isOne() && !NoWrap) {
11563     auto isUBOnWrap = [&]() {
11564       // Can we prove this loop *must* be UB if overflow of IV occurs?
11565       // Reasoning goes as follows:
11566       // * Suppose the IV did self wrap.
11567       // * If Stride evenly divides the iteration space, then once wrap
11568       //   occurs, the loop must revisit the same values.
11569       // * We know that RHS is invariant, and that none of those values
11570       //   caused this exit to be taken previously.  Thus, this exit is
11571       //   dynamically dead.
11572       // * If this is the sole exit, then a dead exit implies the loop
11573       //   must be infinite if there are no abnormal exits.
11574       // * If the loop were infinite, then it must either not be mustprogress
11575       //   or have side effects. Otherwise, it must be UB.
11576       // * It can't (by assumption), be UB so we have contradicted our
11577       //   premise and can conclude the IV did not in fact self-wrap.
11578       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
11579       // follows trivially from the fact that every (un)signed-wrapped, but
11580       // not self-wrapped value must be LT than the last value before
11581       // (un)signed wrap.  Since we know that last value didn't exit, nor
11582       // will any smaller one.
11583 
11584       if (!isLoopInvariant(RHS, L))
11585         return false;
11586 
11587       auto *StrideC = dyn_cast<SCEVConstant>(Stride);
11588       if (!StrideC || !StrideC->getAPInt().isPowerOf2())
11589         return false;
11590 
11591       if (!ControlsExit || !loopHasNoAbnormalExits(L))
11592         return false;
11593 
11594       return loopIsFiniteByAssumption(L);
11595     };
11596 
11597     // Avoid proven overflow cases: this will ensure that the backedge taken
11598     // count will not generate any unsigned overflow. Relaxed no-overflow
11599     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11600     // undefined behaviors like the case of C language.
11601     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
11602       return getCouldNotCompute();
11603   }
11604 
11605   const SCEV *Start = IV->getStart();
11606 
11607   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
11608   // Use integer-typed versions for actual computation.
11609   const SCEV *OrigStart = Start;
11610   const SCEV *OrigRHS = RHS;
11611   if (Start->getType()->isPointerTy()) {
11612     Start = getLosslessPtrToIntExpr(Start);
11613     if (isa<SCEVCouldNotCompute>(Start))
11614       return Start;
11615   }
11616   if (RHS->getType()->isPointerTy()) {
11617     RHS = getLosslessPtrToIntExpr(RHS);
11618     if (isa<SCEVCouldNotCompute>(RHS))
11619       return RHS;
11620   }
11621 
11622   const SCEV *End = RHS;
11623   // When the RHS is not invariant, we do not know the end bound of the loop and
11624   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11625   // calculate the MaxBECount, given the start, stride and max value for the end
11626   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11627   // checked above).
11628   if (!isLoopInvariant(RHS, L)) {
11629     const SCEV *MaxBECount = computeMaxBECountForLT(
11630         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11631     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11632                      false /*MaxOrZero*/, Predicates);
11633   }
11634   // If the backedge is taken at least once, then it will be taken
11635   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11636   // is the LHS value of the less-than comparison the first time it is evaluated
11637   // and End is the RHS.
11638   const SCEV *BECountIfBackedgeTaken =
11639     computeBECount(getMinusSCEV(End, Start), Stride);
11640   // If the loop entry is guarded by the result of the backedge test of the
11641   // first loop iteration, then we know the backedge will be taken at least
11642   // once and so the backedge taken count is as above. If not then we use the
11643   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11644   // as if the backedge is taken at least once max(End,Start) is End and so the
11645   // result is as above, and if not max(End,Start) is Start so we get a backedge
11646   // count of zero.
11647   const SCEV *BECount;
11648   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(OrigStart, Stride), OrigRHS))
11649     BECount = BECountIfBackedgeTaken;
11650   else {
11651     // If we know that RHS >= Start in the context of loop, then we know that
11652     // max(RHS, Start) = RHS at this point.
11653     if (isLoopEntryGuardedByCond(
11654             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, OrigRHS, OrigStart))
11655       End = RHS;
11656     else
11657       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11658     BECount = computeBECount(getMinusSCEV(End, Start), Stride);
11659   }
11660 
11661   const SCEV *MaxBECount;
11662   bool MaxOrZero = false;
11663   if (isa<SCEVConstant>(BECount))
11664     MaxBECount = BECount;
11665   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11666     // If we know exactly how many times the backedge will be taken if it's
11667     // taken at least once, then the backedge count will either be that or
11668     // zero.
11669     MaxBECount = BECountIfBackedgeTaken;
11670     MaxOrZero = true;
11671   } else {
11672     MaxBECount = computeMaxBECountForLT(
11673         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11674   }
11675 
11676   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11677       !isa<SCEVCouldNotCompute>(BECount))
11678     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11679 
11680   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11681 }
11682 
11683 ScalarEvolution::ExitLimit
11684 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11685                                      const Loop *L, bool IsSigned,
11686                                      bool ControlsExit, bool AllowPredicates) {
11687   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11688   // We handle only IV > Invariant
11689   if (!isLoopInvariant(RHS, L))
11690     return getCouldNotCompute();
11691 
11692   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11693   if (!IV && AllowPredicates)
11694     // Try to make this an AddRec using runtime tests, in the first X
11695     // iterations of this loop, where X is the SCEV expression found by the
11696     // algorithm below.
11697     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11698 
11699   // Avoid weird loops
11700   if (!IV || IV->getLoop() != L || !IV->isAffine())
11701     return getCouldNotCompute();
11702 
11703   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11704   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11705   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
11706 
11707   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11708 
11709   // Avoid negative or zero stride values
11710   if (!isKnownPositive(Stride))
11711     return getCouldNotCompute();
11712 
11713   // Avoid proven overflow cases: this will ensure that the backedge taken count
11714   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11715   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11716   // behaviors like the case of C language.
11717   if (!Stride->isOne() && !NoWrap)
11718     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
11719       return getCouldNotCompute();
11720 
11721   const SCEV *Start = IV->getStart();
11722   const SCEV *End = RHS;
11723   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11724     // If we know that Start >= RHS in the context of loop, then we know that
11725     // min(RHS, Start) = RHS at this point.
11726     if (isLoopEntryGuardedByCond(
11727             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11728       End = RHS;
11729     else
11730       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11731   }
11732 
11733   if (Start->getType()->isPointerTy()) {
11734     Start = getLosslessPtrToIntExpr(Start);
11735     if (isa<SCEVCouldNotCompute>(Start))
11736       return Start;
11737   }
11738   if (End->getType()->isPointerTy()) {
11739     End = getLosslessPtrToIntExpr(End);
11740     if (isa<SCEVCouldNotCompute>(End))
11741       return End;
11742   }
11743 
11744   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride);
11745 
11746   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11747                             : getUnsignedRangeMax(Start);
11748 
11749   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11750                              : getUnsignedRangeMin(Stride);
11751 
11752   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11753   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11754                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11755 
11756   // Although End can be a MIN expression we estimate MinEnd considering only
11757   // the case End = RHS. This is safe because in the other case (Start - End)
11758   // is zero, leading to a zero maximum backedge taken count.
11759   APInt MinEnd =
11760     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11761              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11762 
11763   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11764                                ? BECount
11765                                : computeBECount(getConstant(MaxStart - MinEnd),
11766                                                 getConstant(MinStride));
11767 
11768   if (isa<SCEVCouldNotCompute>(MaxBECount))
11769     MaxBECount = BECount;
11770 
11771   return ExitLimit(BECount, MaxBECount, false, Predicates);
11772 }
11773 
11774 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11775                                                     ScalarEvolution &SE) const {
11776   if (Range.isFullSet())  // Infinite loop.
11777     return SE.getCouldNotCompute();
11778 
11779   // If the start is a non-zero constant, shift the range to simplify things.
11780   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11781     if (!SC->getValue()->isZero()) {
11782       SmallVector<const SCEV *, 4> Operands(operands());
11783       Operands[0] = SE.getZero(SC->getType());
11784       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11785                                              getNoWrapFlags(FlagNW));
11786       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11787         return ShiftedAddRec->getNumIterationsInRange(
11788             Range.subtract(SC->getAPInt()), SE);
11789       // This is strange and shouldn't happen.
11790       return SE.getCouldNotCompute();
11791     }
11792 
11793   // The only time we can solve this is when we have all constant indices.
11794   // Otherwise, we cannot determine the overflow conditions.
11795   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11796     return SE.getCouldNotCompute();
11797 
11798   // Okay at this point we know that all elements of the chrec are constants and
11799   // that the start element is zero.
11800 
11801   // First check to see if the range contains zero.  If not, the first
11802   // iteration exits.
11803   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11804   if (!Range.contains(APInt(BitWidth, 0)))
11805     return SE.getZero(getType());
11806 
11807   if (isAffine()) {
11808     // If this is an affine expression then we have this situation:
11809     //   Solve {0,+,A} in Range  ===  Ax in Range
11810 
11811     // We know that zero is in the range.  If A is positive then we know that
11812     // the upper value of the range must be the first possible exit value.
11813     // If A is negative then the lower of the range is the last possible loop
11814     // value.  Also note that we already checked for a full range.
11815     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11816     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11817 
11818     // The exit value should be (End+A)/A.
11819     APInt ExitVal = (End + A).udiv(A);
11820     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11821 
11822     // Evaluate at the exit value.  If we really did fall out of the valid
11823     // range, then we computed our trip count, otherwise wrap around or other
11824     // things must have happened.
11825     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11826     if (Range.contains(Val->getValue()))
11827       return SE.getCouldNotCompute();  // Something strange happened
11828 
11829     // Ensure that the previous value is in the range.  This is a sanity check.
11830     assert(Range.contains(
11831            EvaluateConstantChrecAtConstant(this,
11832            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11833            "Linear scev computation is off in a bad way!");
11834     return SE.getConstant(ExitValue);
11835   }
11836 
11837   if (isQuadratic()) {
11838     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11839       return SE.getConstant(S.getValue());
11840   }
11841 
11842   return SE.getCouldNotCompute();
11843 }
11844 
11845 const SCEVAddRecExpr *
11846 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11847   assert(getNumOperands() > 1 && "AddRec with zero step?");
11848   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11849   // but in this case we cannot guarantee that the value returned will be an
11850   // AddRec because SCEV does not have a fixed point where it stops
11851   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11852   // may happen if we reach arithmetic depth limit while simplifying. So we
11853   // construct the returned value explicitly.
11854   SmallVector<const SCEV *, 3> Ops;
11855   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11856   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11857   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11858     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11859   // We know that the last operand is not a constant zero (otherwise it would
11860   // have been popped out earlier). This guarantees us that if the result has
11861   // the same last operand, then it will also not be popped out, meaning that
11862   // the returned value will be an AddRec.
11863   const SCEV *Last = getOperand(getNumOperands() - 1);
11864   assert(!Last->isZero() && "Recurrency with zero step?");
11865   Ops.push_back(Last);
11866   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11867                                                SCEV::FlagAnyWrap));
11868 }
11869 
11870 // Return true when S contains at least an undef value.
11871 static inline bool containsUndefs(const SCEV *S) {
11872   return SCEVExprContains(S, [](const SCEV *S) {
11873     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11874       return isa<UndefValue>(SU->getValue());
11875     return false;
11876   });
11877 }
11878 
11879 namespace {
11880 
11881 // Collect all steps of SCEV expressions.
11882 struct SCEVCollectStrides {
11883   ScalarEvolution &SE;
11884   SmallVectorImpl<const SCEV *> &Strides;
11885 
11886   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11887       : SE(SE), Strides(S) {}
11888 
11889   bool follow(const SCEV *S) {
11890     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11891       Strides.push_back(AR->getStepRecurrence(SE));
11892     return true;
11893   }
11894 
11895   bool isDone() const { return false; }
11896 };
11897 
11898 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11899 struct SCEVCollectTerms {
11900   SmallVectorImpl<const SCEV *> &Terms;
11901 
11902   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11903 
11904   bool follow(const SCEV *S) {
11905     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11906         isa<SCEVSignExtendExpr>(S)) {
11907       if (!containsUndefs(S))
11908         Terms.push_back(S);
11909 
11910       // Stop recursion: once we collected a term, do not walk its operands.
11911       return false;
11912     }
11913 
11914     // Keep looking.
11915     return true;
11916   }
11917 
11918   bool isDone() const { return false; }
11919 };
11920 
11921 // Check if a SCEV contains an AddRecExpr.
11922 struct SCEVHasAddRec {
11923   bool &ContainsAddRec;
11924 
11925   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11926     ContainsAddRec = false;
11927   }
11928 
11929   bool follow(const SCEV *S) {
11930     if (isa<SCEVAddRecExpr>(S)) {
11931       ContainsAddRec = true;
11932 
11933       // Stop recursion: once we collected a term, do not walk its operands.
11934       return false;
11935     }
11936 
11937     // Keep looking.
11938     return true;
11939   }
11940 
11941   bool isDone() const { return false; }
11942 };
11943 
11944 // Find factors that are multiplied with an expression that (possibly as a
11945 // subexpression) contains an AddRecExpr. In the expression:
11946 //
11947 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11948 //
11949 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11950 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11951 // parameters as they form a product with an induction variable.
11952 //
11953 // This collector expects all array size parameters to be in the same MulExpr.
11954 // It might be necessary to later add support for collecting parameters that are
11955 // spread over different nested MulExpr.
11956 struct SCEVCollectAddRecMultiplies {
11957   SmallVectorImpl<const SCEV *> &Terms;
11958   ScalarEvolution &SE;
11959 
11960   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11961       : Terms(T), SE(SE) {}
11962 
11963   bool follow(const SCEV *S) {
11964     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11965       bool HasAddRec = false;
11966       SmallVector<const SCEV *, 0> Operands;
11967       for (auto Op : Mul->operands()) {
11968         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11969         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11970           Operands.push_back(Op);
11971         } else if (Unknown) {
11972           HasAddRec = true;
11973         } else {
11974           bool ContainsAddRec = false;
11975           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11976           visitAll(Op, ContiansAddRec);
11977           HasAddRec |= ContainsAddRec;
11978         }
11979       }
11980       if (Operands.size() == 0)
11981         return true;
11982 
11983       if (!HasAddRec)
11984         return false;
11985 
11986       Terms.push_back(SE.getMulExpr(Operands));
11987       // Stop recursion: once we collected a term, do not walk its operands.
11988       return false;
11989     }
11990 
11991     // Keep looking.
11992     return true;
11993   }
11994 
11995   bool isDone() const { return false; }
11996 };
11997 
11998 } // end anonymous namespace
11999 
12000 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
12001 /// two places:
12002 ///   1) The strides of AddRec expressions.
12003 ///   2) Unknowns that are multiplied with AddRec expressions.
12004 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
12005     SmallVectorImpl<const SCEV *> &Terms) {
12006   SmallVector<const SCEV *, 4> Strides;
12007   SCEVCollectStrides StrideCollector(*this, Strides);
12008   visitAll(Expr, StrideCollector);
12009 
12010   LLVM_DEBUG({
12011     dbgs() << "Strides:\n";
12012     for (const SCEV *S : Strides)
12013       dbgs() << *S << "\n";
12014   });
12015 
12016   for (const SCEV *S : Strides) {
12017     SCEVCollectTerms TermCollector(Terms);
12018     visitAll(S, TermCollector);
12019   }
12020 
12021   LLVM_DEBUG({
12022     dbgs() << "Terms:\n";
12023     for (const SCEV *T : Terms)
12024       dbgs() << *T << "\n";
12025   });
12026 
12027   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
12028   visitAll(Expr, MulCollector);
12029 }
12030 
12031 static bool findArrayDimensionsRec(ScalarEvolution &SE,
12032                                    SmallVectorImpl<const SCEV *> &Terms,
12033                                    SmallVectorImpl<const SCEV *> &Sizes) {
12034   int Last = Terms.size() - 1;
12035   const SCEV *Step = Terms[Last];
12036 
12037   // End of recursion.
12038   if (Last == 0) {
12039     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
12040       SmallVector<const SCEV *, 2> Qs;
12041       for (const SCEV *Op : M->operands())
12042         if (!isa<SCEVConstant>(Op))
12043           Qs.push_back(Op);
12044 
12045       Step = SE.getMulExpr(Qs);
12046     }
12047 
12048     Sizes.push_back(Step);
12049     return true;
12050   }
12051 
12052   for (const SCEV *&Term : Terms) {
12053     // Normalize the terms before the next call to findArrayDimensionsRec.
12054     const SCEV *Q, *R;
12055     SCEVDivision::divide(SE, Term, Step, &Q, &R);
12056 
12057     // Bail out when GCD does not evenly divide one of the terms.
12058     if (!R->isZero())
12059       return false;
12060 
12061     Term = Q;
12062   }
12063 
12064   // Remove all SCEVConstants.
12065   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
12066 
12067   if (Terms.size() > 0)
12068     if (!findArrayDimensionsRec(SE, Terms, Sizes))
12069       return false;
12070 
12071   Sizes.push_back(Step);
12072   return true;
12073 }
12074 
12075 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
12076 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
12077   for (const SCEV *T : Terms)
12078     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
12079       return true;
12080 
12081   return false;
12082 }
12083 
12084 // Return the number of product terms in S.
12085 static inline int numberOfTerms(const SCEV *S) {
12086   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
12087     return Expr->getNumOperands();
12088   return 1;
12089 }
12090 
12091 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
12092   if (isa<SCEVConstant>(T))
12093     return nullptr;
12094 
12095   if (isa<SCEVUnknown>(T))
12096     return T;
12097 
12098   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
12099     SmallVector<const SCEV *, 2> Factors;
12100     for (const SCEV *Op : M->operands())
12101       if (!isa<SCEVConstant>(Op))
12102         Factors.push_back(Op);
12103 
12104     return SE.getMulExpr(Factors);
12105   }
12106 
12107   return T;
12108 }
12109 
12110 /// Return the size of an element read or written by Inst.
12111 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12112   Type *Ty;
12113   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12114     Ty = Store->getValueOperand()->getType();
12115   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12116     Ty = Load->getType();
12117   else
12118     return nullptr;
12119 
12120   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12121   return getSizeOfExpr(ETy, Ty);
12122 }
12123 
12124 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
12125                                           SmallVectorImpl<const SCEV *> &Sizes,
12126                                           const SCEV *ElementSize) {
12127   if (Terms.size() < 1 || !ElementSize)
12128     return;
12129 
12130   // Early return when Terms do not contain parameters: we do not delinearize
12131   // non parametric SCEVs.
12132   if (!containsParameters(Terms))
12133     return;
12134 
12135   LLVM_DEBUG({
12136     dbgs() << "Terms:\n";
12137     for (const SCEV *T : Terms)
12138       dbgs() << *T << "\n";
12139   });
12140 
12141   // Remove duplicates.
12142   array_pod_sort(Terms.begin(), Terms.end());
12143   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
12144 
12145   // Put larger terms first.
12146   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
12147     return numberOfTerms(LHS) > numberOfTerms(RHS);
12148   });
12149 
12150   // Try to divide all terms by the element size. If term is not divisible by
12151   // element size, proceed with the original term.
12152   for (const SCEV *&Term : Terms) {
12153     const SCEV *Q, *R;
12154     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
12155     if (!Q->isZero())
12156       Term = Q;
12157   }
12158 
12159   SmallVector<const SCEV *, 4> NewTerms;
12160 
12161   // Remove constant factors.
12162   for (const SCEV *T : Terms)
12163     if (const SCEV *NewT = removeConstantFactors(*this, T))
12164       NewTerms.push_back(NewT);
12165 
12166   LLVM_DEBUG({
12167     dbgs() << "Terms after sorting:\n";
12168     for (const SCEV *T : NewTerms)
12169       dbgs() << *T << "\n";
12170   });
12171 
12172   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
12173     Sizes.clear();
12174     return;
12175   }
12176 
12177   // The last element to be pushed into Sizes is the size of an element.
12178   Sizes.push_back(ElementSize);
12179 
12180   LLVM_DEBUG({
12181     dbgs() << "Sizes:\n";
12182     for (const SCEV *S : Sizes)
12183       dbgs() << *S << "\n";
12184   });
12185 }
12186 
12187 void ScalarEvolution::computeAccessFunctions(
12188     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
12189     SmallVectorImpl<const SCEV *> &Sizes) {
12190   // Early exit in case this SCEV is not an affine multivariate function.
12191   if (Sizes.empty())
12192     return;
12193 
12194   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
12195     if (!AR->isAffine())
12196       return;
12197 
12198   const SCEV *Res = Expr;
12199   int Last = Sizes.size() - 1;
12200   for (int i = Last; i >= 0; i--) {
12201     const SCEV *Q, *R;
12202     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
12203 
12204     LLVM_DEBUG({
12205       dbgs() << "Res: " << *Res << "\n";
12206       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
12207       dbgs() << "Res divided by Sizes[i]:\n";
12208       dbgs() << "Quotient: " << *Q << "\n";
12209       dbgs() << "Remainder: " << *R << "\n";
12210     });
12211 
12212     Res = Q;
12213 
12214     // Do not record the last subscript corresponding to the size of elements in
12215     // the array.
12216     if (i == Last) {
12217 
12218       // Bail out if the remainder is too complex.
12219       if (isa<SCEVAddRecExpr>(R)) {
12220         Subscripts.clear();
12221         Sizes.clear();
12222         return;
12223       }
12224 
12225       continue;
12226     }
12227 
12228     // Record the access function for the current subscript.
12229     Subscripts.push_back(R);
12230   }
12231 
12232   // Also push in last position the remainder of the last division: it will be
12233   // the access function of the innermost dimension.
12234   Subscripts.push_back(Res);
12235 
12236   std::reverse(Subscripts.begin(), Subscripts.end());
12237 
12238   LLVM_DEBUG({
12239     dbgs() << "Subscripts:\n";
12240     for (const SCEV *S : Subscripts)
12241       dbgs() << *S << "\n";
12242   });
12243 }
12244 
12245 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
12246 /// sizes of an array access. Returns the remainder of the delinearization that
12247 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
12248 /// the multiples of SCEV coefficients: that is a pattern matching of sub
12249 /// expressions in the stride and base of a SCEV corresponding to the
12250 /// computation of a GCD (greatest common divisor) of base and stride.  When
12251 /// SCEV->delinearize fails, it returns the SCEV unchanged.
12252 ///
12253 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
12254 ///
12255 ///  void foo(long n, long m, long o, double A[n][m][o]) {
12256 ///
12257 ///    for (long i = 0; i < n; i++)
12258 ///      for (long j = 0; j < m; j++)
12259 ///        for (long k = 0; k < o; k++)
12260 ///          A[i][j][k] = 1.0;
12261 ///  }
12262 ///
12263 /// the delinearization input is the following AddRec SCEV:
12264 ///
12265 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
12266 ///
12267 /// From this SCEV, we are able to say that the base offset of the access is %A
12268 /// because it appears as an offset that does not divide any of the strides in
12269 /// the loops:
12270 ///
12271 ///  CHECK: Base offset: %A
12272 ///
12273 /// and then SCEV->delinearize determines the size of some of the dimensions of
12274 /// the array as these are the multiples by which the strides are happening:
12275 ///
12276 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
12277 ///
12278 /// Note that the outermost dimension remains of UnknownSize because there are
12279 /// no strides that would help identifying the size of the last dimension: when
12280 /// the array has been statically allocated, one could compute the size of that
12281 /// dimension by dividing the overall size of the array by the size of the known
12282 /// dimensions: %m * %o * 8.
12283 ///
12284 /// Finally delinearize provides the access functions for the array reference
12285 /// that does correspond to A[i][j][k] of the above C testcase:
12286 ///
12287 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
12288 ///
12289 /// The testcases are checking the output of a function pass:
12290 /// DelinearizationPass that walks through all loads and stores of a function
12291 /// asking for the SCEV of the memory access with respect to all enclosing
12292 /// loops, calling SCEV->delinearize on that and printing the results.
12293 void ScalarEvolution::delinearize(const SCEV *Expr,
12294                                  SmallVectorImpl<const SCEV *> &Subscripts,
12295                                  SmallVectorImpl<const SCEV *> &Sizes,
12296                                  const SCEV *ElementSize) {
12297   // First step: collect parametric terms.
12298   SmallVector<const SCEV *, 4> Terms;
12299   collectParametricTerms(Expr, Terms);
12300 
12301   if (Terms.empty())
12302     return;
12303 
12304   // Second step: find subscript sizes.
12305   findArrayDimensions(Terms, Sizes, ElementSize);
12306 
12307   if (Sizes.empty())
12308     return;
12309 
12310   // Third step: compute the access functions for each subscript.
12311   computeAccessFunctions(Expr, Subscripts, Sizes);
12312 
12313   if (Subscripts.empty())
12314     return;
12315 
12316   LLVM_DEBUG({
12317     dbgs() << "succeeded to delinearize " << *Expr << "\n";
12318     dbgs() << "ArrayDecl[UnknownSize]";
12319     for (const SCEV *S : Sizes)
12320       dbgs() << "[" << *S << "]";
12321 
12322     dbgs() << "\nArrayRef";
12323     for (const SCEV *S : Subscripts)
12324       dbgs() << "[" << *S << "]";
12325     dbgs() << "\n";
12326   });
12327 }
12328 
12329 bool ScalarEvolution::getIndexExpressionsFromGEP(
12330     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
12331     SmallVectorImpl<int> &Sizes) {
12332   assert(Subscripts.empty() && Sizes.empty() &&
12333          "Expected output lists to be empty on entry to this function.");
12334   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
12335   Type *Ty = GEP->getPointerOperandType();
12336   bool DroppedFirstDim = false;
12337   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
12338     const SCEV *Expr = getSCEV(GEP->getOperand(i));
12339     if (i == 1) {
12340       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
12341         Ty = PtrTy->getElementType();
12342       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
12343         Ty = ArrayTy->getElementType();
12344       } else {
12345         Subscripts.clear();
12346         Sizes.clear();
12347         return false;
12348       }
12349       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
12350         if (Const->getValue()->isZero()) {
12351           DroppedFirstDim = true;
12352           continue;
12353         }
12354       Subscripts.push_back(Expr);
12355       continue;
12356     }
12357 
12358     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
12359     if (!ArrayTy) {
12360       Subscripts.clear();
12361       Sizes.clear();
12362       return false;
12363     }
12364 
12365     Subscripts.push_back(Expr);
12366     if (!(DroppedFirstDim && i == 2))
12367       Sizes.push_back(ArrayTy->getNumElements());
12368 
12369     Ty = ArrayTy->getElementType();
12370   }
12371   return !Subscripts.empty();
12372 }
12373 
12374 //===----------------------------------------------------------------------===//
12375 //                   SCEVCallbackVH Class Implementation
12376 //===----------------------------------------------------------------------===//
12377 
12378 void ScalarEvolution::SCEVCallbackVH::deleted() {
12379   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12380   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12381     SE->ConstantEvolutionLoopExitValue.erase(PN);
12382   SE->eraseValueFromMap(getValPtr());
12383   // this now dangles!
12384 }
12385 
12386 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12387   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12388 
12389   // Forget all the expressions associated with users of the old value,
12390   // so that future queries will recompute the expressions using the new
12391   // value.
12392   Value *Old = getValPtr();
12393   SmallVector<User *, 16> Worklist(Old->users());
12394   SmallPtrSet<User *, 8> Visited;
12395   while (!Worklist.empty()) {
12396     User *U = Worklist.pop_back_val();
12397     // Deleting the Old value will cause this to dangle. Postpone
12398     // that until everything else is done.
12399     if (U == Old)
12400       continue;
12401     if (!Visited.insert(U).second)
12402       continue;
12403     if (PHINode *PN = dyn_cast<PHINode>(U))
12404       SE->ConstantEvolutionLoopExitValue.erase(PN);
12405     SE->eraseValueFromMap(U);
12406     llvm::append_range(Worklist, U->users());
12407   }
12408   // Delete the Old value.
12409   if (PHINode *PN = dyn_cast<PHINode>(Old))
12410     SE->ConstantEvolutionLoopExitValue.erase(PN);
12411   SE->eraseValueFromMap(Old);
12412   // this now dangles!
12413 }
12414 
12415 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12416   : CallbackVH(V), SE(se) {}
12417 
12418 //===----------------------------------------------------------------------===//
12419 //                   ScalarEvolution Class Implementation
12420 //===----------------------------------------------------------------------===//
12421 
12422 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12423                                  AssumptionCache &AC, DominatorTree &DT,
12424                                  LoopInfo &LI)
12425     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12426       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12427       LoopDispositions(64), BlockDispositions(64) {
12428   // To use guards for proving predicates, we need to scan every instruction in
12429   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12430   // time if the IR does not actually contain any calls to
12431   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12432   //
12433   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12434   // to _add_ guards to the module when there weren't any before, and wants
12435   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12436   // efficient in lieu of being smart in that rather obscure case.
12437 
12438   auto *GuardDecl = F.getParent()->getFunction(
12439       Intrinsic::getName(Intrinsic::experimental_guard));
12440   HasGuards = GuardDecl && !GuardDecl->use_empty();
12441 }
12442 
12443 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12444     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12445       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12446       ValueExprMap(std::move(Arg.ValueExprMap)),
12447       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12448       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12449       PendingMerges(std::move(Arg.PendingMerges)),
12450       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12451       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12452       PredicatedBackedgeTakenCounts(
12453           std::move(Arg.PredicatedBackedgeTakenCounts)),
12454       ConstantEvolutionLoopExitValue(
12455           std::move(Arg.ConstantEvolutionLoopExitValue)),
12456       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12457       LoopDispositions(std::move(Arg.LoopDispositions)),
12458       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12459       BlockDispositions(std::move(Arg.BlockDispositions)),
12460       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12461       SignedRanges(std::move(Arg.SignedRanges)),
12462       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12463       UniquePreds(std::move(Arg.UniquePreds)),
12464       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12465       LoopUsers(std::move(Arg.LoopUsers)),
12466       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12467       FirstUnknown(Arg.FirstUnknown) {
12468   Arg.FirstUnknown = nullptr;
12469 }
12470 
12471 ScalarEvolution::~ScalarEvolution() {
12472   // Iterate through all the SCEVUnknown instances and call their
12473   // destructors, so that they release their references to their values.
12474   for (SCEVUnknown *U = FirstUnknown; U;) {
12475     SCEVUnknown *Tmp = U;
12476     U = U->Next;
12477     Tmp->~SCEVUnknown();
12478   }
12479   FirstUnknown = nullptr;
12480 
12481   ExprValueMap.clear();
12482   ValueExprMap.clear();
12483   HasRecMap.clear();
12484   BackedgeTakenCounts.clear();
12485   PredicatedBackedgeTakenCounts.clear();
12486 
12487   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12488   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12489   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12490   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12491   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12492 }
12493 
12494 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12495   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12496 }
12497 
12498 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12499                           const Loop *L) {
12500   // Print all inner loops first
12501   for (Loop *I : *L)
12502     PrintLoopInfo(OS, SE, I);
12503 
12504   OS << "Loop ";
12505   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12506   OS << ": ";
12507 
12508   SmallVector<BasicBlock *, 8> ExitingBlocks;
12509   L->getExitingBlocks(ExitingBlocks);
12510   if (ExitingBlocks.size() != 1)
12511     OS << "<multiple exits> ";
12512 
12513   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12514     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12515   else
12516     OS << "Unpredictable backedge-taken count.\n";
12517 
12518   if (ExitingBlocks.size() > 1)
12519     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12520       OS << "  exit count for " << ExitingBlock->getName() << ": "
12521          << *SE->getExitCount(L, ExitingBlock) << "\n";
12522     }
12523 
12524   OS << "Loop ";
12525   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12526   OS << ": ";
12527 
12528   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12529     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12530     if (SE->isBackedgeTakenCountMaxOrZero(L))
12531       OS << ", actual taken count either this or zero.";
12532   } else {
12533     OS << "Unpredictable max backedge-taken count. ";
12534   }
12535 
12536   OS << "\n"
12537         "Loop ";
12538   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12539   OS << ": ";
12540 
12541   SCEVUnionPredicate Pred;
12542   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12543   if (!isa<SCEVCouldNotCompute>(PBT)) {
12544     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12545     OS << " Predicates:\n";
12546     Pred.print(OS, 4);
12547   } else {
12548     OS << "Unpredictable predicated backedge-taken count. ";
12549   }
12550   OS << "\n";
12551 
12552   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12553     OS << "Loop ";
12554     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12555     OS << ": ";
12556     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12557   }
12558 }
12559 
12560 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12561   switch (LD) {
12562   case ScalarEvolution::LoopVariant:
12563     return "Variant";
12564   case ScalarEvolution::LoopInvariant:
12565     return "Invariant";
12566   case ScalarEvolution::LoopComputable:
12567     return "Computable";
12568   }
12569   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12570 }
12571 
12572 void ScalarEvolution::print(raw_ostream &OS) const {
12573   // ScalarEvolution's implementation of the print method is to print
12574   // out SCEV values of all instructions that are interesting. Doing
12575   // this potentially causes it to create new SCEV objects though,
12576   // which technically conflicts with the const qualifier. This isn't
12577   // observable from outside the class though, so casting away the
12578   // const isn't dangerous.
12579   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12580 
12581   if (ClassifyExpressions) {
12582     OS << "Classifying expressions for: ";
12583     F.printAsOperand(OS, /*PrintType=*/false);
12584     OS << "\n";
12585     for (Instruction &I : instructions(F))
12586       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12587         OS << I << '\n';
12588         OS << "  -->  ";
12589         const SCEV *SV = SE.getSCEV(&I);
12590         SV->print(OS);
12591         if (!isa<SCEVCouldNotCompute>(SV)) {
12592           OS << " U: ";
12593           SE.getUnsignedRange(SV).print(OS);
12594           OS << " S: ";
12595           SE.getSignedRange(SV).print(OS);
12596         }
12597 
12598         const Loop *L = LI.getLoopFor(I.getParent());
12599 
12600         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12601         if (AtUse != SV) {
12602           OS << "  -->  ";
12603           AtUse->print(OS);
12604           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12605             OS << " U: ";
12606             SE.getUnsignedRange(AtUse).print(OS);
12607             OS << " S: ";
12608             SE.getSignedRange(AtUse).print(OS);
12609           }
12610         }
12611 
12612         if (L) {
12613           OS << "\t\t" "Exits: ";
12614           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12615           if (!SE.isLoopInvariant(ExitValue, L)) {
12616             OS << "<<Unknown>>";
12617           } else {
12618             OS << *ExitValue;
12619           }
12620 
12621           bool First = true;
12622           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12623             if (First) {
12624               OS << "\t\t" "LoopDispositions: { ";
12625               First = false;
12626             } else {
12627               OS << ", ";
12628             }
12629 
12630             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12631             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12632           }
12633 
12634           for (auto *InnerL : depth_first(L)) {
12635             if (InnerL == L)
12636               continue;
12637             if (First) {
12638               OS << "\t\t" "LoopDispositions: { ";
12639               First = false;
12640             } else {
12641               OS << ", ";
12642             }
12643 
12644             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12645             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12646           }
12647 
12648           OS << " }";
12649         }
12650 
12651         OS << "\n";
12652       }
12653   }
12654 
12655   OS << "Determining loop execution counts for: ";
12656   F.printAsOperand(OS, /*PrintType=*/false);
12657   OS << "\n";
12658   for (Loop *I : LI)
12659     PrintLoopInfo(OS, &SE, I);
12660 }
12661 
12662 ScalarEvolution::LoopDisposition
12663 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12664   auto &Values = LoopDispositions[S];
12665   for (auto &V : Values) {
12666     if (V.getPointer() == L)
12667       return V.getInt();
12668   }
12669   Values.emplace_back(L, LoopVariant);
12670   LoopDisposition D = computeLoopDisposition(S, L);
12671   auto &Values2 = LoopDispositions[S];
12672   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12673     if (V.getPointer() == L) {
12674       V.setInt(D);
12675       break;
12676     }
12677   }
12678   return D;
12679 }
12680 
12681 ScalarEvolution::LoopDisposition
12682 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12683   switch (S->getSCEVType()) {
12684   case scConstant:
12685     return LoopInvariant;
12686   case scPtrToInt:
12687   case scTruncate:
12688   case scZeroExtend:
12689   case scSignExtend:
12690     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12691   case scAddRecExpr: {
12692     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12693 
12694     // If L is the addrec's loop, it's computable.
12695     if (AR->getLoop() == L)
12696       return LoopComputable;
12697 
12698     // Add recurrences are never invariant in the function-body (null loop).
12699     if (!L)
12700       return LoopVariant;
12701 
12702     // Everything that is not defined at loop entry is variant.
12703     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12704       return LoopVariant;
12705     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12706            " dominate the contained loop's header?");
12707 
12708     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12709     if (AR->getLoop()->contains(L))
12710       return LoopInvariant;
12711 
12712     // This recurrence is variant w.r.t. L if any of its operands
12713     // are variant.
12714     for (auto *Op : AR->operands())
12715       if (!isLoopInvariant(Op, L))
12716         return LoopVariant;
12717 
12718     // Otherwise it's loop-invariant.
12719     return LoopInvariant;
12720   }
12721   case scAddExpr:
12722   case scMulExpr:
12723   case scUMaxExpr:
12724   case scSMaxExpr:
12725   case scUMinExpr:
12726   case scSMinExpr: {
12727     bool HasVarying = false;
12728     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12729       LoopDisposition D = getLoopDisposition(Op, L);
12730       if (D == LoopVariant)
12731         return LoopVariant;
12732       if (D == LoopComputable)
12733         HasVarying = true;
12734     }
12735     return HasVarying ? LoopComputable : LoopInvariant;
12736   }
12737   case scUDivExpr: {
12738     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12739     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12740     if (LD == LoopVariant)
12741       return LoopVariant;
12742     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12743     if (RD == LoopVariant)
12744       return LoopVariant;
12745     return (LD == LoopInvariant && RD == LoopInvariant) ?
12746            LoopInvariant : LoopComputable;
12747   }
12748   case scUnknown:
12749     // All non-instruction values are loop invariant.  All instructions are loop
12750     // invariant if they are not contained in the specified loop.
12751     // Instructions are never considered invariant in the function body
12752     // (null loop) because they are defined within the "loop".
12753     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12754       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12755     return LoopInvariant;
12756   case scCouldNotCompute:
12757     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12758   }
12759   llvm_unreachable("Unknown SCEV kind!");
12760 }
12761 
12762 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12763   return getLoopDisposition(S, L) == LoopInvariant;
12764 }
12765 
12766 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12767   return getLoopDisposition(S, L) == LoopComputable;
12768 }
12769 
12770 ScalarEvolution::BlockDisposition
12771 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12772   auto &Values = BlockDispositions[S];
12773   for (auto &V : Values) {
12774     if (V.getPointer() == BB)
12775       return V.getInt();
12776   }
12777   Values.emplace_back(BB, DoesNotDominateBlock);
12778   BlockDisposition D = computeBlockDisposition(S, BB);
12779   auto &Values2 = BlockDispositions[S];
12780   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12781     if (V.getPointer() == BB) {
12782       V.setInt(D);
12783       break;
12784     }
12785   }
12786   return D;
12787 }
12788 
12789 ScalarEvolution::BlockDisposition
12790 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12791   switch (S->getSCEVType()) {
12792   case scConstant:
12793     return ProperlyDominatesBlock;
12794   case scPtrToInt:
12795   case scTruncate:
12796   case scZeroExtend:
12797   case scSignExtend:
12798     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12799   case scAddRecExpr: {
12800     // This uses a "dominates" query instead of "properly dominates" query
12801     // to test for proper dominance too, because the instruction which
12802     // produces the addrec's value is a PHI, and a PHI effectively properly
12803     // dominates its entire containing block.
12804     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12805     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12806       return DoesNotDominateBlock;
12807 
12808     // Fall through into SCEVNAryExpr handling.
12809     LLVM_FALLTHROUGH;
12810   }
12811   case scAddExpr:
12812   case scMulExpr:
12813   case scUMaxExpr:
12814   case scSMaxExpr:
12815   case scUMinExpr:
12816   case scSMinExpr: {
12817     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12818     bool Proper = true;
12819     for (const SCEV *NAryOp : NAry->operands()) {
12820       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12821       if (D == DoesNotDominateBlock)
12822         return DoesNotDominateBlock;
12823       if (D == DominatesBlock)
12824         Proper = false;
12825     }
12826     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12827   }
12828   case scUDivExpr: {
12829     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12830     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12831     BlockDisposition LD = getBlockDisposition(LHS, BB);
12832     if (LD == DoesNotDominateBlock)
12833       return DoesNotDominateBlock;
12834     BlockDisposition RD = getBlockDisposition(RHS, BB);
12835     if (RD == DoesNotDominateBlock)
12836       return DoesNotDominateBlock;
12837     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12838       ProperlyDominatesBlock : DominatesBlock;
12839   }
12840   case scUnknown:
12841     if (Instruction *I =
12842           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12843       if (I->getParent() == BB)
12844         return DominatesBlock;
12845       if (DT.properlyDominates(I->getParent(), BB))
12846         return ProperlyDominatesBlock;
12847       return DoesNotDominateBlock;
12848     }
12849     return ProperlyDominatesBlock;
12850   case scCouldNotCompute:
12851     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12852   }
12853   llvm_unreachable("Unknown SCEV kind!");
12854 }
12855 
12856 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12857   return getBlockDisposition(S, BB) >= DominatesBlock;
12858 }
12859 
12860 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12861   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12862 }
12863 
12864 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12865   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12866 }
12867 
12868 void
12869 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12870   ValuesAtScopes.erase(S);
12871   LoopDispositions.erase(S);
12872   BlockDispositions.erase(S);
12873   UnsignedRanges.erase(S);
12874   SignedRanges.erase(S);
12875   ExprValueMap.erase(S);
12876   HasRecMap.erase(S);
12877   MinTrailingZerosCache.erase(S);
12878 
12879   for (auto I = PredicatedSCEVRewrites.begin();
12880        I != PredicatedSCEVRewrites.end();) {
12881     std::pair<const SCEV *, const Loop *> Entry = I->first;
12882     if (Entry.first == S)
12883       PredicatedSCEVRewrites.erase(I++);
12884     else
12885       ++I;
12886   }
12887 
12888   auto RemoveSCEVFromBackedgeMap =
12889       [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12890         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12891           BackedgeTakenInfo &BEInfo = I->second;
12892           if (BEInfo.hasOperand(S))
12893             Map.erase(I++);
12894           else
12895             ++I;
12896         }
12897       };
12898 
12899   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12900   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12901 }
12902 
12903 void
12904 ScalarEvolution::getUsedLoops(const SCEV *S,
12905                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12906   struct FindUsedLoops {
12907     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12908         : LoopsUsed(LoopsUsed) {}
12909     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12910     bool follow(const SCEV *S) {
12911       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12912         LoopsUsed.insert(AR->getLoop());
12913       return true;
12914     }
12915 
12916     bool isDone() const { return false; }
12917   };
12918 
12919   FindUsedLoops F(LoopsUsed);
12920   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12921 }
12922 
12923 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12924   SmallPtrSet<const Loop *, 8> LoopsUsed;
12925   getUsedLoops(S, LoopsUsed);
12926   for (auto *L : LoopsUsed)
12927     LoopUsers[L].push_back(S);
12928 }
12929 
12930 void ScalarEvolution::verify() const {
12931   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12932   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12933 
12934   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12935 
12936   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12937   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12938     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12939 
12940     const SCEV *visitConstant(const SCEVConstant *Constant) {
12941       return SE.getConstant(Constant->getAPInt());
12942     }
12943 
12944     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12945       return SE.getUnknown(Expr->getValue());
12946     }
12947 
12948     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12949       return SE.getCouldNotCompute();
12950     }
12951   };
12952 
12953   SCEVMapper SCM(SE2);
12954 
12955   while (!LoopStack.empty()) {
12956     auto *L = LoopStack.pop_back_val();
12957     llvm::append_range(LoopStack, *L);
12958 
12959     auto *CurBECount = SCM.visit(
12960         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12961     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12962 
12963     if (CurBECount == SE2.getCouldNotCompute() ||
12964         NewBECount == SE2.getCouldNotCompute()) {
12965       // NB! This situation is legal, but is very suspicious -- whatever pass
12966       // change the loop to make a trip count go from could not compute to
12967       // computable or vice-versa *should have* invalidated SCEV.  However, we
12968       // choose not to assert here (for now) since we don't want false
12969       // positives.
12970       continue;
12971     }
12972 
12973     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12974       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12975       // not propagate undef aggressively).  This means we can (and do) fail
12976       // verification in cases where a transform makes the trip count of a loop
12977       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12978       // both cases the loop iterates "undef" times, but SCEV thinks we
12979       // increased the trip count of the loop by 1 incorrectly.
12980       continue;
12981     }
12982 
12983     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12984         SE.getTypeSizeInBits(NewBECount->getType()))
12985       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12986     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12987              SE.getTypeSizeInBits(NewBECount->getType()))
12988       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12989 
12990     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12991 
12992     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12993     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12994       dbgs() << "Trip Count for " << *L << " Changed!\n";
12995       dbgs() << "Old: " << *CurBECount << "\n";
12996       dbgs() << "New: " << *NewBECount << "\n";
12997       dbgs() << "Delta: " << *Delta << "\n";
12998       std::abort();
12999     }
13000   }
13001 
13002   // Collect all valid loops currently in LoopInfo.
13003   SmallPtrSet<Loop *, 32> ValidLoops;
13004   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13005   while (!Worklist.empty()) {
13006     Loop *L = Worklist.pop_back_val();
13007     if (ValidLoops.contains(L))
13008       continue;
13009     ValidLoops.insert(L);
13010     Worklist.append(L->begin(), L->end());
13011   }
13012   // Check for SCEV expressions referencing invalid/deleted loops.
13013   for (auto &KV : ValueExprMap) {
13014     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
13015     if (!AR)
13016       continue;
13017     assert(ValidLoops.contains(AR->getLoop()) &&
13018            "AddRec references invalid loop");
13019   }
13020 }
13021 
13022 bool ScalarEvolution::invalidate(
13023     Function &F, const PreservedAnalyses &PA,
13024     FunctionAnalysisManager::Invalidator &Inv) {
13025   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13026   // of its dependencies is invalidated.
13027   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13028   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13029          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13030          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13031          Inv.invalidate<LoopAnalysis>(F, PA);
13032 }
13033 
13034 AnalysisKey ScalarEvolutionAnalysis::Key;
13035 
13036 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13037                                              FunctionAnalysisManager &AM) {
13038   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13039                          AM.getResult<AssumptionAnalysis>(F),
13040                          AM.getResult<DominatorTreeAnalysis>(F),
13041                          AM.getResult<LoopAnalysis>(F));
13042 }
13043 
13044 PreservedAnalyses
13045 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13046   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13047   return PreservedAnalyses::all();
13048 }
13049 
13050 PreservedAnalyses
13051 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13052   // For compatibility with opt's -analyze feature under legacy pass manager
13053   // which was not ported to NPM. This keeps tests using
13054   // update_analyze_test_checks.py working.
13055   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13056      << F.getName() << "':\n";
13057   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13058   return PreservedAnalyses::all();
13059 }
13060 
13061 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13062                       "Scalar Evolution Analysis", false, true)
13063 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13064 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13065 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13066 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13067 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13068                     "Scalar Evolution Analysis", false, true)
13069 
13070 char ScalarEvolutionWrapperPass::ID = 0;
13071 
13072 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13073   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13074 }
13075 
13076 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13077   SE.reset(new ScalarEvolution(
13078       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13079       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13080       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13081       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13082   return false;
13083 }
13084 
13085 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13086 
13087 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13088   SE->print(OS);
13089 }
13090 
13091 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13092   if (!VerifySCEV)
13093     return;
13094 
13095   SE->verify();
13096 }
13097 
13098 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13099   AU.setPreservesAll();
13100   AU.addRequiredTransitive<AssumptionCacheTracker>();
13101   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13102   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13103   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13104 }
13105 
13106 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13107                                                         const SCEV *RHS) {
13108   FoldingSetNodeID ID;
13109   assert(LHS->getType() == RHS->getType() &&
13110          "Type mismatch between LHS and RHS");
13111   // Unique this node based on the arguments
13112   ID.AddInteger(SCEVPredicate::P_Equal);
13113   ID.AddPointer(LHS);
13114   ID.AddPointer(RHS);
13115   void *IP = nullptr;
13116   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13117     return S;
13118   SCEVEqualPredicate *Eq = new (SCEVAllocator)
13119       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
13120   UniquePreds.InsertNode(Eq, IP);
13121   return Eq;
13122 }
13123 
13124 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13125     const SCEVAddRecExpr *AR,
13126     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13127   FoldingSetNodeID ID;
13128   // Unique this node based on the arguments
13129   ID.AddInteger(SCEVPredicate::P_Wrap);
13130   ID.AddPointer(AR);
13131   ID.AddInteger(AddedFlags);
13132   void *IP = nullptr;
13133   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13134     return S;
13135   auto *OF = new (SCEVAllocator)
13136       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13137   UniquePreds.InsertNode(OF, IP);
13138   return OF;
13139 }
13140 
13141 namespace {
13142 
13143 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13144 public:
13145 
13146   /// Rewrites \p S in the context of a loop L and the SCEV predication
13147   /// infrastructure.
13148   ///
13149   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13150   /// equivalences present in \p Pred.
13151   ///
13152   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13153   /// \p NewPreds such that the result will be an AddRecExpr.
13154   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13155                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13156                              SCEVUnionPredicate *Pred) {
13157     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13158     return Rewriter.visit(S);
13159   }
13160 
13161   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13162     if (Pred) {
13163       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
13164       for (auto *Pred : ExprPreds)
13165         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
13166           if (IPred->getLHS() == Expr)
13167             return IPred->getRHS();
13168     }
13169     return convertToAddRecWithPreds(Expr);
13170   }
13171 
13172   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13173     const SCEV *Operand = visit(Expr->getOperand());
13174     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13175     if (AR && AR->getLoop() == L && AR->isAffine()) {
13176       // This couldn't be folded because the operand didn't have the nuw
13177       // flag. Add the nusw flag as an assumption that we could make.
13178       const SCEV *Step = AR->getStepRecurrence(SE);
13179       Type *Ty = Expr->getType();
13180       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13181         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13182                                 SE.getSignExtendExpr(Step, Ty), L,
13183                                 AR->getNoWrapFlags());
13184     }
13185     return SE.getZeroExtendExpr(Operand, Expr->getType());
13186   }
13187 
13188   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13189     const SCEV *Operand = visit(Expr->getOperand());
13190     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13191     if (AR && AR->getLoop() == L && AR->isAffine()) {
13192       // This couldn't be folded because the operand didn't have the nsw
13193       // flag. Add the nssw flag as an assumption that we could make.
13194       const SCEV *Step = AR->getStepRecurrence(SE);
13195       Type *Ty = Expr->getType();
13196       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13197         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13198                                 SE.getSignExtendExpr(Step, Ty), L,
13199                                 AR->getNoWrapFlags());
13200     }
13201     return SE.getSignExtendExpr(Operand, Expr->getType());
13202   }
13203 
13204 private:
13205   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13206                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13207                         SCEVUnionPredicate *Pred)
13208       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13209 
13210   bool addOverflowAssumption(const SCEVPredicate *P) {
13211     if (!NewPreds) {
13212       // Check if we've already made this assumption.
13213       return Pred && Pred->implies(P);
13214     }
13215     NewPreds->insert(P);
13216     return true;
13217   }
13218 
13219   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13220                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13221     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13222     return addOverflowAssumption(A);
13223   }
13224 
13225   // If \p Expr represents a PHINode, we try to see if it can be represented
13226   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13227   // to add this predicate as a runtime overflow check, we return the AddRec.
13228   // If \p Expr does not meet these conditions (is not a PHI node, or we
13229   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13230   // return \p Expr.
13231   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13232     if (!isa<PHINode>(Expr->getValue()))
13233       return Expr;
13234     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13235     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13236     if (!PredicatedRewrite)
13237       return Expr;
13238     for (auto *P : PredicatedRewrite->second){
13239       // Wrap predicates from outer loops are not supported.
13240       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13241         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
13242         if (L != AR->getLoop())
13243           return Expr;
13244       }
13245       if (!addOverflowAssumption(P))
13246         return Expr;
13247     }
13248     return PredicatedRewrite->first;
13249   }
13250 
13251   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13252   SCEVUnionPredicate *Pred;
13253   const Loop *L;
13254 };
13255 
13256 } // end anonymous namespace
13257 
13258 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13259                                                    SCEVUnionPredicate &Preds) {
13260   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13261 }
13262 
13263 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13264     const SCEV *S, const Loop *L,
13265     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13266   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13267   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13268   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13269 
13270   if (!AddRec)
13271     return nullptr;
13272 
13273   // Since the transformation was successful, we can now transfer the SCEV
13274   // predicates.
13275   for (auto *P : TransformPreds)
13276     Preds.insert(P);
13277 
13278   return AddRec;
13279 }
13280 
13281 /// SCEV predicates
13282 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13283                              SCEVPredicateKind Kind)
13284     : FastID(ID), Kind(Kind) {}
13285 
13286 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13287                                        const SCEV *LHS, const SCEV *RHS)
13288     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13289   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13290   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13291 }
13292 
13293 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13294   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13295 
13296   if (!Op)
13297     return false;
13298 
13299   return Op->LHS == LHS && Op->RHS == RHS;
13300 }
13301 
13302 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13303 
13304 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13305 
13306 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13307   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13308 }
13309 
13310 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13311                                      const SCEVAddRecExpr *AR,
13312                                      IncrementWrapFlags Flags)
13313     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13314 
13315 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13316 
13317 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13318   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13319 
13320   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13321 }
13322 
13323 bool SCEVWrapPredicate::isAlwaysTrue() const {
13324   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13325   IncrementWrapFlags IFlags = Flags;
13326 
13327   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13328     IFlags = clearFlags(IFlags, IncrementNSSW);
13329 
13330   return IFlags == IncrementAnyWrap;
13331 }
13332 
13333 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13334   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13335   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13336     OS << "<nusw>";
13337   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13338     OS << "<nssw>";
13339   OS << "\n";
13340 }
13341 
13342 SCEVWrapPredicate::IncrementWrapFlags
13343 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13344                                    ScalarEvolution &SE) {
13345   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13346   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13347 
13348   // We can safely transfer the NSW flag as NSSW.
13349   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13350     ImpliedFlags = IncrementNSSW;
13351 
13352   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13353     // If the increment is positive, the SCEV NUW flag will also imply the
13354     // WrapPredicate NUSW flag.
13355     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13356       if (Step->getValue()->getValue().isNonNegative())
13357         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13358   }
13359 
13360   return ImpliedFlags;
13361 }
13362 
13363 /// Union predicates don't get cached so create a dummy set ID for it.
13364 SCEVUnionPredicate::SCEVUnionPredicate()
13365     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13366 
13367 bool SCEVUnionPredicate::isAlwaysTrue() const {
13368   return all_of(Preds,
13369                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13370 }
13371 
13372 ArrayRef<const SCEVPredicate *>
13373 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13374   auto I = SCEVToPreds.find(Expr);
13375   if (I == SCEVToPreds.end())
13376     return ArrayRef<const SCEVPredicate *>();
13377   return I->second;
13378 }
13379 
13380 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13381   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13382     return all_of(Set->Preds,
13383                   [this](const SCEVPredicate *I) { return this->implies(I); });
13384 
13385   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13386   if (ScevPredsIt == SCEVToPreds.end())
13387     return false;
13388   auto &SCEVPreds = ScevPredsIt->second;
13389 
13390   return any_of(SCEVPreds,
13391                 [N](const SCEVPredicate *I) { return I->implies(N); });
13392 }
13393 
13394 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13395 
13396 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13397   for (auto Pred : Preds)
13398     Pred->print(OS, Depth);
13399 }
13400 
13401 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13402   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13403     for (auto Pred : Set->Preds)
13404       add(Pred);
13405     return;
13406   }
13407 
13408   if (implies(N))
13409     return;
13410 
13411   const SCEV *Key = N->getExpr();
13412   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13413                 " associated expression!");
13414 
13415   SCEVToPreds[Key].push_back(N);
13416   Preds.push_back(N);
13417 }
13418 
13419 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13420                                                      Loop &L)
13421     : SE(SE), L(L) {}
13422 
13423 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13424   const SCEV *Expr = SE.getSCEV(V);
13425   RewriteEntry &Entry = RewriteMap[Expr];
13426 
13427   // If we already have an entry and the version matches, return it.
13428   if (Entry.second && Generation == Entry.first)
13429     return Entry.second;
13430 
13431   // We found an entry but it's stale. Rewrite the stale entry
13432   // according to the current predicate.
13433   if (Entry.second)
13434     Expr = Entry.second;
13435 
13436   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13437   Entry = {Generation, NewSCEV};
13438 
13439   return NewSCEV;
13440 }
13441 
13442 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13443   if (!BackedgeCount) {
13444     SCEVUnionPredicate BackedgePred;
13445     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13446     addPredicate(BackedgePred);
13447   }
13448   return BackedgeCount;
13449 }
13450 
13451 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13452   if (Preds.implies(&Pred))
13453     return;
13454   Preds.add(&Pred);
13455   updateGeneration();
13456 }
13457 
13458 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13459   return Preds;
13460 }
13461 
13462 void PredicatedScalarEvolution::updateGeneration() {
13463   // If the generation number wrapped recompute everything.
13464   if (++Generation == 0) {
13465     for (auto &II : RewriteMap) {
13466       const SCEV *Rewritten = II.second.second;
13467       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13468     }
13469   }
13470 }
13471 
13472 void PredicatedScalarEvolution::setNoOverflow(
13473     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13474   const SCEV *Expr = getSCEV(V);
13475   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13476 
13477   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13478 
13479   // Clear the statically implied flags.
13480   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13481   addPredicate(*SE.getWrapPredicate(AR, Flags));
13482 
13483   auto II = FlagsMap.insert({V, Flags});
13484   if (!II.second)
13485     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13486 }
13487 
13488 bool PredicatedScalarEvolution::hasNoOverflow(
13489     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13490   const SCEV *Expr = getSCEV(V);
13491   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13492 
13493   Flags = SCEVWrapPredicate::clearFlags(
13494       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13495 
13496   auto II = FlagsMap.find(V);
13497 
13498   if (II != FlagsMap.end())
13499     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13500 
13501   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13502 }
13503 
13504 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13505   const SCEV *Expr = this->getSCEV(V);
13506   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13507   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13508 
13509   if (!New)
13510     return nullptr;
13511 
13512   for (auto *P : NewPreds)
13513     Preds.add(P);
13514 
13515   updateGeneration();
13516   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13517   return New;
13518 }
13519 
13520 PredicatedScalarEvolution::PredicatedScalarEvolution(
13521     const PredicatedScalarEvolution &Init)
13522     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13523       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13524   for (auto I : Init.FlagsMap)
13525     FlagsMap.insert(I);
13526 }
13527 
13528 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13529   // For each block.
13530   for (auto *BB : L.getBlocks())
13531     for (auto &I : *BB) {
13532       if (!SE.isSCEVable(I.getType()))
13533         continue;
13534 
13535       auto *Expr = SE.getSCEV(&I);
13536       auto II = RewriteMap.find(Expr);
13537 
13538       if (II == RewriteMap.end())
13539         continue;
13540 
13541       // Don't print things that are not interesting.
13542       if (II->second.second == Expr)
13543         continue;
13544 
13545       OS.indent(Depth) << "[PSE]" << I << ":\n";
13546       OS.indent(Depth + 2) << *Expr << "\n";
13547       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13548     }
13549 }
13550 
13551 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13552 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13553 // for URem with constant power-of-2 second operands.
13554 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13555 // 4, A / B becomes X / 8).
13556 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13557                                 const SCEV *&RHS) {
13558   // Try to match 'zext (trunc A to iB) to iY', which is used
13559   // for URem with constant power-of-2 second operands. Make sure the size of
13560   // the operand A matches the size of the whole expressions.
13561   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13562     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13563       LHS = Trunc->getOperand();
13564       // Bail out if the type of the LHS is larger than the type of the
13565       // expression for now.
13566       if (getTypeSizeInBits(LHS->getType()) >
13567           getTypeSizeInBits(Expr->getType()))
13568         return false;
13569       if (LHS->getType() != Expr->getType())
13570         LHS = getZeroExtendExpr(LHS, Expr->getType());
13571       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13572                         << getTypeSizeInBits(Trunc->getType()));
13573       return true;
13574     }
13575   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13576   if (Add == nullptr || Add->getNumOperands() != 2)
13577     return false;
13578 
13579   const SCEV *A = Add->getOperand(1);
13580   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13581 
13582   if (Mul == nullptr)
13583     return false;
13584 
13585   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13586     // (SomeExpr + (-(SomeExpr / B) * B)).
13587     if (Expr == getURemExpr(A, B)) {
13588       LHS = A;
13589       RHS = B;
13590       return true;
13591     }
13592     return false;
13593   };
13594 
13595   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13596   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13597     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13598            MatchURemWithDivisor(Mul->getOperand(2));
13599 
13600   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13601   if (Mul->getNumOperands() == 2)
13602     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13603            MatchURemWithDivisor(Mul->getOperand(0)) ||
13604            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13605            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13606   return false;
13607 }
13608 
13609 const SCEV *
13610 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13611   SmallVector<BasicBlock*, 16> ExitingBlocks;
13612   L->getExitingBlocks(ExitingBlocks);
13613 
13614   // Form an expression for the maximum exit count possible for this loop. We
13615   // merge the max and exact information to approximate a version of
13616   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13617   SmallVector<const SCEV*, 4> ExitCounts;
13618   for (BasicBlock *ExitingBB : ExitingBlocks) {
13619     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13620     if (isa<SCEVCouldNotCompute>(ExitCount))
13621       ExitCount = getExitCount(L, ExitingBB,
13622                                   ScalarEvolution::ConstantMaximum);
13623     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13624       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13625              "We should only have known counts for exiting blocks that "
13626              "dominate latch!");
13627       ExitCounts.push_back(ExitCount);
13628     }
13629   }
13630   if (ExitCounts.empty())
13631     return getCouldNotCompute();
13632   return getUMinFromMismatchedTypes(ExitCounts);
13633 }
13634 
13635 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13636 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13637 /// we cannot guarantee that the replacement is loop invariant in the loop of
13638 /// the AddRec.
13639 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13640   ValueToSCEVMapTy &Map;
13641 
13642 public:
13643   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13644       : SCEVRewriteVisitor(SE), Map(M) {}
13645 
13646   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13647 
13648   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13649     auto I = Map.find(Expr->getValue());
13650     if (I == Map.end())
13651       return Expr;
13652     return I->second;
13653   }
13654 };
13655 
13656 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13657   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13658                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13659     // If we have LHS == 0, check if LHS is computing a property of some unknown
13660     // SCEV %v which we can rewrite %v to express explicitly.
13661     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13662     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13663         RHSC->getValue()->isNullValue()) {
13664       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13665       // explicitly express that.
13666       const SCEV *URemLHS = nullptr;
13667       const SCEV *URemRHS = nullptr;
13668       if (matchURem(LHS, URemLHS, URemRHS)) {
13669         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13670           Value *V = LHSUnknown->getValue();
13671           auto Multiple =
13672               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13673                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13674           RewriteMap[V] = Multiple;
13675           return;
13676         }
13677       }
13678     }
13679 
13680     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
13681       std::swap(LHS, RHS);
13682       Predicate = CmpInst::getSwappedPredicate(Predicate);
13683     }
13684 
13685     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
13686     // create this form when combining two checks of the form (X u< C2 + C1) and
13687     // (X >=u C1).
13688     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() {
13689       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
13690       if (!AddExpr || AddExpr->getNumOperands() != 2)
13691         return false;
13692 
13693       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
13694       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
13695       auto *C2 = dyn_cast<SCEVConstant>(RHS);
13696       if (!C1 || !C2 || !LHSUnknown)
13697         return false;
13698 
13699       auto ExactRegion =
13700           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
13701               .sub(C1->getAPInt());
13702 
13703       // Bail out, unless we have a non-wrapping, monotonic range.
13704       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
13705         return false;
13706       auto I = RewriteMap.find(LHSUnknown->getValue());
13707       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13708       RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(
13709           getConstant(ExactRegion.getUnsignedMin()),
13710           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
13711       return true;
13712     };
13713     if (MatchRangeCheckIdiom())
13714       return;
13715 
13716     // For now, limit to conditions that provide information about unknown
13717     // expressions. RHS also cannot contain add recurrences.
13718     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13719     if (!LHSUnknown || containsAddRecurrence(RHS))
13720       return;
13721 
13722     // Check whether LHS has already been rewritten. In that case we want to
13723     // chain further rewrites onto the already rewritten value.
13724     auto I = RewriteMap.find(LHSUnknown->getValue());
13725     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13726     const SCEV *RewrittenRHS = nullptr;
13727     switch (Predicate) {
13728     case CmpInst::ICMP_ULT:
13729       RewrittenRHS =
13730           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13731       break;
13732     case CmpInst::ICMP_SLT:
13733       RewrittenRHS =
13734           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13735       break;
13736     case CmpInst::ICMP_ULE:
13737       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
13738       break;
13739     case CmpInst::ICMP_SLE:
13740       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
13741       break;
13742     case CmpInst::ICMP_UGT:
13743       RewrittenRHS =
13744           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13745       break;
13746     case CmpInst::ICMP_SGT:
13747       RewrittenRHS =
13748           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13749       break;
13750     case CmpInst::ICMP_UGE:
13751       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
13752       break;
13753     case CmpInst::ICMP_SGE:
13754       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
13755       break;
13756     case CmpInst::ICMP_EQ:
13757       if (isa<SCEVConstant>(RHS))
13758         RewrittenRHS = RHS;
13759       break;
13760     case CmpInst::ICMP_NE:
13761       if (isa<SCEVConstant>(RHS) &&
13762           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13763         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
13764       break;
13765     default:
13766       break;
13767     }
13768 
13769     if (RewrittenRHS)
13770       RewriteMap[LHSUnknown->getValue()] = RewrittenRHS;
13771   };
13772   // Starting at the loop predecessor, climb up the predecessor chain, as long
13773   // as there are predecessors that can be found that have unique successors
13774   // leading to the original header.
13775   // TODO: share this logic with isLoopEntryGuardedByCond.
13776   ValueToSCEVMapTy RewriteMap;
13777   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13778            L->getLoopPredecessor(), L->getHeader());
13779        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13780 
13781     const BranchInst *LoopEntryPredicate =
13782         dyn_cast<BranchInst>(Pair.first->getTerminator());
13783     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13784       continue;
13785 
13786     bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second;
13787     SmallVector<Value *, 8> Worklist;
13788     SmallPtrSet<Value *, 8> Visited;
13789     Worklist.push_back(LoopEntryPredicate->getCondition());
13790     while (!Worklist.empty()) {
13791       Value *Cond = Worklist.pop_back_val();
13792       if (!Visited.insert(Cond).second)
13793         continue;
13794 
13795       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13796         auto Predicate =
13797             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
13798         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13799                          getSCEV(Cmp->getOperand(1)), RewriteMap);
13800         continue;
13801       }
13802 
13803       Value *L, *R;
13804       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
13805                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
13806         Worklist.push_back(L);
13807         Worklist.push_back(R);
13808       }
13809     }
13810   }
13811 
13812   // Also collect information from assumptions dominating the loop.
13813   for (auto &AssumeVH : AC.assumptions()) {
13814     if (!AssumeVH)
13815       continue;
13816     auto *AssumeI = cast<CallInst>(AssumeVH);
13817     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13818     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13819       continue;
13820     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13821                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13822   }
13823 
13824   if (RewriteMap.empty())
13825     return Expr;
13826   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13827   return Rewriter.visit(Expr);
13828 }
13829