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 /// Compute an expression equivalent to S - getPointerBase(S).
4135 static const SCEV *removePointerBase(ScalarEvolution *SE, const SCEV *P) {
4136   assert(P->getType()->isPointerTy());
4137 
4138   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4139     // The base of an AddRec is the first operand.
4140     SmallVector<const SCEV *> Ops{AddRec->operands()};
4141     Ops[0] = removePointerBase(SE, Ops[0]);
4142     // Don't try to transfer nowrap flags for now. We could in some cases
4143     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4144     return SE->getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4145   }
4146   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4147     // The base of an Add is the pointer operand.
4148     SmallVector<const SCEV *> Ops{Add->operands()};
4149     const SCEV **PtrOp = nullptr;
4150     for (const SCEV *&AddOp : Ops) {
4151       if (AddOp->getType()->isPointerTy()) {
4152         // If we find an Add with multiple pointer operands, treat it as a
4153         // pointer base to be consistent with getPointerBase.  Eventually
4154         // we should be able to assert this is impossible.
4155         if (PtrOp)
4156           return SE->getZero(P->getType());
4157         PtrOp = &AddOp;
4158       }
4159     }
4160     *PtrOp = removePointerBase(SE, *PtrOp);
4161     // Don't try to transfer nowrap flags for now. We could in some cases
4162     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4163     return SE->getAddExpr(Ops);
4164   }
4165   // Any other expression must be a pointer base.
4166   return SE->getZero(P->getType());
4167 }
4168 
4169 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4170                                           SCEV::NoWrapFlags Flags,
4171                                           unsigned Depth) {
4172   // Fast path: X - X --> 0.
4173   if (LHS == RHS)
4174     return getZero(LHS->getType());
4175 
4176   // If we subtract two pointers with different pointer bases, bail.
4177   // Eventually, we're going to add an assertion to getMulExpr that we
4178   // can't multiply by a pointer.
4179   if (RHS->getType()->isPointerTy()) {
4180     if (!LHS->getType()->isPointerTy() ||
4181         getPointerBase(LHS) != getPointerBase(RHS))
4182       return getCouldNotCompute();
4183     LHS = removePointerBase(this, LHS);
4184     RHS = removePointerBase(this, RHS);
4185   }
4186 
4187   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4188   // makes it so that we cannot make much use of NUW.
4189   auto AddFlags = SCEV::FlagAnyWrap;
4190   const bool RHSIsNotMinSigned =
4191       !getSignedRangeMin(RHS).isMinSignedValue();
4192   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4193     // Let M be the minimum representable signed value. Then (-1)*RHS
4194     // signed-wraps if and only if RHS is M. That can happen even for
4195     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4196     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4197     // (-1)*RHS, we need to prove that RHS != M.
4198     //
4199     // If LHS is non-negative and we know that LHS - RHS does not
4200     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4201     // either by proving that RHS > M or that LHS >= 0.
4202     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4203       AddFlags = SCEV::FlagNSW;
4204     }
4205   }
4206 
4207   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4208   // RHS is NSW and LHS >= 0.
4209   //
4210   // The difficulty here is that the NSW flag may have been proven
4211   // relative to a loop that is to be found in a recurrence in LHS and
4212   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4213   // larger scope than intended.
4214   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4215 
4216   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4217 }
4218 
4219 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4220                                                      unsigned Depth) {
4221   Type *SrcTy = V->getType();
4222   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4223          "Cannot truncate or zero extend with non-integer arguments!");
4224   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4225     return V;  // No conversion
4226   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4227     return getTruncateExpr(V, Ty, Depth);
4228   return getZeroExtendExpr(V, Ty, Depth);
4229 }
4230 
4231 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4232                                                      unsigned Depth) {
4233   Type *SrcTy = V->getType();
4234   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4235          "Cannot truncate or zero extend with non-integer arguments!");
4236   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4237     return V;  // No conversion
4238   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4239     return getTruncateExpr(V, Ty, Depth);
4240   return getSignExtendExpr(V, Ty, Depth);
4241 }
4242 
4243 const SCEV *
4244 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4245   Type *SrcTy = V->getType();
4246   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4247          "Cannot noop or zero extend with non-integer arguments!");
4248   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4249          "getNoopOrZeroExtend cannot truncate!");
4250   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4251     return V;  // No conversion
4252   return getZeroExtendExpr(V, Ty);
4253 }
4254 
4255 const SCEV *
4256 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4257   Type *SrcTy = V->getType();
4258   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4259          "Cannot noop or sign extend with non-integer arguments!");
4260   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4261          "getNoopOrSignExtend cannot truncate!");
4262   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4263     return V;  // No conversion
4264   return getSignExtendExpr(V, Ty);
4265 }
4266 
4267 const SCEV *
4268 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4269   Type *SrcTy = V->getType();
4270   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4271          "Cannot noop or any extend with non-integer arguments!");
4272   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4273          "getNoopOrAnyExtend cannot truncate!");
4274   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4275     return V;  // No conversion
4276   return getAnyExtendExpr(V, Ty);
4277 }
4278 
4279 const SCEV *
4280 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4281   Type *SrcTy = V->getType();
4282   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4283          "Cannot truncate or noop with non-integer arguments!");
4284   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4285          "getTruncateOrNoop cannot extend!");
4286   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4287     return V;  // No conversion
4288   return getTruncateExpr(V, Ty);
4289 }
4290 
4291 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4292                                                         const SCEV *RHS) {
4293   const SCEV *PromotedLHS = LHS;
4294   const SCEV *PromotedRHS = RHS;
4295 
4296   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4297     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4298   else
4299     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4300 
4301   return getUMaxExpr(PromotedLHS, PromotedRHS);
4302 }
4303 
4304 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4305                                                         const SCEV *RHS) {
4306   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4307   return getUMinFromMismatchedTypes(Ops);
4308 }
4309 
4310 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4311     SmallVectorImpl<const SCEV *> &Ops) {
4312   assert(!Ops.empty() && "At least one operand must be!");
4313   // Trivial case.
4314   if (Ops.size() == 1)
4315     return Ops[0];
4316 
4317   // Find the max type first.
4318   Type *MaxType = nullptr;
4319   for (auto *S : Ops)
4320     if (MaxType)
4321       MaxType = getWiderType(MaxType, S->getType());
4322     else
4323       MaxType = S->getType();
4324   assert(MaxType && "Failed to find maximum type!");
4325 
4326   // Extend all ops to max type.
4327   SmallVector<const SCEV *, 2> PromotedOps;
4328   for (auto *S : Ops)
4329     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4330 
4331   // Generate umin.
4332   return getUMinExpr(PromotedOps);
4333 }
4334 
4335 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4336   // A pointer operand may evaluate to a nonpointer expression, such as null.
4337   if (!V->getType()->isPointerTy())
4338     return V;
4339 
4340   while (true) {
4341     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4342       V = AddRec->getStart();
4343     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4344       const SCEV *PtrOp = nullptr;
4345       for (const SCEV *AddOp : Add->operands()) {
4346         if (AddOp->getType()->isPointerTy()) {
4347           // Cannot find the base of an expression with multiple pointer ops.
4348           if (PtrOp)
4349             return V;
4350           PtrOp = AddOp;
4351         }
4352       }
4353       if (!PtrOp) // All operands were non-pointer.
4354         return V;
4355       V = PtrOp;
4356     } else // Not something we can look further into.
4357       return V;
4358   }
4359 }
4360 
4361 /// Push users of the given Instruction onto the given Worklist.
4362 static void
4363 PushDefUseChildren(Instruction *I,
4364                    SmallVectorImpl<Instruction *> &Worklist) {
4365   // Push the def-use children onto the Worklist stack.
4366   for (User *U : I->users())
4367     Worklist.push_back(cast<Instruction>(U));
4368 }
4369 
4370 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4371   SmallVector<Instruction *, 16> Worklist;
4372   PushDefUseChildren(PN, Worklist);
4373 
4374   SmallPtrSet<Instruction *, 8> Visited;
4375   Visited.insert(PN);
4376   while (!Worklist.empty()) {
4377     Instruction *I = Worklist.pop_back_val();
4378     if (!Visited.insert(I).second)
4379       continue;
4380 
4381     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4382     if (It != ValueExprMap.end()) {
4383       const SCEV *Old = It->second;
4384 
4385       // Short-circuit the def-use traversal if the symbolic name
4386       // ceases to appear in expressions.
4387       if (Old != SymName && !hasOperand(Old, SymName))
4388         continue;
4389 
4390       // SCEVUnknown for a PHI either means that it has an unrecognized
4391       // structure, it's a PHI that's in the progress of being computed
4392       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4393       // additional loop trip count information isn't going to change anything.
4394       // In the second case, createNodeForPHI will perform the necessary
4395       // updates on its own when it gets to that point. In the third, we do
4396       // want to forget the SCEVUnknown.
4397       if (!isa<PHINode>(I) ||
4398           !isa<SCEVUnknown>(Old) ||
4399           (I != PN && Old == SymName)) {
4400         eraseValueFromMap(It->first);
4401         forgetMemoizedResults(Old);
4402       }
4403     }
4404 
4405     PushDefUseChildren(I, Worklist);
4406   }
4407 }
4408 
4409 namespace {
4410 
4411 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4412 /// expression in case its Loop is L. If it is not L then
4413 /// if IgnoreOtherLoops is true then use AddRec itself
4414 /// otherwise rewrite cannot be done.
4415 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4416 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4417 public:
4418   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4419                              bool IgnoreOtherLoops = true) {
4420     SCEVInitRewriter Rewriter(L, SE);
4421     const SCEV *Result = Rewriter.visit(S);
4422     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4423       return SE.getCouldNotCompute();
4424     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4425                ? SE.getCouldNotCompute()
4426                : Result;
4427   }
4428 
4429   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4430     if (!SE.isLoopInvariant(Expr, L))
4431       SeenLoopVariantSCEVUnknown = true;
4432     return Expr;
4433   }
4434 
4435   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4436     // Only re-write AddRecExprs for this loop.
4437     if (Expr->getLoop() == L)
4438       return Expr->getStart();
4439     SeenOtherLoops = true;
4440     return Expr;
4441   }
4442 
4443   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4444 
4445   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4446 
4447 private:
4448   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4449       : SCEVRewriteVisitor(SE), L(L) {}
4450 
4451   const Loop *L;
4452   bool SeenLoopVariantSCEVUnknown = false;
4453   bool SeenOtherLoops = false;
4454 };
4455 
4456 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4457 /// increment expression in case its Loop is L. If it is not L then
4458 /// use AddRec itself.
4459 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4460 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4461 public:
4462   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4463     SCEVPostIncRewriter Rewriter(L, SE);
4464     const SCEV *Result = Rewriter.visit(S);
4465     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4466         ? SE.getCouldNotCompute()
4467         : Result;
4468   }
4469 
4470   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4471     if (!SE.isLoopInvariant(Expr, L))
4472       SeenLoopVariantSCEVUnknown = true;
4473     return Expr;
4474   }
4475 
4476   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4477     // Only re-write AddRecExprs for this loop.
4478     if (Expr->getLoop() == L)
4479       return Expr->getPostIncExpr(SE);
4480     SeenOtherLoops = true;
4481     return Expr;
4482   }
4483 
4484   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4485 
4486   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4487 
4488 private:
4489   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4490       : SCEVRewriteVisitor(SE), L(L) {}
4491 
4492   const Loop *L;
4493   bool SeenLoopVariantSCEVUnknown = false;
4494   bool SeenOtherLoops = false;
4495 };
4496 
4497 /// This class evaluates the compare condition by matching it against the
4498 /// condition of loop latch. If there is a match we assume a true value
4499 /// for the condition while building SCEV nodes.
4500 class SCEVBackedgeConditionFolder
4501     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4502 public:
4503   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4504                              ScalarEvolution &SE) {
4505     bool IsPosBECond = false;
4506     Value *BECond = nullptr;
4507     if (BasicBlock *Latch = L->getLoopLatch()) {
4508       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4509       if (BI && BI->isConditional()) {
4510         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4511                "Both outgoing branches should not target same header!");
4512         BECond = BI->getCondition();
4513         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4514       } else {
4515         return S;
4516       }
4517     }
4518     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4519     return Rewriter.visit(S);
4520   }
4521 
4522   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4523     const SCEV *Result = Expr;
4524     bool InvariantF = SE.isLoopInvariant(Expr, L);
4525 
4526     if (!InvariantF) {
4527       Instruction *I = cast<Instruction>(Expr->getValue());
4528       switch (I->getOpcode()) {
4529       case Instruction::Select: {
4530         SelectInst *SI = cast<SelectInst>(I);
4531         Optional<const SCEV *> Res =
4532             compareWithBackedgeCondition(SI->getCondition());
4533         if (Res.hasValue()) {
4534           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4535           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4536         }
4537         break;
4538       }
4539       default: {
4540         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4541         if (Res.hasValue())
4542           Result = Res.getValue();
4543         break;
4544       }
4545       }
4546     }
4547     return Result;
4548   }
4549 
4550 private:
4551   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4552                                        bool IsPosBECond, ScalarEvolution &SE)
4553       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4554         IsPositiveBECond(IsPosBECond) {}
4555 
4556   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4557 
4558   const Loop *L;
4559   /// Loop back condition.
4560   Value *BackedgeCond = nullptr;
4561   /// Set to true if loop back is on positive branch condition.
4562   bool IsPositiveBECond;
4563 };
4564 
4565 Optional<const SCEV *>
4566 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4567 
4568   // If value matches the backedge condition for loop latch,
4569   // then return a constant evolution node based on loopback
4570   // branch taken.
4571   if (BackedgeCond == IC)
4572     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4573                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4574   return None;
4575 }
4576 
4577 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4578 public:
4579   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4580                              ScalarEvolution &SE) {
4581     SCEVShiftRewriter Rewriter(L, SE);
4582     const SCEV *Result = Rewriter.visit(S);
4583     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4584   }
4585 
4586   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4587     // Only allow AddRecExprs for this loop.
4588     if (!SE.isLoopInvariant(Expr, L))
4589       Valid = false;
4590     return Expr;
4591   }
4592 
4593   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4594     if (Expr->getLoop() == L && Expr->isAffine())
4595       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4596     Valid = false;
4597     return Expr;
4598   }
4599 
4600   bool isValid() { return Valid; }
4601 
4602 private:
4603   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4604       : SCEVRewriteVisitor(SE), L(L) {}
4605 
4606   const Loop *L;
4607   bool Valid = true;
4608 };
4609 
4610 } // end anonymous namespace
4611 
4612 SCEV::NoWrapFlags
4613 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4614   if (!AR->isAffine())
4615     return SCEV::FlagAnyWrap;
4616 
4617   using OBO = OverflowingBinaryOperator;
4618 
4619   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4620 
4621   if (!AR->hasNoSignedWrap()) {
4622     ConstantRange AddRecRange = getSignedRange(AR);
4623     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4624 
4625     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4626         Instruction::Add, IncRange, OBO::NoSignedWrap);
4627     if (NSWRegion.contains(AddRecRange))
4628       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4629   }
4630 
4631   if (!AR->hasNoUnsignedWrap()) {
4632     ConstantRange AddRecRange = getUnsignedRange(AR);
4633     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4634 
4635     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4636         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4637     if (NUWRegion.contains(AddRecRange))
4638       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4639   }
4640 
4641   return Result;
4642 }
4643 
4644 SCEV::NoWrapFlags
4645 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4646   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4647 
4648   if (AR->hasNoSignedWrap())
4649     return Result;
4650 
4651   if (!AR->isAffine())
4652     return Result;
4653 
4654   const SCEV *Step = AR->getStepRecurrence(*this);
4655   const Loop *L = AR->getLoop();
4656 
4657   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4658   // Note that this serves two purposes: It filters out loops that are
4659   // simply not analyzable, and it covers the case where this code is
4660   // being called from within backedge-taken count analysis, such that
4661   // attempting to ask for the backedge-taken count would likely result
4662   // in infinite recursion. In the later case, the analysis code will
4663   // cope with a conservative value, and it will take care to purge
4664   // that value once it has finished.
4665   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4666 
4667   // Normally, in the cases we can prove no-overflow via a
4668   // backedge guarding condition, we can also compute a backedge
4669   // taken count for the loop.  The exceptions are assumptions and
4670   // guards present in the loop -- SCEV is not great at exploiting
4671   // these to compute max backedge taken counts, but can still use
4672   // these to prove lack of overflow.  Use this fact to avoid
4673   // doing extra work that may not pay off.
4674 
4675   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4676       AC.assumptions().empty())
4677     return Result;
4678 
4679   // If the backedge is guarded by a comparison with the pre-inc  value the
4680   // addrec is safe. Also, if the entry is guarded by a comparison with the
4681   // start value and the backedge is guarded by a comparison with the post-inc
4682   // value, the addrec is safe.
4683   ICmpInst::Predicate Pred;
4684   const SCEV *OverflowLimit =
4685     getSignedOverflowLimitForStep(Step, &Pred, this);
4686   if (OverflowLimit &&
4687       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4688        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4689     Result = setFlags(Result, SCEV::FlagNSW);
4690   }
4691   return Result;
4692 }
4693 SCEV::NoWrapFlags
4694 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4695   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4696 
4697   if (AR->hasNoUnsignedWrap())
4698     return Result;
4699 
4700   if (!AR->isAffine())
4701     return Result;
4702 
4703   const SCEV *Step = AR->getStepRecurrence(*this);
4704   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4705   const Loop *L = AR->getLoop();
4706 
4707   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4708   // Note that this serves two purposes: It filters out loops that are
4709   // simply not analyzable, and it covers the case where this code is
4710   // being called from within backedge-taken count analysis, such that
4711   // attempting to ask for the backedge-taken count would likely result
4712   // in infinite recursion. In the later case, the analysis code will
4713   // cope with a conservative value, and it will take care to purge
4714   // that value once it has finished.
4715   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4716 
4717   // Normally, in the cases we can prove no-overflow via a
4718   // backedge guarding condition, we can also compute a backedge
4719   // taken count for the loop.  The exceptions are assumptions and
4720   // guards present in the loop -- SCEV is not great at exploiting
4721   // these to compute max backedge taken counts, but can still use
4722   // these to prove lack of overflow.  Use this fact to avoid
4723   // doing extra work that may not pay off.
4724 
4725   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4726       AC.assumptions().empty())
4727     return Result;
4728 
4729   // If the backedge is guarded by a comparison with the pre-inc  value the
4730   // addrec is safe. Also, if the entry is guarded by a comparison with the
4731   // start value and the backedge is guarded by a comparison with the post-inc
4732   // value, the addrec is safe.
4733   if (isKnownPositive(Step)) {
4734     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4735                                 getUnsignedRangeMax(Step));
4736     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4737         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4738       Result = setFlags(Result, SCEV::FlagNUW);
4739     }
4740   }
4741 
4742   return Result;
4743 }
4744 
4745 namespace {
4746 
4747 /// Represents an abstract binary operation.  This may exist as a
4748 /// normal instruction or constant expression, or may have been
4749 /// derived from an expression tree.
4750 struct BinaryOp {
4751   unsigned Opcode;
4752   Value *LHS;
4753   Value *RHS;
4754   bool IsNSW = false;
4755   bool IsNUW = false;
4756 
4757   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4758   /// constant expression.
4759   Operator *Op = nullptr;
4760 
4761   explicit BinaryOp(Operator *Op)
4762       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4763         Op(Op) {
4764     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4765       IsNSW = OBO->hasNoSignedWrap();
4766       IsNUW = OBO->hasNoUnsignedWrap();
4767     }
4768   }
4769 
4770   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4771                     bool IsNUW = false)
4772       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4773 };
4774 
4775 } // end anonymous namespace
4776 
4777 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4778 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4779   auto *Op = dyn_cast<Operator>(V);
4780   if (!Op)
4781     return None;
4782 
4783   // Implementation detail: all the cleverness here should happen without
4784   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4785   // SCEV expressions when possible, and we should not break that.
4786 
4787   switch (Op->getOpcode()) {
4788   case Instruction::Add:
4789   case Instruction::Sub:
4790   case Instruction::Mul:
4791   case Instruction::UDiv:
4792   case Instruction::URem:
4793   case Instruction::And:
4794   case Instruction::Or:
4795   case Instruction::AShr:
4796   case Instruction::Shl:
4797     return BinaryOp(Op);
4798 
4799   case Instruction::Xor:
4800     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4801       // If the RHS of the xor is a signmask, then this is just an add.
4802       // Instcombine turns add of signmask into xor as a strength reduction step.
4803       if (RHSC->getValue().isSignMask())
4804         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4805     return BinaryOp(Op);
4806 
4807   case Instruction::LShr:
4808     // Turn logical shift right of a constant into a unsigned divide.
4809     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4810       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4811 
4812       // If the shift count is not less than the bitwidth, the result of
4813       // the shift is undefined. Don't try to analyze it, because the
4814       // resolution chosen here may differ from the resolution chosen in
4815       // other parts of the compiler.
4816       if (SA->getValue().ult(BitWidth)) {
4817         Constant *X =
4818             ConstantInt::get(SA->getContext(),
4819                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4820         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4821       }
4822     }
4823     return BinaryOp(Op);
4824 
4825   case Instruction::ExtractValue: {
4826     auto *EVI = cast<ExtractValueInst>(Op);
4827     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4828       break;
4829 
4830     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4831     if (!WO)
4832       break;
4833 
4834     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4835     bool Signed = WO->isSigned();
4836     // TODO: Should add nuw/nsw flags for mul as well.
4837     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4838       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4839 
4840     // Now that we know that all uses of the arithmetic-result component of
4841     // CI are guarded by the overflow check, we can go ahead and pretend
4842     // that the arithmetic is non-overflowing.
4843     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4844                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4845   }
4846 
4847   default:
4848     break;
4849   }
4850 
4851   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4852   // semantics as a Sub, return a binary sub expression.
4853   if (auto *II = dyn_cast<IntrinsicInst>(V))
4854     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4855       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4856 
4857   return None;
4858 }
4859 
4860 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4861 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4862 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4863 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4864 /// follows one of the following patterns:
4865 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4866 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4867 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4868 /// we return the type of the truncation operation, and indicate whether the
4869 /// truncated type should be treated as signed/unsigned by setting
4870 /// \p Signed to true/false, respectively.
4871 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4872                                bool &Signed, ScalarEvolution &SE) {
4873   // The case where Op == SymbolicPHI (that is, with no type conversions on
4874   // the way) is handled by the regular add recurrence creating logic and
4875   // would have already been triggered in createAddRecForPHI. Reaching it here
4876   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4877   // because one of the other operands of the SCEVAddExpr updating this PHI is
4878   // not invariant).
4879   //
4880   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4881   // this case predicates that allow us to prove that Op == SymbolicPHI will
4882   // be added.
4883   if (Op == SymbolicPHI)
4884     return nullptr;
4885 
4886   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4887   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4888   if (SourceBits != NewBits)
4889     return nullptr;
4890 
4891   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4892   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4893   if (!SExt && !ZExt)
4894     return nullptr;
4895   const SCEVTruncateExpr *Trunc =
4896       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4897            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4898   if (!Trunc)
4899     return nullptr;
4900   const SCEV *X = Trunc->getOperand();
4901   if (X != SymbolicPHI)
4902     return nullptr;
4903   Signed = SExt != nullptr;
4904   return Trunc->getType();
4905 }
4906 
4907 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4908   if (!PN->getType()->isIntegerTy())
4909     return nullptr;
4910   const Loop *L = LI.getLoopFor(PN->getParent());
4911   if (!L || L->getHeader() != PN->getParent())
4912     return nullptr;
4913   return L;
4914 }
4915 
4916 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4917 // computation that updates the phi follows the following pattern:
4918 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4919 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4920 // If so, try to see if it can be rewritten as an AddRecExpr under some
4921 // Predicates. If successful, return them as a pair. Also cache the results
4922 // of the analysis.
4923 //
4924 // Example usage scenario:
4925 //    Say the Rewriter is called for the following SCEV:
4926 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4927 //    where:
4928 //         %X = phi i64 (%Start, %BEValue)
4929 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4930 //    and call this function with %SymbolicPHI = %X.
4931 //
4932 //    The analysis will find that the value coming around the backedge has
4933 //    the following SCEV:
4934 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4935 //    Upon concluding that this matches the desired pattern, the function
4936 //    will return the pair {NewAddRec, SmallPredsVec} where:
4937 //         NewAddRec = {%Start,+,%Step}
4938 //         SmallPredsVec = {P1, P2, P3} as follows:
4939 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4940 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4941 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4942 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4943 //    under the predicates {P1,P2,P3}.
4944 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4945 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4946 //
4947 // TODO's:
4948 //
4949 // 1) Extend the Induction descriptor to also support inductions that involve
4950 //    casts: When needed (namely, when we are called in the context of the
4951 //    vectorizer induction analysis), a Set of cast instructions will be
4952 //    populated by this method, and provided back to isInductionPHI. This is
4953 //    needed to allow the vectorizer to properly record them to be ignored by
4954 //    the cost model and to avoid vectorizing them (otherwise these casts,
4955 //    which are redundant under the runtime overflow checks, will be
4956 //    vectorized, which can be costly).
4957 //
4958 // 2) Support additional induction/PHISCEV patterns: We also want to support
4959 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4960 //    after the induction update operation (the induction increment):
4961 //
4962 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4963 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4964 //
4965 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4966 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4967 //
4968 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4969 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4970 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4971   SmallVector<const SCEVPredicate *, 3> Predicates;
4972 
4973   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4974   // return an AddRec expression under some predicate.
4975 
4976   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4977   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4978   assert(L && "Expecting an integer loop header phi");
4979 
4980   // The loop may have multiple entrances or multiple exits; we can analyze
4981   // this phi as an addrec if it has a unique entry value and a unique
4982   // backedge value.
4983   Value *BEValueV = nullptr, *StartValueV = nullptr;
4984   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4985     Value *V = PN->getIncomingValue(i);
4986     if (L->contains(PN->getIncomingBlock(i))) {
4987       if (!BEValueV) {
4988         BEValueV = V;
4989       } else if (BEValueV != V) {
4990         BEValueV = nullptr;
4991         break;
4992       }
4993     } else if (!StartValueV) {
4994       StartValueV = V;
4995     } else if (StartValueV != V) {
4996       StartValueV = nullptr;
4997       break;
4998     }
4999   }
5000   if (!BEValueV || !StartValueV)
5001     return None;
5002 
5003   const SCEV *BEValue = getSCEV(BEValueV);
5004 
5005   // If the value coming around the backedge is an add with the symbolic
5006   // value we just inserted, possibly with casts that we can ignore under
5007   // an appropriate runtime guard, then we found a simple induction variable!
5008   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5009   if (!Add)
5010     return None;
5011 
5012   // If there is a single occurrence of the symbolic value, possibly
5013   // casted, replace it with a recurrence.
5014   unsigned FoundIndex = Add->getNumOperands();
5015   Type *TruncTy = nullptr;
5016   bool Signed;
5017   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5018     if ((TruncTy =
5019              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5020       if (FoundIndex == e) {
5021         FoundIndex = i;
5022         break;
5023       }
5024 
5025   if (FoundIndex == Add->getNumOperands())
5026     return None;
5027 
5028   // Create an add with everything but the specified operand.
5029   SmallVector<const SCEV *, 8> Ops;
5030   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5031     if (i != FoundIndex)
5032       Ops.push_back(Add->getOperand(i));
5033   const SCEV *Accum = getAddExpr(Ops);
5034 
5035   // The runtime checks will not be valid if the step amount is
5036   // varying inside the loop.
5037   if (!isLoopInvariant(Accum, L))
5038     return None;
5039 
5040   // *** Part2: Create the predicates
5041 
5042   // Analysis was successful: we have a phi-with-cast pattern for which we
5043   // can return an AddRec expression under the following predicates:
5044   //
5045   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5046   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5047   // P2: An Equal predicate that guarantees that
5048   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5049   // P3: An Equal predicate that guarantees that
5050   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5051   //
5052   // As we next prove, the above predicates guarantee that:
5053   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5054   //
5055   //
5056   // More formally, we want to prove that:
5057   //     Expr(i+1) = Start + (i+1) * Accum
5058   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5059   //
5060   // Given that:
5061   // 1) Expr(0) = Start
5062   // 2) Expr(1) = Start + Accum
5063   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5064   // 3) Induction hypothesis (step i):
5065   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5066   //
5067   // Proof:
5068   //  Expr(i+1) =
5069   //   = Start + (i+1)*Accum
5070   //   = (Start + i*Accum) + Accum
5071   //   = Expr(i) + Accum
5072   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5073   //                                                             :: from step i
5074   //
5075   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5076   //
5077   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5078   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5079   //     + Accum                                                     :: from P3
5080   //
5081   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5082   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5083   //
5084   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5085   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5086   //
5087   // By induction, the same applies to all iterations 1<=i<n:
5088   //
5089 
5090   // Create a truncated addrec for which we will add a no overflow check (P1).
5091   const SCEV *StartVal = getSCEV(StartValueV);
5092   const SCEV *PHISCEV =
5093       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5094                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5095 
5096   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5097   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5098   // will be constant.
5099   //
5100   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5101   // add P1.
5102   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5103     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5104         Signed ? SCEVWrapPredicate::IncrementNSSW
5105                : SCEVWrapPredicate::IncrementNUSW;
5106     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5107     Predicates.push_back(AddRecPred);
5108   }
5109 
5110   // Create the Equal Predicates P2,P3:
5111 
5112   // It is possible that the predicates P2 and/or P3 are computable at
5113   // compile time due to StartVal and/or Accum being constants.
5114   // If either one is, then we can check that now and escape if either P2
5115   // or P3 is false.
5116 
5117   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5118   // for each of StartVal and Accum
5119   auto getExtendedExpr = [&](const SCEV *Expr,
5120                              bool CreateSignExtend) -> const SCEV * {
5121     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5122     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5123     const SCEV *ExtendedExpr =
5124         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5125                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5126     return ExtendedExpr;
5127   };
5128 
5129   // Given:
5130   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5131   //               = getExtendedExpr(Expr)
5132   // Determine whether the predicate P: Expr == ExtendedExpr
5133   // is known to be false at compile time
5134   auto PredIsKnownFalse = [&](const SCEV *Expr,
5135                               const SCEV *ExtendedExpr) -> bool {
5136     return Expr != ExtendedExpr &&
5137            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5138   };
5139 
5140   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5141   if (PredIsKnownFalse(StartVal, StartExtended)) {
5142     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5143     return None;
5144   }
5145 
5146   // The Step is always Signed (because the overflow checks are either
5147   // NSSW or NUSW)
5148   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5149   if (PredIsKnownFalse(Accum, AccumExtended)) {
5150     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5151     return None;
5152   }
5153 
5154   auto AppendPredicate = [&](const SCEV *Expr,
5155                              const SCEV *ExtendedExpr) -> void {
5156     if (Expr != ExtendedExpr &&
5157         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5158       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5159       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5160       Predicates.push_back(Pred);
5161     }
5162   };
5163 
5164   AppendPredicate(StartVal, StartExtended);
5165   AppendPredicate(Accum, AccumExtended);
5166 
5167   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5168   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5169   // into NewAR if it will also add the runtime overflow checks specified in
5170   // Predicates.
5171   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5172 
5173   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5174       std::make_pair(NewAR, Predicates);
5175   // Remember the result of the analysis for this SCEV at this locayyytion.
5176   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5177   return PredRewrite;
5178 }
5179 
5180 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5181 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5182   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5183   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5184   if (!L)
5185     return None;
5186 
5187   // Check to see if we already analyzed this PHI.
5188   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5189   if (I != PredicatedSCEVRewrites.end()) {
5190     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5191         I->second;
5192     // Analysis was done before and failed to create an AddRec:
5193     if (Rewrite.first == SymbolicPHI)
5194       return None;
5195     // Analysis was done before and succeeded to create an AddRec under
5196     // a predicate:
5197     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5198     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5199     return Rewrite;
5200   }
5201 
5202   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5203     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5204 
5205   // Record in the cache that the analysis failed
5206   if (!Rewrite) {
5207     SmallVector<const SCEVPredicate *, 3> Predicates;
5208     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5209     return None;
5210   }
5211 
5212   return Rewrite;
5213 }
5214 
5215 // FIXME: This utility is currently required because the Rewriter currently
5216 // does not rewrite this expression:
5217 // {0, +, (sext ix (trunc iy to ix) to iy)}
5218 // into {0, +, %step},
5219 // even when the following Equal predicate exists:
5220 // "%step == (sext ix (trunc iy to ix) to iy)".
5221 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5222     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5223   if (AR1 == AR2)
5224     return true;
5225 
5226   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5227     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5228         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5229       return false;
5230     return true;
5231   };
5232 
5233   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5234       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5235     return false;
5236   return true;
5237 }
5238 
5239 /// A helper function for createAddRecFromPHI to handle simple cases.
5240 ///
5241 /// This function tries to find an AddRec expression for the simplest (yet most
5242 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5243 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5244 /// technique for finding the AddRec expression.
5245 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5246                                                       Value *BEValueV,
5247                                                       Value *StartValueV) {
5248   const Loop *L = LI.getLoopFor(PN->getParent());
5249   assert(L && L->getHeader() == PN->getParent());
5250   assert(BEValueV && StartValueV);
5251 
5252   auto BO = MatchBinaryOp(BEValueV, DT);
5253   if (!BO)
5254     return nullptr;
5255 
5256   if (BO->Opcode != Instruction::Add)
5257     return nullptr;
5258 
5259   const SCEV *Accum = nullptr;
5260   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5261     Accum = getSCEV(BO->RHS);
5262   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5263     Accum = getSCEV(BO->LHS);
5264 
5265   if (!Accum)
5266     return nullptr;
5267 
5268   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5269   if (BO->IsNUW)
5270     Flags = setFlags(Flags, SCEV::FlagNUW);
5271   if (BO->IsNSW)
5272     Flags = setFlags(Flags, SCEV::FlagNSW);
5273 
5274   const SCEV *StartVal = getSCEV(StartValueV);
5275   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5276 
5277   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5278 
5279   // We can add Flags to the post-inc expression only if we
5280   // know that it is *undefined behavior* for BEValueV to
5281   // overflow.
5282   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5283     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5284       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5285 
5286   return PHISCEV;
5287 }
5288 
5289 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5290   const Loop *L = LI.getLoopFor(PN->getParent());
5291   if (!L || L->getHeader() != PN->getParent())
5292     return nullptr;
5293 
5294   // The loop may have multiple entrances or multiple exits; we can analyze
5295   // this phi as an addrec if it has a unique entry value and a unique
5296   // backedge value.
5297   Value *BEValueV = nullptr, *StartValueV = nullptr;
5298   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5299     Value *V = PN->getIncomingValue(i);
5300     if (L->contains(PN->getIncomingBlock(i))) {
5301       if (!BEValueV) {
5302         BEValueV = V;
5303       } else if (BEValueV != V) {
5304         BEValueV = nullptr;
5305         break;
5306       }
5307     } else if (!StartValueV) {
5308       StartValueV = V;
5309     } else if (StartValueV != V) {
5310       StartValueV = nullptr;
5311       break;
5312     }
5313   }
5314   if (!BEValueV || !StartValueV)
5315     return nullptr;
5316 
5317   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5318          "PHI node already processed?");
5319 
5320   // First, try to find AddRec expression without creating a fictituos symbolic
5321   // value for PN.
5322   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5323     return S;
5324 
5325   // Handle PHI node value symbolically.
5326   const SCEV *SymbolicName = getUnknown(PN);
5327   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5328 
5329   // Using this symbolic name for the PHI, analyze the value coming around
5330   // the back-edge.
5331   const SCEV *BEValue = getSCEV(BEValueV);
5332 
5333   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5334   // has a special value for the first iteration of the loop.
5335 
5336   // If the value coming around the backedge is an add with the symbolic
5337   // value we just inserted, then we found a simple induction variable!
5338   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5339     // If there is a single occurrence of the symbolic value, replace it
5340     // with a recurrence.
5341     unsigned FoundIndex = Add->getNumOperands();
5342     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5343       if (Add->getOperand(i) == SymbolicName)
5344         if (FoundIndex == e) {
5345           FoundIndex = i;
5346           break;
5347         }
5348 
5349     if (FoundIndex != Add->getNumOperands()) {
5350       // Create an add with everything but the specified operand.
5351       SmallVector<const SCEV *, 8> Ops;
5352       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5353         if (i != FoundIndex)
5354           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5355                                                              L, *this));
5356       const SCEV *Accum = getAddExpr(Ops);
5357 
5358       // This is not a valid addrec if the step amount is varying each
5359       // loop iteration, but is not itself an addrec in this loop.
5360       if (isLoopInvariant(Accum, L) ||
5361           (isa<SCEVAddRecExpr>(Accum) &&
5362            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5363         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5364 
5365         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5366           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5367             if (BO->IsNUW)
5368               Flags = setFlags(Flags, SCEV::FlagNUW);
5369             if (BO->IsNSW)
5370               Flags = setFlags(Flags, SCEV::FlagNSW);
5371           }
5372         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5373           // If the increment is an inbounds GEP, then we know the address
5374           // space cannot be wrapped around. We cannot make any guarantee
5375           // about signed or unsigned overflow because pointers are
5376           // unsigned but we may have a negative index from the base
5377           // pointer. We can guarantee that no unsigned wrap occurs if the
5378           // indices form a positive value.
5379           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5380             Flags = setFlags(Flags, SCEV::FlagNW);
5381 
5382             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5383             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5384               Flags = setFlags(Flags, SCEV::FlagNUW);
5385           }
5386 
5387           // We cannot transfer nuw and nsw flags from subtraction
5388           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5389           // for instance.
5390         }
5391 
5392         const SCEV *StartVal = getSCEV(StartValueV);
5393         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5394 
5395         // Okay, for the entire analysis of this edge we assumed the PHI
5396         // to be symbolic.  We now need to go back and purge all of the
5397         // entries for the scalars that use the symbolic expression.
5398         forgetSymbolicName(PN, SymbolicName);
5399         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5400 
5401         // We can add Flags to the post-inc expression only if we
5402         // know that it is *undefined behavior* for BEValueV to
5403         // overflow.
5404         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5405           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5406             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5407 
5408         return PHISCEV;
5409       }
5410     }
5411   } else {
5412     // Otherwise, this could be a loop like this:
5413     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5414     // In this case, j = {1,+,1}  and BEValue is j.
5415     // Because the other in-value of i (0) fits the evolution of BEValue
5416     // i really is an addrec evolution.
5417     //
5418     // We can generalize this saying that i is the shifted value of BEValue
5419     // by one iteration:
5420     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5421     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5422     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5423     if (Shifted != getCouldNotCompute() &&
5424         Start != getCouldNotCompute()) {
5425       const SCEV *StartVal = getSCEV(StartValueV);
5426       if (Start == StartVal) {
5427         // Okay, for the entire analysis of this edge we assumed the PHI
5428         // to be symbolic.  We now need to go back and purge all of the
5429         // entries for the scalars that use the symbolic expression.
5430         forgetSymbolicName(PN, SymbolicName);
5431         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5432         return Shifted;
5433       }
5434     }
5435   }
5436 
5437   // Remove the temporary PHI node SCEV that has been inserted while intending
5438   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5439   // as it will prevent later (possibly simpler) SCEV expressions to be added
5440   // to the ValueExprMap.
5441   eraseValueFromMap(PN);
5442 
5443   return nullptr;
5444 }
5445 
5446 // Checks if the SCEV S is available at BB.  S is considered available at BB
5447 // if S can be materialized at BB without introducing a fault.
5448 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5449                                BasicBlock *BB) {
5450   struct CheckAvailable {
5451     bool TraversalDone = false;
5452     bool Available = true;
5453 
5454     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5455     BasicBlock *BB = nullptr;
5456     DominatorTree &DT;
5457 
5458     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5459       : L(L), BB(BB), DT(DT) {}
5460 
5461     bool setUnavailable() {
5462       TraversalDone = true;
5463       Available = false;
5464       return false;
5465     }
5466 
5467     bool follow(const SCEV *S) {
5468       switch (S->getSCEVType()) {
5469       case scConstant:
5470       case scPtrToInt:
5471       case scTruncate:
5472       case scZeroExtend:
5473       case scSignExtend:
5474       case scAddExpr:
5475       case scMulExpr:
5476       case scUMaxExpr:
5477       case scSMaxExpr:
5478       case scUMinExpr:
5479       case scSMinExpr:
5480         // These expressions are available if their operand(s) is/are.
5481         return true;
5482 
5483       case scAddRecExpr: {
5484         // We allow add recurrences that are on the loop BB is in, or some
5485         // outer loop.  This guarantees availability because the value of the
5486         // add recurrence at BB is simply the "current" value of the induction
5487         // variable.  We can relax this in the future; for instance an add
5488         // recurrence on a sibling dominating loop is also available at BB.
5489         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5490         if (L && (ARLoop == L || ARLoop->contains(L)))
5491           return true;
5492 
5493         return setUnavailable();
5494       }
5495 
5496       case scUnknown: {
5497         // For SCEVUnknown, we check for simple dominance.
5498         const auto *SU = cast<SCEVUnknown>(S);
5499         Value *V = SU->getValue();
5500 
5501         if (isa<Argument>(V))
5502           return false;
5503 
5504         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5505           return false;
5506 
5507         return setUnavailable();
5508       }
5509 
5510       case scUDivExpr:
5511       case scCouldNotCompute:
5512         // We do not try to smart about these at all.
5513         return setUnavailable();
5514       }
5515       llvm_unreachable("Unknown SCEV kind!");
5516     }
5517 
5518     bool isDone() { return TraversalDone; }
5519   };
5520 
5521   CheckAvailable CA(L, BB, DT);
5522   SCEVTraversal<CheckAvailable> ST(CA);
5523 
5524   ST.visitAll(S);
5525   return CA.Available;
5526 }
5527 
5528 // Try to match a control flow sequence that branches out at BI and merges back
5529 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5530 // match.
5531 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5532                           Value *&C, Value *&LHS, Value *&RHS) {
5533   C = BI->getCondition();
5534 
5535   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5536   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5537 
5538   if (!LeftEdge.isSingleEdge())
5539     return false;
5540 
5541   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5542 
5543   Use &LeftUse = Merge->getOperandUse(0);
5544   Use &RightUse = Merge->getOperandUse(1);
5545 
5546   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5547     LHS = LeftUse;
5548     RHS = RightUse;
5549     return true;
5550   }
5551 
5552   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5553     LHS = RightUse;
5554     RHS = LeftUse;
5555     return true;
5556   }
5557 
5558   return false;
5559 }
5560 
5561 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5562   auto IsReachable =
5563       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5564   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5565     const Loop *L = LI.getLoopFor(PN->getParent());
5566 
5567     // We don't want to break LCSSA, even in a SCEV expression tree.
5568     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5569       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5570         return nullptr;
5571 
5572     // Try to match
5573     //
5574     //  br %cond, label %left, label %right
5575     // left:
5576     //  br label %merge
5577     // right:
5578     //  br label %merge
5579     // merge:
5580     //  V = phi [ %x, %left ], [ %y, %right ]
5581     //
5582     // as "select %cond, %x, %y"
5583 
5584     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5585     assert(IDom && "At least the entry block should dominate PN");
5586 
5587     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5588     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5589 
5590     if (BI && BI->isConditional() &&
5591         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5592         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5593         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5594       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5595   }
5596 
5597   return nullptr;
5598 }
5599 
5600 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5601   if (const SCEV *S = createAddRecFromPHI(PN))
5602     return S;
5603 
5604   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5605     return S;
5606 
5607   // If the PHI has a single incoming value, follow that value, unless the
5608   // PHI's incoming blocks are in a different loop, in which case doing so
5609   // risks breaking LCSSA form. Instcombine would normally zap these, but
5610   // it doesn't have DominatorTree information, so it may miss cases.
5611   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5612     if (LI.replacementPreservesLCSSAForm(PN, V))
5613       return getSCEV(V);
5614 
5615   // If it's not a loop phi, we can't handle it yet.
5616   return getUnknown(PN);
5617 }
5618 
5619 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5620                                                       Value *Cond,
5621                                                       Value *TrueVal,
5622                                                       Value *FalseVal) {
5623   // Handle "constant" branch or select. This can occur for instance when a
5624   // loop pass transforms an inner loop and moves on to process the outer loop.
5625   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5626     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5627 
5628   // Try to match some simple smax or umax patterns.
5629   auto *ICI = dyn_cast<ICmpInst>(Cond);
5630   if (!ICI)
5631     return getUnknown(I);
5632 
5633   Value *LHS = ICI->getOperand(0);
5634   Value *RHS = ICI->getOperand(1);
5635 
5636   switch (ICI->getPredicate()) {
5637   case ICmpInst::ICMP_SLT:
5638   case ICmpInst::ICMP_SLE:
5639   case ICmpInst::ICMP_ULT:
5640   case ICmpInst::ICMP_ULE:
5641     std::swap(LHS, RHS);
5642     LLVM_FALLTHROUGH;
5643   case ICmpInst::ICMP_SGT:
5644   case ICmpInst::ICMP_SGE:
5645   case ICmpInst::ICMP_UGT:
5646   case ICmpInst::ICMP_UGE:
5647     // a > b ? a+x : b+x  ->  max(a, b)+x
5648     // a > b ? b+x : a+x  ->  min(a, b)+x
5649     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5650       bool Signed = ICI->isSigned();
5651       const SCEV *LA = getSCEV(TrueVal);
5652       const SCEV *RA = getSCEV(FalseVal);
5653       const SCEV *LS = getSCEV(LHS);
5654       const SCEV *RS = getSCEV(RHS);
5655       if (LA->getType()->isPointerTy()) {
5656         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5657         // Need to make sure we can't produce weird expressions involving
5658         // negated pointers.
5659         if (LA == LS && RA == RS)
5660           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5661         if (LA == RS && RA == LS)
5662           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5663       }
5664       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5665         if (Op->getType()->isPointerTy()) {
5666           Op = getLosslessPtrToIntExpr(Op);
5667           if (isa<SCEVCouldNotCompute>(Op))
5668             return Op;
5669         }
5670         if (Signed)
5671           Op = getNoopOrSignExtend(Op, I->getType());
5672         else
5673           Op = getNoopOrZeroExtend(Op, I->getType());
5674         return Op;
5675       };
5676       LS = CoerceOperand(LS);
5677       RS = CoerceOperand(RS);
5678       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
5679         break;
5680       const SCEV *LDiff = getMinusSCEV(LA, LS);
5681       const SCEV *RDiff = getMinusSCEV(RA, RS);
5682       if (LDiff == RDiff)
5683         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
5684                           LDiff);
5685       LDiff = getMinusSCEV(LA, RS);
5686       RDiff = getMinusSCEV(RA, LS);
5687       if (LDiff == RDiff)
5688         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
5689                           LDiff);
5690     }
5691     break;
5692   case ICmpInst::ICMP_NE:
5693     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5694     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5695         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5696       const SCEV *One = getOne(I->getType());
5697       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5698       const SCEV *LA = getSCEV(TrueVal);
5699       const SCEV *RA = getSCEV(FalseVal);
5700       const SCEV *LDiff = getMinusSCEV(LA, LS);
5701       const SCEV *RDiff = getMinusSCEV(RA, One);
5702       if (LDiff == RDiff)
5703         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5704     }
5705     break;
5706   case ICmpInst::ICMP_EQ:
5707     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5708     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5709         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5710       const SCEV *One = getOne(I->getType());
5711       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5712       const SCEV *LA = getSCEV(TrueVal);
5713       const SCEV *RA = getSCEV(FalseVal);
5714       const SCEV *LDiff = getMinusSCEV(LA, One);
5715       const SCEV *RDiff = getMinusSCEV(RA, LS);
5716       if (LDiff == RDiff)
5717         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5718     }
5719     break;
5720   default:
5721     break;
5722   }
5723 
5724   return getUnknown(I);
5725 }
5726 
5727 /// Expand GEP instructions into add and multiply operations. This allows them
5728 /// to be analyzed by regular SCEV code.
5729 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5730   // Don't attempt to analyze GEPs over unsized objects.
5731   if (!GEP->getSourceElementType()->isSized())
5732     return getUnknown(GEP);
5733 
5734   SmallVector<const SCEV *, 4> IndexExprs;
5735   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5736     IndexExprs.push_back(getSCEV(*Index));
5737   return getGEPExpr(GEP, IndexExprs);
5738 }
5739 
5740 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5741   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5742     return C->getAPInt().countTrailingZeros();
5743 
5744   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5745     return GetMinTrailingZeros(I->getOperand());
5746 
5747   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5748     return std::min(GetMinTrailingZeros(T->getOperand()),
5749                     (uint32_t)getTypeSizeInBits(T->getType()));
5750 
5751   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5752     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5753     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5754                ? getTypeSizeInBits(E->getType())
5755                : OpRes;
5756   }
5757 
5758   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5759     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5760     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5761                ? getTypeSizeInBits(E->getType())
5762                : OpRes;
5763   }
5764 
5765   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5766     // The result is the min of all operands results.
5767     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5768     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5769       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5770     return MinOpRes;
5771   }
5772 
5773   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5774     // The result is the sum of all operands results.
5775     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5776     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5777     for (unsigned i = 1, e = M->getNumOperands();
5778          SumOpRes != BitWidth && i != e; ++i)
5779       SumOpRes =
5780           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5781     return SumOpRes;
5782   }
5783 
5784   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5785     // The result is the min of all operands results.
5786     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5787     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5788       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5789     return MinOpRes;
5790   }
5791 
5792   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5793     // The result is the min of all operands results.
5794     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5795     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5796       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5797     return MinOpRes;
5798   }
5799 
5800   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5801     // The result is the min of all operands results.
5802     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5803     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5804       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5805     return MinOpRes;
5806   }
5807 
5808   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5809     // For a SCEVUnknown, ask ValueTracking.
5810     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5811     return Known.countMinTrailingZeros();
5812   }
5813 
5814   // SCEVUDivExpr
5815   return 0;
5816 }
5817 
5818 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5819   auto I = MinTrailingZerosCache.find(S);
5820   if (I != MinTrailingZerosCache.end())
5821     return I->second;
5822 
5823   uint32_t Result = GetMinTrailingZerosImpl(S);
5824   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5825   assert(InsertPair.second && "Should insert a new key");
5826   return InsertPair.first->second;
5827 }
5828 
5829 /// Helper method to assign a range to V from metadata present in the IR.
5830 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5831   if (Instruction *I = dyn_cast<Instruction>(V))
5832     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5833       return getConstantRangeFromMetadata(*MD);
5834 
5835   return None;
5836 }
5837 
5838 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5839                                      SCEV::NoWrapFlags Flags) {
5840   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5841     AddRec->setNoWrapFlags(Flags);
5842     UnsignedRanges.erase(AddRec);
5843     SignedRanges.erase(AddRec);
5844   }
5845 }
5846 
5847 ConstantRange ScalarEvolution::
5848 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5849   const DataLayout &DL = getDataLayout();
5850 
5851   unsigned BitWidth = getTypeSizeInBits(U->getType());
5852   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
5853 
5854   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5855   // use information about the trip count to improve our available range.  Note
5856   // that the trip count independent cases are already handled by known bits.
5857   // WARNING: The definition of recurrence used here is subtly different than
5858   // the one used by AddRec (and thus most of this file).  Step is allowed to
5859   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5860   // and other addrecs in the same loop (for non-affine addrecs).  The code
5861   // below intentionally handles the case where step is not loop invariant.
5862   auto *P = dyn_cast<PHINode>(U->getValue());
5863   if (!P)
5864     return FullSet;
5865 
5866   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5867   // even the values that are not available in these blocks may come from them,
5868   // and this leads to false-positive recurrence test.
5869   for (auto *Pred : predecessors(P->getParent()))
5870     if (!DT.isReachableFromEntry(Pred))
5871       return FullSet;
5872 
5873   BinaryOperator *BO;
5874   Value *Start, *Step;
5875   if (!matchSimpleRecurrence(P, BO, Start, Step))
5876     return FullSet;
5877 
5878   // If we found a recurrence in reachable code, we must be in a loop. Note
5879   // that BO might be in some subloop of L, and that's completely okay.
5880   auto *L = LI.getLoopFor(P->getParent());
5881   assert(L && L->getHeader() == P->getParent());
5882   if (!L->contains(BO->getParent()))
5883     // NOTE: This bailout should be an assert instead.  However, asserting
5884     // the condition here exposes a case where LoopFusion is querying SCEV
5885     // with malformed loop information during the midst of the transform.
5886     // There doesn't appear to be an obvious fix, so for the moment bailout
5887     // until the caller issue can be fixed.  PR49566 tracks the bug.
5888     return FullSet;
5889 
5890   // TODO: Extend to other opcodes such as mul, and div
5891   switch (BO->getOpcode()) {
5892   default:
5893     return FullSet;
5894   case Instruction::AShr:
5895   case Instruction::LShr:
5896   case Instruction::Shl:
5897     break;
5898   };
5899 
5900   if (BO->getOperand(0) != P)
5901     // TODO: Handle the power function forms some day.
5902     return FullSet;
5903 
5904   unsigned TC = getSmallConstantMaxTripCount(L);
5905   if (!TC || TC >= BitWidth)
5906     return FullSet;
5907 
5908   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5909   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5910   assert(KnownStart.getBitWidth() == BitWidth &&
5911          KnownStep.getBitWidth() == BitWidth);
5912 
5913   // Compute total shift amount, being careful of overflow and bitwidths.
5914   auto MaxShiftAmt = KnownStep.getMaxValue();
5915   APInt TCAP(BitWidth, TC-1);
5916   bool Overflow = false;
5917   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5918   if (Overflow)
5919     return FullSet;
5920 
5921   switch (BO->getOpcode()) {
5922   default:
5923     llvm_unreachable("filtered out above");
5924   case Instruction::AShr: {
5925     // For each ashr, three cases:
5926     //   shift = 0 => unchanged value
5927     //   saturation => 0 or -1
5928     //   other => a value closer to zero (of the same sign)
5929     // Thus, the end value is closer to zero than the start.
5930     auto KnownEnd = KnownBits::ashr(KnownStart,
5931                                     KnownBits::makeConstant(TotalShift));
5932     if (KnownStart.isNonNegative())
5933       // Analogous to lshr (simply not yet canonicalized)
5934       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5935                                         KnownStart.getMaxValue() + 1);
5936     if (KnownStart.isNegative())
5937       // End >=u Start && End <=s Start
5938       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
5939                                         KnownEnd.getMaxValue() + 1);
5940     break;
5941   }
5942   case Instruction::LShr: {
5943     // For each lshr, three cases:
5944     //   shift = 0 => unchanged value
5945     //   saturation => 0
5946     //   other => a smaller positive number
5947     // Thus, the low end of the unsigned range is the last value produced.
5948     auto KnownEnd = KnownBits::lshr(KnownStart,
5949                                     KnownBits::makeConstant(TotalShift));
5950     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5951                                       KnownStart.getMaxValue() + 1);
5952   }
5953   case Instruction::Shl: {
5954     // Iff no bits are shifted out, value increases on every shift.
5955     auto KnownEnd = KnownBits::shl(KnownStart,
5956                                    KnownBits::makeConstant(TotalShift));
5957     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5958       return ConstantRange(KnownStart.getMinValue(),
5959                            KnownEnd.getMaxValue() + 1);
5960     break;
5961   }
5962   };
5963   return FullSet;
5964 }
5965 
5966 /// Determine the range for a particular SCEV.  If SignHint is
5967 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5968 /// with a "cleaner" unsigned (resp. signed) representation.
5969 const ConstantRange &
5970 ScalarEvolution::getRangeRef(const SCEV *S,
5971                              ScalarEvolution::RangeSignHint SignHint) {
5972   DenseMap<const SCEV *, ConstantRange> &Cache =
5973       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5974                                                        : SignedRanges;
5975   ConstantRange::PreferredRangeType RangeType =
5976       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5977           ? ConstantRange::Unsigned : ConstantRange::Signed;
5978 
5979   // See if we've computed this range already.
5980   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5981   if (I != Cache.end())
5982     return I->second;
5983 
5984   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5985     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5986 
5987   unsigned BitWidth = getTypeSizeInBits(S->getType());
5988   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5989   using OBO = OverflowingBinaryOperator;
5990 
5991   // If the value has known zeros, the maximum value will have those known zeros
5992   // as well.
5993   uint32_t TZ = GetMinTrailingZeros(S);
5994   if (TZ != 0) {
5995     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5996       ConservativeResult =
5997           ConstantRange(APInt::getMinValue(BitWidth),
5998                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5999     else
6000       ConservativeResult = ConstantRange(
6001           APInt::getSignedMinValue(BitWidth),
6002           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6003   }
6004 
6005   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6006     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6007     unsigned WrapType = OBO::AnyWrap;
6008     if (Add->hasNoSignedWrap())
6009       WrapType |= OBO::NoSignedWrap;
6010     if (Add->hasNoUnsignedWrap())
6011       WrapType |= OBO::NoUnsignedWrap;
6012     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6013       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6014                           WrapType, RangeType);
6015     return setRange(Add, SignHint,
6016                     ConservativeResult.intersectWith(X, RangeType));
6017   }
6018 
6019   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6020     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6021     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6022       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6023     return setRange(Mul, SignHint,
6024                     ConservativeResult.intersectWith(X, RangeType));
6025   }
6026 
6027   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
6028     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
6029     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
6030       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
6031     return setRange(SMax, SignHint,
6032                     ConservativeResult.intersectWith(X, RangeType));
6033   }
6034 
6035   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
6036     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
6037     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
6038       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
6039     return setRange(UMax, SignHint,
6040                     ConservativeResult.intersectWith(X, RangeType));
6041   }
6042 
6043   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
6044     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
6045     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
6046       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
6047     return setRange(SMin, SignHint,
6048                     ConservativeResult.intersectWith(X, RangeType));
6049   }
6050 
6051   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
6052     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
6053     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
6054       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
6055     return setRange(UMin, SignHint,
6056                     ConservativeResult.intersectWith(X, RangeType));
6057   }
6058 
6059   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6060     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6061     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6062     return setRange(UDiv, SignHint,
6063                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6064   }
6065 
6066   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6067     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6068     return setRange(ZExt, SignHint,
6069                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6070                                                      RangeType));
6071   }
6072 
6073   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6074     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6075     return setRange(SExt, SignHint,
6076                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6077                                                      RangeType));
6078   }
6079 
6080   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6081     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6082     return setRange(PtrToInt, SignHint, X);
6083   }
6084 
6085   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6086     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6087     return setRange(Trunc, SignHint,
6088                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6089                                                      RangeType));
6090   }
6091 
6092   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6093     // If there's no unsigned wrap, the value will never be less than its
6094     // initial value.
6095     if (AddRec->hasNoUnsignedWrap()) {
6096       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6097       if (!UnsignedMinValue.isNullValue())
6098         ConservativeResult = ConservativeResult.intersectWith(
6099             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6100     }
6101 
6102     // If there's no signed wrap, and all the operands except initial value have
6103     // the same sign or zero, the value won't ever be:
6104     // 1: smaller than initial value if operands are non negative,
6105     // 2: bigger than initial value if operands are non positive.
6106     // For both cases, value can not cross signed min/max boundary.
6107     if (AddRec->hasNoSignedWrap()) {
6108       bool AllNonNeg = true;
6109       bool AllNonPos = true;
6110       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6111         if (!isKnownNonNegative(AddRec->getOperand(i)))
6112           AllNonNeg = false;
6113         if (!isKnownNonPositive(AddRec->getOperand(i)))
6114           AllNonPos = false;
6115       }
6116       if (AllNonNeg)
6117         ConservativeResult = ConservativeResult.intersectWith(
6118             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6119                                        APInt::getSignedMinValue(BitWidth)),
6120             RangeType);
6121       else if (AllNonPos)
6122         ConservativeResult = ConservativeResult.intersectWith(
6123             ConstantRange::getNonEmpty(
6124                 APInt::getSignedMinValue(BitWidth),
6125                 getSignedRangeMax(AddRec->getStart()) + 1),
6126             RangeType);
6127     }
6128 
6129     // TODO: non-affine addrec
6130     if (AddRec->isAffine()) {
6131       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6132       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6133           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6134         auto RangeFromAffine = getRangeForAffineAR(
6135             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6136             BitWidth);
6137         ConservativeResult =
6138             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6139 
6140         auto RangeFromFactoring = getRangeViaFactoring(
6141             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6142             BitWidth);
6143         ConservativeResult =
6144             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6145       }
6146 
6147       // Now try symbolic BE count and more powerful methods.
6148       if (UseExpensiveRangeSharpening) {
6149         const SCEV *SymbolicMaxBECount =
6150             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6151         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6152             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6153             AddRec->hasNoSelfWrap()) {
6154           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6155               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6156           ConservativeResult =
6157               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6158         }
6159       }
6160     }
6161 
6162     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6163   }
6164 
6165   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6166 
6167     // Check if the IR explicitly contains !range metadata.
6168     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6169     if (MDRange.hasValue())
6170       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6171                                                             RangeType);
6172 
6173     // Use facts about recurrences in the underlying IR.  Note that add
6174     // recurrences are AddRecExprs and thus don't hit this path.  This
6175     // primarily handles shift recurrences.
6176     auto CR = getRangeForUnknownRecurrence(U);
6177     ConservativeResult = ConservativeResult.intersectWith(CR);
6178 
6179     // See if ValueTracking can give us a useful range.
6180     const DataLayout &DL = getDataLayout();
6181     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6182     if (Known.getBitWidth() != BitWidth)
6183       Known = Known.zextOrTrunc(BitWidth);
6184 
6185     // ValueTracking may be able to compute a tighter result for the number of
6186     // sign bits than for the value of those sign bits.
6187     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6188     if (U->getType()->isPointerTy()) {
6189       // If the pointer size is larger than the index size type, this can cause
6190       // NS to be larger than BitWidth. So compensate for this.
6191       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6192       int ptrIdxDiff = ptrSize - BitWidth;
6193       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6194         NS -= ptrIdxDiff;
6195     }
6196 
6197     if (NS > 1) {
6198       // If we know any of the sign bits, we know all of the sign bits.
6199       if (!Known.Zero.getHiBits(NS).isNullValue())
6200         Known.Zero.setHighBits(NS);
6201       if (!Known.One.getHiBits(NS).isNullValue())
6202         Known.One.setHighBits(NS);
6203     }
6204 
6205     if (Known.getMinValue() != Known.getMaxValue() + 1)
6206       ConservativeResult = ConservativeResult.intersectWith(
6207           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6208           RangeType);
6209     if (NS > 1)
6210       ConservativeResult = ConservativeResult.intersectWith(
6211           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6212                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6213           RangeType);
6214 
6215     // A range of Phi is a subset of union of all ranges of its input.
6216     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6217       // Make sure that we do not run over cycled Phis.
6218       if (PendingPhiRanges.insert(Phi).second) {
6219         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6220         for (auto &Op : Phi->operands()) {
6221           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6222           RangeFromOps = RangeFromOps.unionWith(OpRange);
6223           // No point to continue if we already have a full set.
6224           if (RangeFromOps.isFullSet())
6225             break;
6226         }
6227         ConservativeResult =
6228             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6229         bool Erased = PendingPhiRanges.erase(Phi);
6230         assert(Erased && "Failed to erase Phi properly?");
6231         (void) Erased;
6232       }
6233     }
6234 
6235     return setRange(U, SignHint, std::move(ConservativeResult));
6236   }
6237 
6238   return setRange(S, SignHint, std::move(ConservativeResult));
6239 }
6240 
6241 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6242 // values that the expression can take. Initially, the expression has a value
6243 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6244 // argument defines if we treat Step as signed or unsigned.
6245 static ConstantRange getRangeForAffineARHelper(APInt Step,
6246                                                const ConstantRange &StartRange,
6247                                                const APInt &MaxBECount,
6248                                                unsigned BitWidth, bool Signed) {
6249   // If either Step or MaxBECount is 0, then the expression won't change, and we
6250   // just need to return the initial range.
6251   if (Step == 0 || MaxBECount == 0)
6252     return StartRange;
6253 
6254   // If we don't know anything about the initial value (i.e. StartRange is
6255   // FullRange), then we don't know anything about the final range either.
6256   // Return FullRange.
6257   if (StartRange.isFullSet())
6258     return ConstantRange::getFull(BitWidth);
6259 
6260   // If Step is signed and negative, then we use its absolute value, but we also
6261   // note that we're moving in the opposite direction.
6262   bool Descending = Signed && Step.isNegative();
6263 
6264   if (Signed)
6265     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6266     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6267     // This equations hold true due to the well-defined wrap-around behavior of
6268     // APInt.
6269     Step = Step.abs();
6270 
6271   // Check if Offset is more than full span of BitWidth. If it is, the
6272   // expression is guaranteed to overflow.
6273   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6274     return ConstantRange::getFull(BitWidth);
6275 
6276   // Offset is by how much the expression can change. Checks above guarantee no
6277   // overflow here.
6278   APInt Offset = Step * MaxBECount;
6279 
6280   // Minimum value of the final range will match the minimal value of StartRange
6281   // if the expression is increasing and will be decreased by Offset otherwise.
6282   // Maximum value of the final range will match the maximal value of StartRange
6283   // if the expression is decreasing and will be increased by Offset otherwise.
6284   APInt StartLower = StartRange.getLower();
6285   APInt StartUpper = StartRange.getUpper() - 1;
6286   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6287                                    : (StartUpper + std::move(Offset));
6288 
6289   // It's possible that the new minimum/maximum value will fall into the initial
6290   // range (due to wrap around). This means that the expression can take any
6291   // value in this bitwidth, and we have to return full range.
6292   if (StartRange.contains(MovedBoundary))
6293     return ConstantRange::getFull(BitWidth);
6294 
6295   APInt NewLower =
6296       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6297   APInt NewUpper =
6298       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6299   NewUpper += 1;
6300 
6301   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6302   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6303 }
6304 
6305 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6306                                                    const SCEV *Step,
6307                                                    const SCEV *MaxBECount,
6308                                                    unsigned BitWidth) {
6309   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6310          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6311          "Precondition!");
6312 
6313   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6314   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6315 
6316   // First, consider step signed.
6317   ConstantRange StartSRange = getSignedRange(Start);
6318   ConstantRange StepSRange = getSignedRange(Step);
6319 
6320   // If Step can be both positive and negative, we need to find ranges for the
6321   // maximum absolute step values in both directions and union them.
6322   ConstantRange SR =
6323       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6324                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6325   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6326                                               StartSRange, MaxBECountValue,
6327                                               BitWidth, /* Signed = */ true));
6328 
6329   // Next, consider step unsigned.
6330   ConstantRange UR = getRangeForAffineARHelper(
6331       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6332       MaxBECountValue, BitWidth, /* Signed = */ false);
6333 
6334   // Finally, intersect signed and unsigned ranges.
6335   return SR.intersectWith(UR, ConstantRange::Smallest);
6336 }
6337 
6338 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6339     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6340     ScalarEvolution::RangeSignHint SignHint) {
6341   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6342   assert(AddRec->hasNoSelfWrap() &&
6343          "This only works for non-self-wrapping AddRecs!");
6344   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6345   const SCEV *Step = AddRec->getStepRecurrence(*this);
6346   // Only deal with constant step to save compile time.
6347   if (!isa<SCEVConstant>(Step))
6348     return ConstantRange::getFull(BitWidth);
6349   // Let's make sure that we can prove that we do not self-wrap during
6350   // MaxBECount iterations. We need this because MaxBECount is a maximum
6351   // iteration count estimate, and we might infer nw from some exit for which we
6352   // do not know max exit count (or any other side reasoning).
6353   // TODO: Turn into assert at some point.
6354   if (getTypeSizeInBits(MaxBECount->getType()) >
6355       getTypeSizeInBits(AddRec->getType()))
6356     return ConstantRange::getFull(BitWidth);
6357   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6358   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6359   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6360   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6361   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6362                                          MaxItersWithoutWrap))
6363     return ConstantRange::getFull(BitWidth);
6364 
6365   ICmpInst::Predicate LEPred =
6366       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6367   ICmpInst::Predicate GEPred =
6368       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6369   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6370 
6371   // We know that there is no self-wrap. Let's take Start and End values and
6372   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6373   // the iteration. They either lie inside the range [Min(Start, End),
6374   // Max(Start, End)] or outside it:
6375   //
6376   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6377   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6378   //
6379   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6380   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6381   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6382   // Start <= End and step is positive, or Start >= End and step is negative.
6383   const SCEV *Start = AddRec->getStart();
6384   ConstantRange StartRange = getRangeRef(Start, SignHint);
6385   ConstantRange EndRange = getRangeRef(End, SignHint);
6386   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6387   // If they already cover full iteration space, we will know nothing useful
6388   // even if we prove what we want to prove.
6389   if (RangeBetween.isFullSet())
6390     return RangeBetween;
6391   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6392   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6393                                : RangeBetween.isWrappedSet();
6394   if (IsWrappedSet)
6395     return ConstantRange::getFull(BitWidth);
6396 
6397   if (isKnownPositive(Step) &&
6398       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6399     return RangeBetween;
6400   else if (isKnownNegative(Step) &&
6401            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6402     return RangeBetween;
6403   return ConstantRange::getFull(BitWidth);
6404 }
6405 
6406 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6407                                                     const SCEV *Step,
6408                                                     const SCEV *MaxBECount,
6409                                                     unsigned BitWidth) {
6410   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6411   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6412 
6413   struct SelectPattern {
6414     Value *Condition = nullptr;
6415     APInt TrueValue;
6416     APInt FalseValue;
6417 
6418     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6419                            const SCEV *S) {
6420       Optional<unsigned> CastOp;
6421       APInt Offset(BitWidth, 0);
6422 
6423       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6424              "Should be!");
6425 
6426       // Peel off a constant offset:
6427       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6428         // In the future we could consider being smarter here and handle
6429         // {Start+Step,+,Step} too.
6430         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6431           return;
6432 
6433         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6434         S = SA->getOperand(1);
6435       }
6436 
6437       // Peel off a cast operation
6438       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6439         CastOp = SCast->getSCEVType();
6440         S = SCast->getOperand();
6441       }
6442 
6443       using namespace llvm::PatternMatch;
6444 
6445       auto *SU = dyn_cast<SCEVUnknown>(S);
6446       const APInt *TrueVal, *FalseVal;
6447       if (!SU ||
6448           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6449                                           m_APInt(FalseVal)))) {
6450         Condition = nullptr;
6451         return;
6452       }
6453 
6454       TrueValue = *TrueVal;
6455       FalseValue = *FalseVal;
6456 
6457       // Re-apply the cast we peeled off earlier
6458       if (CastOp.hasValue())
6459         switch (*CastOp) {
6460         default:
6461           llvm_unreachable("Unknown SCEV cast type!");
6462 
6463         case scTruncate:
6464           TrueValue = TrueValue.trunc(BitWidth);
6465           FalseValue = FalseValue.trunc(BitWidth);
6466           break;
6467         case scZeroExtend:
6468           TrueValue = TrueValue.zext(BitWidth);
6469           FalseValue = FalseValue.zext(BitWidth);
6470           break;
6471         case scSignExtend:
6472           TrueValue = TrueValue.sext(BitWidth);
6473           FalseValue = FalseValue.sext(BitWidth);
6474           break;
6475         }
6476 
6477       // Re-apply the constant offset we peeled off earlier
6478       TrueValue += Offset;
6479       FalseValue += Offset;
6480     }
6481 
6482     bool isRecognized() { return Condition != nullptr; }
6483   };
6484 
6485   SelectPattern StartPattern(*this, BitWidth, Start);
6486   if (!StartPattern.isRecognized())
6487     return ConstantRange::getFull(BitWidth);
6488 
6489   SelectPattern StepPattern(*this, BitWidth, Step);
6490   if (!StepPattern.isRecognized())
6491     return ConstantRange::getFull(BitWidth);
6492 
6493   if (StartPattern.Condition != StepPattern.Condition) {
6494     // We don't handle this case today; but we could, by considering four
6495     // possibilities below instead of two. I'm not sure if there are cases where
6496     // that will help over what getRange already does, though.
6497     return ConstantRange::getFull(BitWidth);
6498   }
6499 
6500   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6501   // construct arbitrary general SCEV expressions here.  This function is called
6502   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6503   // say) can end up caching a suboptimal value.
6504 
6505   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6506   // C2352 and C2512 (otherwise it isn't needed).
6507 
6508   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6509   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6510   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6511   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6512 
6513   ConstantRange TrueRange =
6514       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6515   ConstantRange FalseRange =
6516       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6517 
6518   return TrueRange.unionWith(FalseRange);
6519 }
6520 
6521 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6522   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6523   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6524 
6525   // Return early if there are no flags to propagate to the SCEV.
6526   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6527   if (BinOp->hasNoUnsignedWrap())
6528     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6529   if (BinOp->hasNoSignedWrap())
6530     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6531   if (Flags == SCEV::FlagAnyWrap)
6532     return SCEV::FlagAnyWrap;
6533 
6534   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6535 }
6536 
6537 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6538   // Here we check that I is in the header of the innermost loop containing I,
6539   // since we only deal with instructions in the loop header. The actual loop we
6540   // need to check later will come from an add recurrence, but getting that
6541   // requires computing the SCEV of the operands, which can be expensive. This
6542   // check we can do cheaply to rule out some cases early.
6543   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6544   if (InnermostContainingLoop == nullptr ||
6545       InnermostContainingLoop->getHeader() != I->getParent())
6546     return false;
6547 
6548   // Only proceed if we can prove that I does not yield poison.
6549   if (!programUndefinedIfPoison(I))
6550     return false;
6551 
6552   // At this point we know that if I is executed, then it does not wrap
6553   // according to at least one of NSW or NUW. If I is not executed, then we do
6554   // not know if the calculation that I represents would wrap. Multiple
6555   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6556   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6557   // derived from other instructions that map to the same SCEV. We cannot make
6558   // that guarantee for cases where I is not executed. So we need to find the
6559   // loop that I is considered in relation to and prove that I is executed for
6560   // every iteration of that loop. That implies that the value that I
6561   // calculates does not wrap anywhere in the loop, so then we can apply the
6562   // flags to the SCEV.
6563   //
6564   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6565   // from different loops, so that we know which loop to prove that I is
6566   // executed in.
6567   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6568     // I could be an extractvalue from a call to an overflow intrinsic.
6569     // TODO: We can do better here in some cases.
6570     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6571       return false;
6572     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6573     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6574       bool AllOtherOpsLoopInvariant = true;
6575       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6576            ++OtherOpIndex) {
6577         if (OtherOpIndex != OpIndex) {
6578           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6579           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6580             AllOtherOpsLoopInvariant = false;
6581             break;
6582           }
6583         }
6584       }
6585       if (AllOtherOpsLoopInvariant &&
6586           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6587         return true;
6588     }
6589   }
6590   return false;
6591 }
6592 
6593 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6594   // If we know that \c I can never be poison period, then that's enough.
6595   if (isSCEVExprNeverPoison(I))
6596     return true;
6597 
6598   // For an add recurrence specifically, we assume that infinite loops without
6599   // side effects are undefined behavior, and then reason as follows:
6600   //
6601   // If the add recurrence is poison in any iteration, it is poison on all
6602   // future iterations (since incrementing poison yields poison). If the result
6603   // of the add recurrence is fed into the loop latch condition and the loop
6604   // does not contain any throws or exiting blocks other than the latch, we now
6605   // have the ability to "choose" whether the backedge is taken or not (by
6606   // choosing a sufficiently evil value for the poison feeding into the branch)
6607   // for every iteration including and after the one in which \p I first became
6608   // poison.  There are two possibilities (let's call the iteration in which \p
6609   // I first became poison as K):
6610   //
6611   //  1. In the set of iterations including and after K, the loop body executes
6612   //     no side effects.  In this case executing the backege an infinte number
6613   //     of times will yield undefined behavior.
6614   //
6615   //  2. In the set of iterations including and after K, the loop body executes
6616   //     at least one side effect.  In this case, that specific instance of side
6617   //     effect is control dependent on poison, which also yields undefined
6618   //     behavior.
6619 
6620   auto *ExitingBB = L->getExitingBlock();
6621   auto *LatchBB = L->getLoopLatch();
6622   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6623     return false;
6624 
6625   SmallPtrSet<const Instruction *, 16> Pushed;
6626   SmallVector<const Instruction *, 8> PoisonStack;
6627 
6628   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6629   // things that are known to be poison under that assumption go on the
6630   // PoisonStack.
6631   Pushed.insert(I);
6632   PoisonStack.push_back(I);
6633 
6634   bool LatchControlDependentOnPoison = false;
6635   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6636     const Instruction *Poison = PoisonStack.pop_back_val();
6637 
6638     for (auto *PoisonUser : Poison->users()) {
6639       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6640         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6641           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6642       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6643         assert(BI->isConditional() && "Only possibility!");
6644         if (BI->getParent() == LatchBB) {
6645           LatchControlDependentOnPoison = true;
6646           break;
6647         }
6648       }
6649     }
6650   }
6651 
6652   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6653 }
6654 
6655 ScalarEvolution::LoopProperties
6656 ScalarEvolution::getLoopProperties(const Loop *L) {
6657   using LoopProperties = ScalarEvolution::LoopProperties;
6658 
6659   auto Itr = LoopPropertiesCache.find(L);
6660   if (Itr == LoopPropertiesCache.end()) {
6661     auto HasSideEffects = [](Instruction *I) {
6662       if (auto *SI = dyn_cast<StoreInst>(I))
6663         return !SI->isSimple();
6664 
6665       return I->mayHaveSideEffects();
6666     };
6667 
6668     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6669                          /*HasNoSideEffects*/ true};
6670 
6671     for (auto *BB : L->getBlocks())
6672       for (auto &I : *BB) {
6673         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6674           LP.HasNoAbnormalExits = false;
6675         if (HasSideEffects(&I))
6676           LP.HasNoSideEffects = false;
6677         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6678           break; // We're already as pessimistic as we can get.
6679       }
6680 
6681     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6682     assert(InsertPair.second && "We just checked!");
6683     Itr = InsertPair.first;
6684   }
6685 
6686   return Itr->second;
6687 }
6688 
6689 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
6690   // A mustprogress loop without side effects must be finite.
6691   // TODO: The check used here is very conservative.  It's only *specific*
6692   // side effects which are well defined in infinite loops.
6693   return isMustProgress(L) && loopHasNoSideEffects(L);
6694 }
6695 
6696 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6697   if (!isSCEVable(V->getType()))
6698     return getUnknown(V);
6699 
6700   if (Instruction *I = dyn_cast<Instruction>(V)) {
6701     // Don't attempt to analyze instructions in blocks that aren't
6702     // reachable. Such instructions don't matter, and they aren't required
6703     // to obey basic rules for definitions dominating uses which this
6704     // analysis depends on.
6705     if (!DT.isReachableFromEntry(I->getParent()))
6706       return getUnknown(UndefValue::get(V->getType()));
6707   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6708     return getConstant(CI);
6709   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6710     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6711   else if (!isa<ConstantExpr>(V))
6712     return getUnknown(V);
6713 
6714   Operator *U = cast<Operator>(V);
6715   if (auto BO = MatchBinaryOp(U, DT)) {
6716     switch (BO->Opcode) {
6717     case Instruction::Add: {
6718       // The simple thing to do would be to just call getSCEV on both operands
6719       // and call getAddExpr with the result. However if we're looking at a
6720       // bunch of things all added together, this can be quite inefficient,
6721       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6722       // Instead, gather up all the operands and make a single getAddExpr call.
6723       // LLVM IR canonical form means we need only traverse the left operands.
6724       SmallVector<const SCEV *, 4> AddOps;
6725       do {
6726         if (BO->Op) {
6727           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6728             AddOps.push_back(OpSCEV);
6729             break;
6730           }
6731 
6732           // If a NUW or NSW flag can be applied to the SCEV for this
6733           // addition, then compute the SCEV for this addition by itself
6734           // with a separate call to getAddExpr. We need to do that
6735           // instead of pushing the operands of the addition onto AddOps,
6736           // since the flags are only known to apply to this particular
6737           // addition - they may not apply to other additions that can be
6738           // formed with operands from AddOps.
6739           const SCEV *RHS = getSCEV(BO->RHS);
6740           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6741           if (Flags != SCEV::FlagAnyWrap) {
6742             const SCEV *LHS = getSCEV(BO->LHS);
6743             if (BO->Opcode == Instruction::Sub)
6744               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6745             else
6746               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6747             break;
6748           }
6749         }
6750 
6751         if (BO->Opcode == Instruction::Sub)
6752           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6753         else
6754           AddOps.push_back(getSCEV(BO->RHS));
6755 
6756         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6757         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6758                        NewBO->Opcode != Instruction::Sub)) {
6759           AddOps.push_back(getSCEV(BO->LHS));
6760           break;
6761         }
6762         BO = NewBO;
6763       } while (true);
6764 
6765       return getAddExpr(AddOps);
6766     }
6767 
6768     case Instruction::Mul: {
6769       SmallVector<const SCEV *, 4> MulOps;
6770       do {
6771         if (BO->Op) {
6772           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6773             MulOps.push_back(OpSCEV);
6774             break;
6775           }
6776 
6777           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6778           if (Flags != SCEV::FlagAnyWrap) {
6779             MulOps.push_back(
6780                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6781             break;
6782           }
6783         }
6784 
6785         MulOps.push_back(getSCEV(BO->RHS));
6786         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6787         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6788           MulOps.push_back(getSCEV(BO->LHS));
6789           break;
6790         }
6791         BO = NewBO;
6792       } while (true);
6793 
6794       return getMulExpr(MulOps);
6795     }
6796     case Instruction::UDiv:
6797       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6798     case Instruction::URem:
6799       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6800     case Instruction::Sub: {
6801       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6802       if (BO->Op)
6803         Flags = getNoWrapFlagsFromUB(BO->Op);
6804       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6805     }
6806     case Instruction::And:
6807       // For an expression like x&255 that merely masks off the high bits,
6808       // use zext(trunc(x)) as the SCEV expression.
6809       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6810         if (CI->isZero())
6811           return getSCEV(BO->RHS);
6812         if (CI->isMinusOne())
6813           return getSCEV(BO->LHS);
6814         const APInt &A = CI->getValue();
6815 
6816         // Instcombine's ShrinkDemandedConstant may strip bits out of
6817         // constants, obscuring what would otherwise be a low-bits mask.
6818         // Use computeKnownBits to compute what ShrinkDemandedConstant
6819         // knew about to reconstruct a low-bits mask value.
6820         unsigned LZ = A.countLeadingZeros();
6821         unsigned TZ = A.countTrailingZeros();
6822         unsigned BitWidth = A.getBitWidth();
6823         KnownBits Known(BitWidth);
6824         computeKnownBits(BO->LHS, Known, getDataLayout(),
6825                          0, &AC, nullptr, &DT);
6826 
6827         APInt EffectiveMask =
6828             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6829         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6830           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6831           const SCEV *LHS = getSCEV(BO->LHS);
6832           const SCEV *ShiftedLHS = nullptr;
6833           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6834             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6835               // For an expression like (x * 8) & 8, simplify the multiply.
6836               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6837               unsigned GCD = std::min(MulZeros, TZ);
6838               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6839               SmallVector<const SCEV*, 4> MulOps;
6840               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6841               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6842               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6843               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6844             }
6845           }
6846           if (!ShiftedLHS)
6847             ShiftedLHS = getUDivExpr(LHS, MulCount);
6848           return getMulExpr(
6849               getZeroExtendExpr(
6850                   getTruncateExpr(ShiftedLHS,
6851                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6852                   BO->LHS->getType()),
6853               MulCount);
6854         }
6855       }
6856       break;
6857 
6858     case Instruction::Or:
6859       // If the RHS of the Or is a constant, we may have something like:
6860       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6861       // optimizations will transparently handle this case.
6862       //
6863       // In order for this transformation to be safe, the LHS must be of the
6864       // form X*(2^n) and the Or constant must be less than 2^n.
6865       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6866         const SCEV *LHS = getSCEV(BO->LHS);
6867         const APInt &CIVal = CI->getValue();
6868         if (GetMinTrailingZeros(LHS) >=
6869             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6870           // Build a plain add SCEV.
6871           return getAddExpr(LHS, getSCEV(CI),
6872                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6873         }
6874       }
6875       break;
6876 
6877     case Instruction::Xor:
6878       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6879         // If the RHS of xor is -1, then this is a not operation.
6880         if (CI->isMinusOne())
6881           return getNotSCEV(getSCEV(BO->LHS));
6882 
6883         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6884         // This is a variant of the check for xor with -1, and it handles
6885         // the case where instcombine has trimmed non-demanded bits out
6886         // of an xor with -1.
6887         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6888           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6889             if (LBO->getOpcode() == Instruction::And &&
6890                 LCI->getValue() == CI->getValue())
6891               if (const SCEVZeroExtendExpr *Z =
6892                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6893                 Type *UTy = BO->LHS->getType();
6894                 const SCEV *Z0 = Z->getOperand();
6895                 Type *Z0Ty = Z0->getType();
6896                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6897 
6898                 // If C is a low-bits mask, the zero extend is serving to
6899                 // mask off the high bits. Complement the operand and
6900                 // re-apply the zext.
6901                 if (CI->getValue().isMask(Z0TySize))
6902                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6903 
6904                 // If C is a single bit, it may be in the sign-bit position
6905                 // before the zero-extend. In this case, represent the xor
6906                 // using an add, which is equivalent, and re-apply the zext.
6907                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6908                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6909                     Trunc.isSignMask())
6910                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6911                                            UTy);
6912               }
6913       }
6914       break;
6915 
6916     case Instruction::Shl:
6917       // Turn shift left of a constant amount into a multiply.
6918       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6919         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6920 
6921         // If the shift count is not less than the bitwidth, the result of
6922         // the shift is undefined. Don't try to analyze it, because the
6923         // resolution chosen here may differ from the resolution chosen in
6924         // other parts of the compiler.
6925         if (SA->getValue().uge(BitWidth))
6926           break;
6927 
6928         // We can safely preserve the nuw flag in all cases. It's also safe to
6929         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6930         // requires special handling. It can be preserved as long as we're not
6931         // left shifting by bitwidth - 1.
6932         auto Flags = SCEV::FlagAnyWrap;
6933         if (BO->Op) {
6934           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6935           if ((MulFlags & SCEV::FlagNSW) &&
6936               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6937             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6938           if (MulFlags & SCEV::FlagNUW)
6939             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6940         }
6941 
6942         Constant *X = ConstantInt::get(
6943             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6944         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6945       }
6946       break;
6947 
6948     case Instruction::AShr: {
6949       // AShr X, C, where C is a constant.
6950       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6951       if (!CI)
6952         break;
6953 
6954       Type *OuterTy = BO->LHS->getType();
6955       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6956       // If the shift count is not less than the bitwidth, the result of
6957       // the shift is undefined. Don't try to analyze it, because the
6958       // resolution chosen here may differ from the resolution chosen in
6959       // other parts of the compiler.
6960       if (CI->getValue().uge(BitWidth))
6961         break;
6962 
6963       if (CI->isZero())
6964         return getSCEV(BO->LHS); // shift by zero --> noop
6965 
6966       uint64_t AShrAmt = CI->getZExtValue();
6967       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6968 
6969       Operator *L = dyn_cast<Operator>(BO->LHS);
6970       if (L && L->getOpcode() == Instruction::Shl) {
6971         // X = Shl A, n
6972         // Y = AShr X, m
6973         // Both n and m are constant.
6974 
6975         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6976         if (L->getOperand(1) == BO->RHS)
6977           // For a two-shift sext-inreg, i.e. n = m,
6978           // use sext(trunc(x)) as the SCEV expression.
6979           return getSignExtendExpr(
6980               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6981 
6982         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6983         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6984           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6985           if (ShlAmt > AShrAmt) {
6986             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6987             // expression. We already checked that ShlAmt < BitWidth, so
6988             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6989             // ShlAmt - AShrAmt < Amt.
6990             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6991                                             ShlAmt - AShrAmt);
6992             return getSignExtendExpr(
6993                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6994                 getConstant(Mul)), OuterTy);
6995           }
6996         }
6997       }
6998       break;
6999     }
7000     }
7001   }
7002 
7003   switch (U->getOpcode()) {
7004   case Instruction::Trunc:
7005     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7006 
7007   case Instruction::ZExt:
7008     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7009 
7010   case Instruction::SExt:
7011     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7012       // The NSW flag of a subtract does not always survive the conversion to
7013       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7014       // more likely to preserve NSW and allow later AddRec optimisations.
7015       //
7016       // NOTE: This is effectively duplicating this logic from getSignExtend:
7017       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7018       // but by that point the NSW information has potentially been lost.
7019       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7020         Type *Ty = U->getType();
7021         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7022         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7023         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7024       }
7025     }
7026     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7027 
7028   case Instruction::BitCast:
7029     // BitCasts are no-op casts so we just eliminate the cast.
7030     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7031       return getSCEV(U->getOperand(0));
7032     break;
7033 
7034   case Instruction::PtrToInt: {
7035     // Pointer to integer cast is straight-forward, so do model it.
7036     const SCEV *Op = getSCEV(U->getOperand(0));
7037     Type *DstIntTy = U->getType();
7038     // But only if effective SCEV (integer) type is wide enough to represent
7039     // all possible pointer values.
7040     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7041     if (isa<SCEVCouldNotCompute>(IntOp))
7042       return getUnknown(V);
7043     return IntOp;
7044   }
7045   case Instruction::IntToPtr:
7046     // Just don't deal with inttoptr casts.
7047     return getUnknown(V);
7048 
7049   case Instruction::SDiv:
7050     // If both operands are non-negative, this is just an udiv.
7051     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7052         isKnownNonNegative(getSCEV(U->getOperand(1))))
7053       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7054     break;
7055 
7056   case Instruction::SRem:
7057     // If both operands are non-negative, this is just an urem.
7058     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7059         isKnownNonNegative(getSCEV(U->getOperand(1))))
7060       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7061     break;
7062 
7063   case Instruction::GetElementPtr:
7064     return createNodeForGEP(cast<GEPOperator>(U));
7065 
7066   case Instruction::PHI:
7067     return createNodeForPHI(cast<PHINode>(U));
7068 
7069   case Instruction::Select:
7070     // U can also be a select constant expr, which let fall through.  Since
7071     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
7072     // constant expressions cannot have instructions as operands, we'd have
7073     // returned getUnknown for a select constant expressions anyway.
7074     if (isa<Instruction>(U))
7075       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
7076                                       U->getOperand(1), U->getOperand(2));
7077     break;
7078 
7079   case Instruction::Call:
7080   case Instruction::Invoke:
7081     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7082       return getSCEV(RV);
7083 
7084     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7085       switch (II->getIntrinsicID()) {
7086       case Intrinsic::abs:
7087         return getAbsExpr(
7088             getSCEV(II->getArgOperand(0)),
7089             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7090       case Intrinsic::umax:
7091         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7092                            getSCEV(II->getArgOperand(1)));
7093       case Intrinsic::umin:
7094         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7095                            getSCEV(II->getArgOperand(1)));
7096       case Intrinsic::smax:
7097         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7098                            getSCEV(II->getArgOperand(1)));
7099       case Intrinsic::smin:
7100         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7101                            getSCEV(II->getArgOperand(1)));
7102       case Intrinsic::usub_sat: {
7103         const SCEV *X = getSCEV(II->getArgOperand(0));
7104         const SCEV *Y = getSCEV(II->getArgOperand(1));
7105         const SCEV *ClampedY = getUMinExpr(X, Y);
7106         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7107       }
7108       case Intrinsic::uadd_sat: {
7109         const SCEV *X = getSCEV(II->getArgOperand(0));
7110         const SCEV *Y = getSCEV(II->getArgOperand(1));
7111         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7112         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7113       }
7114       case Intrinsic::start_loop_iterations:
7115         // A start_loop_iterations is just equivalent to the first operand for
7116         // SCEV purposes.
7117         return getSCEV(II->getArgOperand(0));
7118       default:
7119         break;
7120       }
7121     }
7122     break;
7123   }
7124 
7125   return getUnknown(V);
7126 }
7127 
7128 //===----------------------------------------------------------------------===//
7129 //                   Iteration Count Computation Code
7130 //
7131 
7132 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
7133   // Get the trip count from the BE count by adding 1.  Overflow, results
7134   // in zero which means "unknown".
7135   return getAddExpr(ExitCount, getOne(ExitCount->getType()));
7136 }
7137 
7138 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7139   if (!ExitCount)
7140     return 0;
7141 
7142   ConstantInt *ExitConst = ExitCount->getValue();
7143 
7144   // Guard against huge trip counts.
7145   if (ExitConst->getValue().getActiveBits() > 32)
7146     return 0;
7147 
7148   // In case of integer overflow, this returns 0, which is correct.
7149   return ((unsigned)ExitConst->getZExtValue()) + 1;
7150 }
7151 
7152 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7153   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7154   return getConstantTripCount(ExitCount);
7155 }
7156 
7157 unsigned
7158 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7159                                            const BasicBlock *ExitingBlock) {
7160   assert(ExitingBlock && "Must pass a non-null exiting block!");
7161   assert(L->isLoopExiting(ExitingBlock) &&
7162          "Exiting block must actually branch out of the loop!");
7163   const SCEVConstant *ExitCount =
7164       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7165   return getConstantTripCount(ExitCount);
7166 }
7167 
7168 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7169   const auto *MaxExitCount =
7170       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7171   return getConstantTripCount(MaxExitCount);
7172 }
7173 
7174 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7175   SmallVector<BasicBlock *, 8> ExitingBlocks;
7176   L->getExitingBlocks(ExitingBlocks);
7177 
7178   Optional<unsigned> Res = None;
7179   for (auto *ExitingBB : ExitingBlocks) {
7180     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7181     if (!Res)
7182       Res = Multiple;
7183     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7184   }
7185   return Res.getValueOr(1);
7186 }
7187 
7188 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7189                                                        const SCEV *ExitCount) {
7190   if (ExitCount == getCouldNotCompute())
7191     return 1;
7192 
7193   // Get the trip count
7194   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7195 
7196   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7197   if (!TC)
7198     // Attempt to factor more general cases. Returns the greatest power of
7199     // two divisor. If overflow happens, the trip count expression is still
7200     // divisible by the greatest power of 2 divisor returned.
7201     return 1U << std::min((uint32_t)31,
7202                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7203 
7204   ConstantInt *Result = TC->getValue();
7205 
7206   // Guard against huge trip counts (this requires checking
7207   // for zero to handle the case where the trip count == -1 and the
7208   // addition wraps).
7209   if (!Result || Result->getValue().getActiveBits() > 32 ||
7210       Result->getValue().getActiveBits() == 0)
7211     return 1;
7212 
7213   return (unsigned)Result->getZExtValue();
7214 }
7215 
7216 /// Returns the largest constant divisor of the trip count of this loop as a
7217 /// normal unsigned value, if possible. This means that the actual trip count is
7218 /// always a multiple of the returned value (don't forget the trip count could
7219 /// very well be zero as well!).
7220 ///
7221 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7222 /// multiple of a constant (which is also the case if the trip count is simply
7223 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7224 /// if the trip count is very large (>= 2^32).
7225 ///
7226 /// As explained in the comments for getSmallConstantTripCount, this assumes
7227 /// that control exits the loop via ExitingBlock.
7228 unsigned
7229 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7230                                               const BasicBlock *ExitingBlock) {
7231   assert(ExitingBlock && "Must pass a non-null exiting block!");
7232   assert(L->isLoopExiting(ExitingBlock) &&
7233          "Exiting block must actually branch out of the loop!");
7234   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7235   return getSmallConstantTripMultiple(L, ExitCount);
7236 }
7237 
7238 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7239                                           const BasicBlock *ExitingBlock,
7240                                           ExitCountKind Kind) {
7241   switch (Kind) {
7242   case Exact:
7243   case SymbolicMaximum:
7244     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7245   case ConstantMaximum:
7246     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7247   };
7248   llvm_unreachable("Invalid ExitCountKind!");
7249 }
7250 
7251 const SCEV *
7252 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7253                                                  SCEVUnionPredicate &Preds) {
7254   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7255 }
7256 
7257 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7258                                                    ExitCountKind Kind) {
7259   switch (Kind) {
7260   case Exact:
7261     return getBackedgeTakenInfo(L).getExact(L, this);
7262   case ConstantMaximum:
7263     return getBackedgeTakenInfo(L).getConstantMax(this);
7264   case SymbolicMaximum:
7265     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7266   };
7267   llvm_unreachable("Invalid ExitCountKind!");
7268 }
7269 
7270 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7271   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7272 }
7273 
7274 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7275 static void
7276 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
7277   BasicBlock *Header = L->getHeader();
7278 
7279   // Push all Loop-header PHIs onto the Worklist stack.
7280   for (PHINode &PN : Header->phis())
7281     Worklist.push_back(&PN);
7282 }
7283 
7284 const ScalarEvolution::BackedgeTakenInfo &
7285 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7286   auto &BTI = getBackedgeTakenInfo(L);
7287   if (BTI.hasFullInfo())
7288     return BTI;
7289 
7290   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7291 
7292   if (!Pair.second)
7293     return Pair.first->second;
7294 
7295   BackedgeTakenInfo Result =
7296       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7297 
7298   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7299 }
7300 
7301 ScalarEvolution::BackedgeTakenInfo &
7302 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7303   // Initially insert an invalid entry for this loop. If the insertion
7304   // succeeds, proceed to actually compute a backedge-taken count and
7305   // update the value. The temporary CouldNotCompute value tells SCEV
7306   // code elsewhere that it shouldn't attempt to request a new
7307   // backedge-taken count, which could result in infinite recursion.
7308   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7309       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7310   if (!Pair.second)
7311     return Pair.first->second;
7312 
7313   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7314   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7315   // must be cleared in this scope.
7316   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7317 
7318   // In product build, there are no usage of statistic.
7319   (void)NumTripCountsComputed;
7320   (void)NumTripCountsNotComputed;
7321 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7322   const SCEV *BEExact = Result.getExact(L, this);
7323   if (BEExact != getCouldNotCompute()) {
7324     assert(isLoopInvariant(BEExact, L) &&
7325            isLoopInvariant(Result.getConstantMax(this), L) &&
7326            "Computed backedge-taken count isn't loop invariant for loop!");
7327     ++NumTripCountsComputed;
7328   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7329              isa<PHINode>(L->getHeader()->begin())) {
7330     // Only count loops that have phi nodes as not being computable.
7331     ++NumTripCountsNotComputed;
7332   }
7333 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7334 
7335   // Now that we know more about the trip count for this loop, forget any
7336   // existing SCEV values for PHI nodes in this loop since they are only
7337   // conservative estimates made without the benefit of trip count
7338   // information. This is similar to the code in forgetLoop, except that
7339   // it handles SCEVUnknown PHI nodes specially.
7340   if (Result.hasAnyInfo()) {
7341     SmallVector<Instruction *, 16> Worklist;
7342     PushLoopPHIs(L, Worklist);
7343 
7344     SmallPtrSet<Instruction *, 8> Discovered;
7345     while (!Worklist.empty()) {
7346       Instruction *I = Worklist.pop_back_val();
7347 
7348       ValueExprMapType::iterator It =
7349         ValueExprMap.find_as(static_cast<Value *>(I));
7350       if (It != ValueExprMap.end()) {
7351         const SCEV *Old = It->second;
7352 
7353         // SCEVUnknown for a PHI either means that it has an unrecognized
7354         // structure, or it's a PHI that's in the progress of being computed
7355         // by createNodeForPHI.  In the former case, additional loop trip
7356         // count information isn't going to change anything. In the later
7357         // case, createNodeForPHI will perform the necessary updates on its
7358         // own when it gets to that point.
7359         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7360           eraseValueFromMap(It->first);
7361           forgetMemoizedResults(Old);
7362         }
7363         if (PHINode *PN = dyn_cast<PHINode>(I))
7364           ConstantEvolutionLoopExitValue.erase(PN);
7365       }
7366 
7367       // Since we don't need to invalidate anything for correctness and we're
7368       // only invalidating to make SCEV's results more precise, we get to stop
7369       // early to avoid invalidating too much.  This is especially important in
7370       // cases like:
7371       //
7372       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7373       // loop0:
7374       //   %pn0 = phi
7375       //   ...
7376       // loop1:
7377       //   %pn1 = phi
7378       //   ...
7379       //
7380       // where both loop0 and loop1's backedge taken count uses the SCEV
7381       // expression for %v.  If we don't have the early stop below then in cases
7382       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7383       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7384       // count for loop1, effectively nullifying SCEV's trip count cache.
7385       for (auto *U : I->users())
7386         if (auto *I = dyn_cast<Instruction>(U)) {
7387           auto *LoopForUser = LI.getLoopFor(I->getParent());
7388           if (LoopForUser && L->contains(LoopForUser) &&
7389               Discovered.insert(I).second)
7390             Worklist.push_back(I);
7391         }
7392     }
7393   }
7394 
7395   // Re-lookup the insert position, since the call to
7396   // computeBackedgeTakenCount above could result in a
7397   // recusive call to getBackedgeTakenInfo (on a different
7398   // loop), which would invalidate the iterator computed
7399   // earlier.
7400   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7401 }
7402 
7403 void ScalarEvolution::forgetAllLoops() {
7404   // This method is intended to forget all info about loops. It should
7405   // invalidate caches as if the following happened:
7406   // - The trip counts of all loops have changed arbitrarily
7407   // - Every llvm::Value has been updated in place to produce a different
7408   // result.
7409   BackedgeTakenCounts.clear();
7410   PredicatedBackedgeTakenCounts.clear();
7411   LoopPropertiesCache.clear();
7412   ConstantEvolutionLoopExitValue.clear();
7413   ValueExprMap.clear();
7414   ValuesAtScopes.clear();
7415   LoopDispositions.clear();
7416   BlockDispositions.clear();
7417   UnsignedRanges.clear();
7418   SignedRanges.clear();
7419   ExprValueMap.clear();
7420   HasRecMap.clear();
7421   MinTrailingZerosCache.clear();
7422   PredicatedSCEVRewrites.clear();
7423 }
7424 
7425 void ScalarEvolution::forgetLoop(const Loop *L) {
7426   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7427   SmallVector<Instruction *, 32> Worklist;
7428   SmallPtrSet<Instruction *, 16> Visited;
7429 
7430   // Iterate over all the loops and sub-loops to drop SCEV information.
7431   while (!LoopWorklist.empty()) {
7432     auto *CurrL = LoopWorklist.pop_back_val();
7433 
7434     // Drop any stored trip count value.
7435     BackedgeTakenCounts.erase(CurrL);
7436     PredicatedBackedgeTakenCounts.erase(CurrL);
7437 
7438     // Drop information about predicated SCEV rewrites for this loop.
7439     for (auto I = PredicatedSCEVRewrites.begin();
7440          I != PredicatedSCEVRewrites.end();) {
7441       std::pair<const SCEV *, const Loop *> Entry = I->first;
7442       if (Entry.second == CurrL)
7443         PredicatedSCEVRewrites.erase(I++);
7444       else
7445         ++I;
7446     }
7447 
7448     auto LoopUsersItr = LoopUsers.find(CurrL);
7449     if (LoopUsersItr != LoopUsers.end()) {
7450       for (auto *S : LoopUsersItr->second)
7451         forgetMemoizedResults(S);
7452       LoopUsers.erase(LoopUsersItr);
7453     }
7454 
7455     // Drop information about expressions based on loop-header PHIs.
7456     PushLoopPHIs(CurrL, Worklist);
7457 
7458     while (!Worklist.empty()) {
7459       Instruction *I = Worklist.pop_back_val();
7460       if (!Visited.insert(I).second)
7461         continue;
7462 
7463       ValueExprMapType::iterator It =
7464           ValueExprMap.find_as(static_cast<Value *>(I));
7465       if (It != ValueExprMap.end()) {
7466         eraseValueFromMap(It->first);
7467         forgetMemoizedResults(It->second);
7468         if (PHINode *PN = dyn_cast<PHINode>(I))
7469           ConstantEvolutionLoopExitValue.erase(PN);
7470       }
7471 
7472       PushDefUseChildren(I, Worklist);
7473     }
7474 
7475     LoopPropertiesCache.erase(CurrL);
7476     // Forget all contained loops too, to avoid dangling entries in the
7477     // ValuesAtScopes map.
7478     LoopWorklist.append(CurrL->begin(), CurrL->end());
7479   }
7480 }
7481 
7482 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7483   while (Loop *Parent = L->getParentLoop())
7484     L = Parent;
7485   forgetLoop(L);
7486 }
7487 
7488 void ScalarEvolution::forgetValue(Value *V) {
7489   Instruction *I = dyn_cast<Instruction>(V);
7490   if (!I) return;
7491 
7492   // Drop information about expressions based on loop-header PHIs.
7493   SmallVector<Instruction *, 16> Worklist;
7494   Worklist.push_back(I);
7495 
7496   SmallPtrSet<Instruction *, 8> Visited;
7497   while (!Worklist.empty()) {
7498     I = Worklist.pop_back_val();
7499     if (!Visited.insert(I).second)
7500       continue;
7501 
7502     ValueExprMapType::iterator It =
7503       ValueExprMap.find_as(static_cast<Value *>(I));
7504     if (It != ValueExprMap.end()) {
7505       eraseValueFromMap(It->first);
7506       forgetMemoizedResults(It->second);
7507       if (PHINode *PN = dyn_cast<PHINode>(I))
7508         ConstantEvolutionLoopExitValue.erase(PN);
7509     }
7510 
7511     PushDefUseChildren(I, Worklist);
7512   }
7513 }
7514 
7515 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7516   LoopDispositions.clear();
7517 }
7518 
7519 /// Get the exact loop backedge taken count considering all loop exits. A
7520 /// computable result can only be returned for loops with all exiting blocks
7521 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7522 /// is never skipped. This is a valid assumption as long as the loop exits via
7523 /// that test. For precise results, it is the caller's responsibility to specify
7524 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7525 const SCEV *
7526 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7527                                              SCEVUnionPredicate *Preds) const {
7528   // If any exits were not computable, the loop is not computable.
7529   if (!isComplete() || ExitNotTaken.empty())
7530     return SE->getCouldNotCompute();
7531 
7532   const BasicBlock *Latch = L->getLoopLatch();
7533   // All exiting blocks we have collected must dominate the only backedge.
7534   if (!Latch)
7535     return SE->getCouldNotCompute();
7536 
7537   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7538   // count is simply a minimum out of all these calculated exit counts.
7539   SmallVector<const SCEV *, 2> Ops;
7540   for (auto &ENT : ExitNotTaken) {
7541     const SCEV *BECount = ENT.ExactNotTaken;
7542     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7543     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7544            "We should only have known counts for exiting blocks that dominate "
7545            "latch!");
7546 
7547     Ops.push_back(BECount);
7548 
7549     if (Preds && !ENT.hasAlwaysTruePredicate())
7550       Preds->add(ENT.Predicate.get());
7551 
7552     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7553            "Predicate should be always true!");
7554   }
7555 
7556   return SE->getUMinFromMismatchedTypes(Ops);
7557 }
7558 
7559 /// Get the exact not taken count for this loop exit.
7560 const SCEV *
7561 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7562                                              ScalarEvolution *SE) const {
7563   for (auto &ENT : ExitNotTaken)
7564     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7565       return ENT.ExactNotTaken;
7566 
7567   return SE->getCouldNotCompute();
7568 }
7569 
7570 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7571     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7572   for (auto &ENT : ExitNotTaken)
7573     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7574       return ENT.MaxNotTaken;
7575 
7576   return SE->getCouldNotCompute();
7577 }
7578 
7579 /// getConstantMax - Get the constant max backedge taken count for the loop.
7580 const SCEV *
7581 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7582   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7583     return !ENT.hasAlwaysTruePredicate();
7584   };
7585 
7586   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7587     return SE->getCouldNotCompute();
7588 
7589   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7590           isa<SCEVConstant>(getConstantMax())) &&
7591          "No point in having a non-constant max backedge taken count!");
7592   return getConstantMax();
7593 }
7594 
7595 const SCEV *
7596 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7597                                                    ScalarEvolution *SE) {
7598   if (!SymbolicMax)
7599     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7600   return SymbolicMax;
7601 }
7602 
7603 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7604     ScalarEvolution *SE) const {
7605   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7606     return !ENT.hasAlwaysTruePredicate();
7607   };
7608   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7609 }
7610 
7611 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const {
7612   return Operands.contains(S);
7613 }
7614 
7615 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7616     : ExitLimit(E, E, false, None) {
7617 }
7618 
7619 ScalarEvolution::ExitLimit::ExitLimit(
7620     const SCEV *E, const SCEV *M, bool MaxOrZero,
7621     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7622     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7623   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7624           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7625          "Exact is not allowed to be less precise than Max");
7626   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7627           isa<SCEVConstant>(MaxNotTaken)) &&
7628          "No point in having a non-constant max backedge taken count!");
7629   for (auto *PredSet : PredSetList)
7630     for (auto *P : *PredSet)
7631       addPredicate(P);
7632   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
7633          "Backedge count should be int");
7634   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
7635          "Max backedge count should be int");
7636 }
7637 
7638 ScalarEvolution::ExitLimit::ExitLimit(
7639     const SCEV *E, const SCEV *M, bool MaxOrZero,
7640     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7641     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7642 }
7643 
7644 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7645                                       bool MaxOrZero)
7646     : ExitLimit(E, M, MaxOrZero, None) {
7647 }
7648 
7649 class SCEVRecordOperands {
7650   SmallPtrSetImpl<const SCEV *> &Operands;
7651 
7652 public:
7653   SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands)
7654     : Operands(Operands) {}
7655   bool follow(const SCEV *S) {
7656     Operands.insert(S);
7657     return true;
7658   }
7659   bool isDone() { return false; }
7660 };
7661 
7662 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7663 /// computable exit into a persistent ExitNotTakenInfo array.
7664 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7665     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7666     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7667     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7668   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7669 
7670   ExitNotTaken.reserve(ExitCounts.size());
7671   std::transform(
7672       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7673       [&](const EdgeExitInfo &EEI) {
7674         BasicBlock *ExitBB = EEI.first;
7675         const ExitLimit &EL = EEI.second;
7676         if (EL.Predicates.empty())
7677           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7678                                   nullptr);
7679 
7680         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7681         for (auto *Pred : EL.Predicates)
7682           Predicate->add(Pred);
7683 
7684         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7685                                 std::move(Predicate));
7686       });
7687   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7688           isa<SCEVConstant>(ConstantMax)) &&
7689          "No point in having a non-constant max backedge taken count!");
7690 
7691   SCEVRecordOperands RecordOperands(Operands);
7692   SCEVTraversal<SCEVRecordOperands> ST(RecordOperands);
7693   if (!isa<SCEVCouldNotCompute>(ConstantMax))
7694     ST.visitAll(ConstantMax);
7695   for (auto &ENT : ExitNotTaken)
7696     if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken))
7697       ST.visitAll(ENT.ExactNotTaken);
7698 }
7699 
7700 /// Compute the number of times the backedge of the specified loop will execute.
7701 ScalarEvolution::BackedgeTakenInfo
7702 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7703                                            bool AllowPredicates) {
7704   SmallVector<BasicBlock *, 8> ExitingBlocks;
7705   L->getExitingBlocks(ExitingBlocks);
7706 
7707   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7708 
7709   SmallVector<EdgeExitInfo, 4> ExitCounts;
7710   bool CouldComputeBECount = true;
7711   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7712   const SCEV *MustExitMaxBECount = nullptr;
7713   const SCEV *MayExitMaxBECount = nullptr;
7714   bool MustExitMaxOrZero = false;
7715 
7716   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7717   // and compute maxBECount.
7718   // Do a union of all the predicates here.
7719   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7720     BasicBlock *ExitBB = ExitingBlocks[i];
7721 
7722     // We canonicalize untaken exits to br (constant), ignore them so that
7723     // proving an exit untaken doesn't negatively impact our ability to reason
7724     // about the loop as whole.
7725     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7726       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7727         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7728         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7729           continue;
7730       }
7731 
7732     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7733 
7734     assert((AllowPredicates || EL.Predicates.empty()) &&
7735            "Predicated exit limit when predicates are not allowed!");
7736 
7737     // 1. For each exit that can be computed, add an entry to ExitCounts.
7738     // CouldComputeBECount is true only if all exits can be computed.
7739     if (EL.ExactNotTaken == getCouldNotCompute())
7740       // We couldn't compute an exact value for this exit, so
7741       // we won't be able to compute an exact value for the loop.
7742       CouldComputeBECount = false;
7743     else
7744       ExitCounts.emplace_back(ExitBB, EL);
7745 
7746     // 2. Derive the loop's MaxBECount from each exit's max number of
7747     // non-exiting iterations. Partition the loop exits into two kinds:
7748     // LoopMustExits and LoopMayExits.
7749     //
7750     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7751     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7752     // MaxBECount is the minimum EL.MaxNotTaken of computable
7753     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7754     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7755     // computable EL.MaxNotTaken.
7756     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7757         DT.dominates(ExitBB, Latch)) {
7758       if (!MustExitMaxBECount) {
7759         MustExitMaxBECount = EL.MaxNotTaken;
7760         MustExitMaxOrZero = EL.MaxOrZero;
7761       } else {
7762         MustExitMaxBECount =
7763             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7764       }
7765     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7766       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7767         MayExitMaxBECount = EL.MaxNotTaken;
7768       else {
7769         MayExitMaxBECount =
7770             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7771       }
7772     }
7773   }
7774   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7775     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7776   // The loop backedge will be taken the maximum or zero times if there's
7777   // a single exit that must be taken the maximum or zero times.
7778   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7779   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7780                            MaxBECount, MaxOrZero);
7781 }
7782 
7783 ScalarEvolution::ExitLimit
7784 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7785                                       bool AllowPredicates) {
7786   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7787   // If our exiting block does not dominate the latch, then its connection with
7788   // loop's exit limit may be far from trivial.
7789   const BasicBlock *Latch = L->getLoopLatch();
7790   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7791     return getCouldNotCompute();
7792 
7793   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7794   Instruction *Term = ExitingBlock->getTerminator();
7795   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7796     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7797     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7798     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7799            "It should have one successor in loop and one exit block!");
7800     // Proceed to the next level to examine the exit condition expression.
7801     return computeExitLimitFromCond(
7802         L, BI->getCondition(), ExitIfTrue,
7803         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7804   }
7805 
7806   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7807     // For switch, make sure that there is a single exit from the loop.
7808     BasicBlock *Exit = nullptr;
7809     for (auto *SBB : successors(ExitingBlock))
7810       if (!L->contains(SBB)) {
7811         if (Exit) // Multiple exit successors.
7812           return getCouldNotCompute();
7813         Exit = SBB;
7814       }
7815     assert(Exit && "Exiting block must have at least one exit");
7816     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7817                                                 /*ControlsExit=*/IsOnlyExit);
7818   }
7819 
7820   return getCouldNotCompute();
7821 }
7822 
7823 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7824     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7825     bool ControlsExit, bool AllowPredicates) {
7826   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7827   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7828                                         ControlsExit, AllowPredicates);
7829 }
7830 
7831 Optional<ScalarEvolution::ExitLimit>
7832 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7833                                       bool ExitIfTrue, bool ControlsExit,
7834                                       bool AllowPredicates) {
7835   (void)this->L;
7836   (void)this->ExitIfTrue;
7837   (void)this->AllowPredicates;
7838 
7839   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7840          this->AllowPredicates == AllowPredicates &&
7841          "Variance in assumed invariant key components!");
7842   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7843   if (Itr == TripCountMap.end())
7844     return None;
7845   return Itr->second;
7846 }
7847 
7848 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7849                                              bool ExitIfTrue,
7850                                              bool ControlsExit,
7851                                              bool AllowPredicates,
7852                                              const ExitLimit &EL) {
7853   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7854          this->AllowPredicates == AllowPredicates &&
7855          "Variance in assumed invariant key components!");
7856 
7857   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7858   assert(InsertResult.second && "Expected successful insertion!");
7859   (void)InsertResult;
7860   (void)ExitIfTrue;
7861 }
7862 
7863 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7864     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7865     bool ControlsExit, bool AllowPredicates) {
7866 
7867   if (auto MaybeEL =
7868           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7869     return *MaybeEL;
7870 
7871   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7872                                               ControlsExit, AllowPredicates);
7873   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7874   return EL;
7875 }
7876 
7877 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7878     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7879     bool ControlsExit, bool AllowPredicates) {
7880   // Handle BinOp conditions (And, Or).
7881   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7882           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7883     return *LimitFromBinOp;
7884 
7885   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7886   // Proceed to the next level to examine the icmp.
7887   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7888     ExitLimit EL =
7889         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7890     if (EL.hasFullInfo() || !AllowPredicates)
7891       return EL;
7892 
7893     // Try again, but use SCEV predicates this time.
7894     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7895                                     /*AllowPredicates=*/true);
7896   }
7897 
7898   // Check for a constant condition. These are normally stripped out by
7899   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7900   // preserve the CFG and is temporarily leaving constant conditions
7901   // in place.
7902   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7903     if (ExitIfTrue == !CI->getZExtValue())
7904       // The backedge is always taken.
7905       return getCouldNotCompute();
7906     else
7907       // The backedge is never taken.
7908       return getZero(CI->getType());
7909   }
7910 
7911   // If it's not an integer or pointer comparison then compute it the hard way.
7912   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7913 }
7914 
7915 Optional<ScalarEvolution::ExitLimit>
7916 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7917     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7918     bool ControlsExit, bool AllowPredicates) {
7919   // Check if the controlling expression for this loop is an And or Or.
7920   Value *Op0, *Op1;
7921   bool IsAnd = false;
7922   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7923     IsAnd = true;
7924   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7925     IsAnd = false;
7926   else
7927     return None;
7928 
7929   // EitherMayExit is true in these two cases:
7930   //   br (and Op0 Op1), loop, exit
7931   //   br (or  Op0 Op1), exit, loop
7932   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7933   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7934                                                  ControlsExit && !EitherMayExit,
7935                                                  AllowPredicates);
7936   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7937                                                  ControlsExit && !EitherMayExit,
7938                                                  AllowPredicates);
7939 
7940   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7941   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7942   if (isa<ConstantInt>(Op1))
7943     return Op1 == NeutralElement ? EL0 : EL1;
7944   if (isa<ConstantInt>(Op0))
7945     return Op0 == NeutralElement ? EL1 : EL0;
7946 
7947   const SCEV *BECount = getCouldNotCompute();
7948   const SCEV *MaxBECount = getCouldNotCompute();
7949   if (EitherMayExit) {
7950     // Both conditions must be same for the loop to continue executing.
7951     // Choose the less conservative count.
7952     // If ExitCond is a short-circuit form (select), using
7953     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7954     // To see the detailed examples, please see
7955     // test/Analysis/ScalarEvolution/exit-count-select.ll
7956     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7957     if (!PoisonSafe)
7958       // Even if ExitCond is select, we can safely derive BECount using both
7959       // EL0 and EL1 in these cases:
7960       // (1) EL0.ExactNotTaken is non-zero
7961       // (2) EL1.ExactNotTaken is non-poison
7962       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7963       //     it cannot be umin(0, ..))
7964       // The PoisonSafe assignment below is simplified and the assertion after
7965       // BECount calculation fully guarantees the condition (3).
7966       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7967                    isa<SCEVConstant>(EL1.ExactNotTaken);
7968     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7969         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7970       BECount =
7971           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7972 
7973       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7974       // it should have been simplified to zero (see the condition (3) above)
7975       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7976              BECount->isZero());
7977     }
7978     if (EL0.MaxNotTaken == getCouldNotCompute())
7979       MaxBECount = EL1.MaxNotTaken;
7980     else if (EL1.MaxNotTaken == getCouldNotCompute())
7981       MaxBECount = EL0.MaxNotTaken;
7982     else
7983       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7984   } else {
7985     // Both conditions must be same at the same time for the loop to exit.
7986     // For now, be conservative.
7987     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7988       BECount = EL0.ExactNotTaken;
7989   }
7990 
7991   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7992   // to be more aggressive when computing BECount than when computing
7993   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7994   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7995   // to not.
7996   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7997       !isa<SCEVCouldNotCompute>(BECount))
7998     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7999 
8000   return ExitLimit(BECount, MaxBECount, false,
8001                    { &EL0.Predicates, &EL1.Predicates });
8002 }
8003 
8004 ScalarEvolution::ExitLimit
8005 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8006                                           ICmpInst *ExitCond,
8007                                           bool ExitIfTrue,
8008                                           bool ControlsExit,
8009                                           bool AllowPredicates) {
8010   // If the condition was exit on true, convert the condition to exit on false
8011   ICmpInst::Predicate Pred;
8012   if (!ExitIfTrue)
8013     Pred = ExitCond->getPredicate();
8014   else
8015     Pred = ExitCond->getInversePredicate();
8016   const ICmpInst::Predicate OriginalPred = Pred;
8017 
8018   // Handle common loops like: for (X = "string"; *X; ++X)
8019   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
8020     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
8021       ExitLimit ItCnt =
8022         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
8023       if (ItCnt.hasAnyInfo())
8024         return ItCnt;
8025     }
8026 
8027   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8028   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8029 
8030   // Try to evaluate any dependencies out of the loop.
8031   LHS = getSCEVAtScope(LHS, L);
8032   RHS = getSCEVAtScope(RHS, L);
8033 
8034   // At this point, we would like to compute how many iterations of the
8035   // loop the predicate will return true for these inputs.
8036   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8037     // If there is a loop-invariant, force it into the RHS.
8038     std::swap(LHS, RHS);
8039     Pred = ICmpInst::getSwappedPredicate(Pred);
8040   }
8041 
8042   // Simplify the operands before analyzing them.
8043   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8044 
8045   // If we have a comparison of a chrec against a constant, try to use value
8046   // ranges to answer this query.
8047   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8048     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8049       if (AddRec->getLoop() == L) {
8050         // Form the constant range.
8051         ConstantRange CompRange =
8052             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8053 
8054         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8055         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8056       }
8057 
8058   switch (Pred) {
8059   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8060     // Convert to: while (X-Y != 0)
8061     if (LHS->getType()->isPointerTy()) {
8062       LHS = getLosslessPtrToIntExpr(LHS);
8063       if (isa<SCEVCouldNotCompute>(LHS))
8064         return LHS;
8065     }
8066     if (RHS->getType()->isPointerTy()) {
8067       RHS = getLosslessPtrToIntExpr(RHS);
8068       if (isa<SCEVCouldNotCompute>(RHS))
8069         return RHS;
8070     }
8071     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8072                                 AllowPredicates);
8073     if (EL.hasAnyInfo()) return EL;
8074     break;
8075   }
8076   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8077     // Convert to: while (X-Y == 0)
8078     if (LHS->getType()->isPointerTy()) {
8079       LHS = getLosslessPtrToIntExpr(LHS);
8080       if (isa<SCEVCouldNotCompute>(LHS))
8081         return LHS;
8082     }
8083     if (RHS->getType()->isPointerTy()) {
8084       RHS = getLosslessPtrToIntExpr(RHS);
8085       if (isa<SCEVCouldNotCompute>(RHS))
8086         return RHS;
8087     }
8088     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8089     if (EL.hasAnyInfo()) return EL;
8090     break;
8091   }
8092   case ICmpInst::ICMP_SLT:
8093   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8094     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8095     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8096                                     AllowPredicates);
8097     if (EL.hasAnyInfo()) return EL;
8098     break;
8099   }
8100   case ICmpInst::ICMP_SGT:
8101   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8102     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8103     ExitLimit EL =
8104         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8105                             AllowPredicates);
8106     if (EL.hasAnyInfo()) return EL;
8107     break;
8108   }
8109   default:
8110     break;
8111   }
8112 
8113   auto *ExhaustiveCount =
8114       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8115 
8116   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8117     return ExhaustiveCount;
8118 
8119   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8120                                       ExitCond->getOperand(1), L, OriginalPred);
8121 }
8122 
8123 ScalarEvolution::ExitLimit
8124 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8125                                                       SwitchInst *Switch,
8126                                                       BasicBlock *ExitingBlock,
8127                                                       bool ControlsExit) {
8128   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8129 
8130   // Give up if the exit is the default dest of a switch.
8131   if (Switch->getDefaultDest() == ExitingBlock)
8132     return getCouldNotCompute();
8133 
8134   assert(L->contains(Switch->getDefaultDest()) &&
8135          "Default case must not exit the loop!");
8136   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8137   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8138 
8139   // while (X != Y) --> while (X-Y != 0)
8140   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8141   if (EL.hasAnyInfo())
8142     return EL;
8143 
8144   return getCouldNotCompute();
8145 }
8146 
8147 static ConstantInt *
8148 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8149                                 ScalarEvolution &SE) {
8150   const SCEV *InVal = SE.getConstant(C);
8151   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8152   assert(isa<SCEVConstant>(Val) &&
8153          "Evaluation of SCEV at constant didn't fold correctly?");
8154   return cast<SCEVConstant>(Val)->getValue();
8155 }
8156 
8157 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
8158 /// compute the backedge execution count.
8159 ScalarEvolution::ExitLimit
8160 ScalarEvolution::computeLoadConstantCompareExitLimit(
8161   LoadInst *LI,
8162   Constant *RHS,
8163   const Loop *L,
8164   ICmpInst::Predicate predicate) {
8165   if (LI->isVolatile()) return getCouldNotCompute();
8166 
8167   // Check to see if the loaded pointer is a getelementptr of a global.
8168   // TODO: Use SCEV instead of manually grubbing with GEPs.
8169   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
8170   if (!GEP) return getCouldNotCompute();
8171 
8172   // Make sure that it is really a constant global we are gepping, with an
8173   // initializer, and make sure the first IDX is really 0.
8174   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
8175   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
8176       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
8177       !cast<Constant>(GEP->getOperand(1))->isNullValue())
8178     return getCouldNotCompute();
8179 
8180   // Okay, we allow one non-constant index into the GEP instruction.
8181   Value *VarIdx = nullptr;
8182   std::vector<Constant*> Indexes;
8183   unsigned VarIdxNum = 0;
8184   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
8185     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
8186       Indexes.push_back(CI);
8187     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
8188       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
8189       VarIdx = GEP->getOperand(i);
8190       VarIdxNum = i-2;
8191       Indexes.push_back(nullptr);
8192     }
8193 
8194   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
8195   if (!VarIdx)
8196     return getCouldNotCompute();
8197 
8198   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
8199   // Check to see if X is a loop variant variable value now.
8200   const SCEV *Idx = getSCEV(VarIdx);
8201   Idx = getSCEVAtScope(Idx, L);
8202 
8203   // We can only recognize very limited forms of loop index expressions, in
8204   // particular, only affine AddRec's like {C1,+,C2}<L>.
8205   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
8206   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
8207       isLoopInvariant(IdxExpr, L) ||
8208       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
8209       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
8210     return getCouldNotCompute();
8211 
8212   unsigned MaxSteps = MaxBruteForceIterations;
8213   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
8214     ConstantInt *ItCst = ConstantInt::get(
8215                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
8216     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
8217 
8218     // Form the GEP offset.
8219     Indexes[VarIdxNum] = Val;
8220 
8221     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
8222                                                          Indexes);
8223     if (!Result) break;  // Cannot compute!
8224 
8225     // Evaluate the condition for this iteration.
8226     Result = ConstantExpr::getICmp(predicate, Result, RHS);
8227     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
8228     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
8229       ++NumArrayLenItCounts;
8230       return getConstant(ItCst);   // Found terminating iteration!
8231     }
8232   }
8233   return getCouldNotCompute();
8234 }
8235 
8236 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8237     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8238   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8239   if (!RHS)
8240     return getCouldNotCompute();
8241 
8242   const BasicBlock *Latch = L->getLoopLatch();
8243   if (!Latch)
8244     return getCouldNotCompute();
8245 
8246   const BasicBlock *Predecessor = L->getLoopPredecessor();
8247   if (!Predecessor)
8248     return getCouldNotCompute();
8249 
8250   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8251   // Return LHS in OutLHS and shift_opt in OutOpCode.
8252   auto MatchPositiveShift =
8253       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8254 
8255     using namespace PatternMatch;
8256 
8257     ConstantInt *ShiftAmt;
8258     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8259       OutOpCode = Instruction::LShr;
8260     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8261       OutOpCode = Instruction::AShr;
8262     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8263       OutOpCode = Instruction::Shl;
8264     else
8265       return false;
8266 
8267     return ShiftAmt->getValue().isStrictlyPositive();
8268   };
8269 
8270   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8271   //
8272   // loop:
8273   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8274   //   %iv.shifted = lshr i32 %iv, <positive constant>
8275   //
8276   // Return true on a successful match.  Return the corresponding PHI node (%iv
8277   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8278   auto MatchShiftRecurrence =
8279       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8280     Optional<Instruction::BinaryOps> PostShiftOpCode;
8281 
8282     {
8283       Instruction::BinaryOps OpC;
8284       Value *V;
8285 
8286       // If we encounter a shift instruction, "peel off" the shift operation,
8287       // and remember that we did so.  Later when we inspect %iv's backedge
8288       // value, we will make sure that the backedge value uses the same
8289       // operation.
8290       //
8291       // Note: the peeled shift operation does not have to be the same
8292       // instruction as the one feeding into the PHI's backedge value.  We only
8293       // really care about it being the same *kind* of shift instruction --
8294       // that's all that is required for our later inferences to hold.
8295       if (MatchPositiveShift(LHS, V, OpC)) {
8296         PostShiftOpCode = OpC;
8297         LHS = V;
8298       }
8299     }
8300 
8301     PNOut = dyn_cast<PHINode>(LHS);
8302     if (!PNOut || PNOut->getParent() != L->getHeader())
8303       return false;
8304 
8305     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8306     Value *OpLHS;
8307 
8308     return
8309         // The backedge value for the PHI node must be a shift by a positive
8310         // amount
8311         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8312 
8313         // of the PHI node itself
8314         OpLHS == PNOut &&
8315 
8316         // and the kind of shift should be match the kind of shift we peeled
8317         // off, if any.
8318         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8319   };
8320 
8321   PHINode *PN;
8322   Instruction::BinaryOps OpCode;
8323   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8324     return getCouldNotCompute();
8325 
8326   const DataLayout &DL = getDataLayout();
8327 
8328   // The key rationale for this optimization is that for some kinds of shift
8329   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8330   // within a finite number of iterations.  If the condition guarding the
8331   // backedge (in the sense that the backedge is taken if the condition is true)
8332   // is false for the value the shift recurrence stabilizes to, then we know
8333   // that the backedge is taken only a finite number of times.
8334 
8335   ConstantInt *StableValue = nullptr;
8336   switch (OpCode) {
8337   default:
8338     llvm_unreachable("Impossible case!");
8339 
8340   case Instruction::AShr: {
8341     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8342     // bitwidth(K) iterations.
8343     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8344     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8345                                        Predecessor->getTerminator(), &DT);
8346     auto *Ty = cast<IntegerType>(RHS->getType());
8347     if (Known.isNonNegative())
8348       StableValue = ConstantInt::get(Ty, 0);
8349     else if (Known.isNegative())
8350       StableValue = ConstantInt::get(Ty, -1, true);
8351     else
8352       return getCouldNotCompute();
8353 
8354     break;
8355   }
8356   case Instruction::LShr:
8357   case Instruction::Shl:
8358     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8359     // stabilize to 0 in at most bitwidth(K) iterations.
8360     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8361     break;
8362   }
8363 
8364   auto *Result =
8365       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8366   assert(Result->getType()->isIntegerTy(1) &&
8367          "Otherwise cannot be an operand to a branch instruction");
8368 
8369   if (Result->isZeroValue()) {
8370     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8371     const SCEV *UpperBound =
8372         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8373     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8374   }
8375 
8376   return getCouldNotCompute();
8377 }
8378 
8379 /// Return true if we can constant fold an instruction of the specified type,
8380 /// assuming that all operands were constants.
8381 static bool CanConstantFold(const Instruction *I) {
8382   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8383       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8384       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8385     return true;
8386 
8387   if (const CallInst *CI = dyn_cast<CallInst>(I))
8388     if (const Function *F = CI->getCalledFunction())
8389       return canConstantFoldCallTo(CI, F);
8390   return false;
8391 }
8392 
8393 /// Determine whether this instruction can constant evolve within this loop
8394 /// assuming its operands can all constant evolve.
8395 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8396   // An instruction outside of the loop can't be derived from a loop PHI.
8397   if (!L->contains(I)) return false;
8398 
8399   if (isa<PHINode>(I)) {
8400     // We don't currently keep track of the control flow needed to evaluate
8401     // PHIs, so we cannot handle PHIs inside of loops.
8402     return L->getHeader() == I->getParent();
8403   }
8404 
8405   // If we won't be able to constant fold this expression even if the operands
8406   // are constants, bail early.
8407   return CanConstantFold(I);
8408 }
8409 
8410 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8411 /// recursing through each instruction operand until reaching a loop header phi.
8412 static PHINode *
8413 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8414                                DenseMap<Instruction *, PHINode *> &PHIMap,
8415                                unsigned Depth) {
8416   if (Depth > MaxConstantEvolvingDepth)
8417     return nullptr;
8418 
8419   // Otherwise, we can evaluate this instruction if all of its operands are
8420   // constant or derived from a PHI node themselves.
8421   PHINode *PHI = nullptr;
8422   for (Value *Op : UseInst->operands()) {
8423     if (isa<Constant>(Op)) continue;
8424 
8425     Instruction *OpInst = dyn_cast<Instruction>(Op);
8426     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8427 
8428     PHINode *P = dyn_cast<PHINode>(OpInst);
8429     if (!P)
8430       // If this operand is already visited, reuse the prior result.
8431       // We may have P != PHI if this is the deepest point at which the
8432       // inconsistent paths meet.
8433       P = PHIMap.lookup(OpInst);
8434     if (!P) {
8435       // Recurse and memoize the results, whether a phi is found or not.
8436       // This recursive call invalidates pointers into PHIMap.
8437       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8438       PHIMap[OpInst] = P;
8439     }
8440     if (!P)
8441       return nullptr;  // Not evolving from PHI
8442     if (PHI && PHI != P)
8443       return nullptr;  // Evolving from multiple different PHIs.
8444     PHI = P;
8445   }
8446   // This is a expression evolving from a constant PHI!
8447   return PHI;
8448 }
8449 
8450 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8451 /// in the loop that V is derived from.  We allow arbitrary operations along the
8452 /// way, but the operands of an operation must either be constants or a value
8453 /// derived from a constant PHI.  If this expression does not fit with these
8454 /// constraints, return null.
8455 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8456   Instruction *I = dyn_cast<Instruction>(V);
8457   if (!I || !canConstantEvolve(I, L)) return nullptr;
8458 
8459   if (PHINode *PN = dyn_cast<PHINode>(I))
8460     return PN;
8461 
8462   // Record non-constant instructions contained by the loop.
8463   DenseMap<Instruction *, PHINode *> PHIMap;
8464   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8465 }
8466 
8467 /// EvaluateExpression - Given an expression that passes the
8468 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8469 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8470 /// reason, return null.
8471 static Constant *EvaluateExpression(Value *V, const Loop *L,
8472                                     DenseMap<Instruction *, Constant *> &Vals,
8473                                     const DataLayout &DL,
8474                                     const TargetLibraryInfo *TLI) {
8475   // Convenient constant check, but redundant for recursive calls.
8476   if (Constant *C = dyn_cast<Constant>(V)) return C;
8477   Instruction *I = dyn_cast<Instruction>(V);
8478   if (!I) return nullptr;
8479 
8480   if (Constant *C = Vals.lookup(I)) return C;
8481 
8482   // An instruction inside the loop depends on a value outside the loop that we
8483   // weren't given a mapping for, or a value such as a call inside the loop.
8484   if (!canConstantEvolve(I, L)) return nullptr;
8485 
8486   // An unmapped PHI can be due to a branch or another loop inside this loop,
8487   // or due to this not being the initial iteration through a loop where we
8488   // couldn't compute the evolution of this particular PHI last time.
8489   if (isa<PHINode>(I)) return nullptr;
8490 
8491   std::vector<Constant*> Operands(I->getNumOperands());
8492 
8493   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8494     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8495     if (!Operand) {
8496       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8497       if (!Operands[i]) return nullptr;
8498       continue;
8499     }
8500     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8501     Vals[Operand] = C;
8502     if (!C) return nullptr;
8503     Operands[i] = C;
8504   }
8505 
8506   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8507     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8508                                            Operands[1], DL, TLI);
8509   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8510     if (!LI->isVolatile())
8511       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8512   }
8513   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8514 }
8515 
8516 
8517 // If every incoming value to PN except the one for BB is a specific Constant,
8518 // return that, else return nullptr.
8519 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8520   Constant *IncomingVal = nullptr;
8521 
8522   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8523     if (PN->getIncomingBlock(i) == BB)
8524       continue;
8525 
8526     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8527     if (!CurrentVal)
8528       return nullptr;
8529 
8530     if (IncomingVal != CurrentVal) {
8531       if (IncomingVal)
8532         return nullptr;
8533       IncomingVal = CurrentVal;
8534     }
8535   }
8536 
8537   return IncomingVal;
8538 }
8539 
8540 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8541 /// in the header of its containing loop, we know the loop executes a
8542 /// constant number of times, and the PHI node is just a recurrence
8543 /// involving constants, fold it.
8544 Constant *
8545 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8546                                                    const APInt &BEs,
8547                                                    const Loop *L) {
8548   auto I = ConstantEvolutionLoopExitValue.find(PN);
8549   if (I != ConstantEvolutionLoopExitValue.end())
8550     return I->second;
8551 
8552   if (BEs.ugt(MaxBruteForceIterations))
8553     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8554 
8555   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8556 
8557   DenseMap<Instruction *, Constant *> CurrentIterVals;
8558   BasicBlock *Header = L->getHeader();
8559   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8560 
8561   BasicBlock *Latch = L->getLoopLatch();
8562   if (!Latch)
8563     return nullptr;
8564 
8565   for (PHINode &PHI : Header->phis()) {
8566     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8567       CurrentIterVals[&PHI] = StartCST;
8568   }
8569   if (!CurrentIterVals.count(PN))
8570     return RetVal = nullptr;
8571 
8572   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8573 
8574   // Execute the loop symbolically to determine the exit value.
8575   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8576          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8577 
8578   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8579   unsigned IterationNum = 0;
8580   const DataLayout &DL = getDataLayout();
8581   for (; ; ++IterationNum) {
8582     if (IterationNum == NumIterations)
8583       return RetVal = CurrentIterVals[PN];  // Got exit value!
8584 
8585     // Compute the value of the PHIs for the next iteration.
8586     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8587     DenseMap<Instruction *, Constant *> NextIterVals;
8588     Constant *NextPHI =
8589         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8590     if (!NextPHI)
8591       return nullptr;        // Couldn't evaluate!
8592     NextIterVals[PN] = NextPHI;
8593 
8594     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8595 
8596     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8597     // cease to be able to evaluate one of them or if they stop evolving,
8598     // because that doesn't necessarily prevent us from computing PN.
8599     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8600     for (const auto &I : CurrentIterVals) {
8601       PHINode *PHI = dyn_cast<PHINode>(I.first);
8602       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8603       PHIsToCompute.emplace_back(PHI, I.second);
8604     }
8605     // We use two distinct loops because EvaluateExpression may invalidate any
8606     // iterators into CurrentIterVals.
8607     for (const auto &I : PHIsToCompute) {
8608       PHINode *PHI = I.first;
8609       Constant *&NextPHI = NextIterVals[PHI];
8610       if (!NextPHI) {   // Not already computed.
8611         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8612         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8613       }
8614       if (NextPHI != I.second)
8615         StoppedEvolving = false;
8616     }
8617 
8618     // If all entries in CurrentIterVals == NextIterVals then we can stop
8619     // iterating, the loop can't continue to change.
8620     if (StoppedEvolving)
8621       return RetVal = CurrentIterVals[PN];
8622 
8623     CurrentIterVals.swap(NextIterVals);
8624   }
8625 }
8626 
8627 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8628                                                           Value *Cond,
8629                                                           bool ExitWhen) {
8630   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8631   if (!PN) return getCouldNotCompute();
8632 
8633   // If the loop is canonicalized, the PHI will have exactly two entries.
8634   // That's the only form we support here.
8635   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8636 
8637   DenseMap<Instruction *, Constant *> CurrentIterVals;
8638   BasicBlock *Header = L->getHeader();
8639   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8640 
8641   BasicBlock *Latch = L->getLoopLatch();
8642   assert(Latch && "Should follow from NumIncomingValues == 2!");
8643 
8644   for (PHINode &PHI : Header->phis()) {
8645     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8646       CurrentIterVals[&PHI] = StartCST;
8647   }
8648   if (!CurrentIterVals.count(PN))
8649     return getCouldNotCompute();
8650 
8651   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8652   // the loop symbolically to determine when the condition gets a value of
8653   // "ExitWhen".
8654   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8655   const DataLayout &DL = getDataLayout();
8656   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8657     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8658         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8659 
8660     // Couldn't symbolically evaluate.
8661     if (!CondVal) return getCouldNotCompute();
8662 
8663     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8664       ++NumBruteForceTripCountsComputed;
8665       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8666     }
8667 
8668     // Update all the PHI nodes for the next iteration.
8669     DenseMap<Instruction *, Constant *> NextIterVals;
8670 
8671     // Create a list of which PHIs we need to compute. We want to do this before
8672     // calling EvaluateExpression on them because that may invalidate iterators
8673     // into CurrentIterVals.
8674     SmallVector<PHINode *, 8> PHIsToCompute;
8675     for (const auto &I : CurrentIterVals) {
8676       PHINode *PHI = dyn_cast<PHINode>(I.first);
8677       if (!PHI || PHI->getParent() != Header) continue;
8678       PHIsToCompute.push_back(PHI);
8679     }
8680     for (PHINode *PHI : PHIsToCompute) {
8681       Constant *&NextPHI = NextIterVals[PHI];
8682       if (NextPHI) continue;    // Already computed!
8683 
8684       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8685       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8686     }
8687     CurrentIterVals.swap(NextIterVals);
8688   }
8689 
8690   // Too many iterations were needed to evaluate.
8691   return getCouldNotCompute();
8692 }
8693 
8694 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8695   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8696       ValuesAtScopes[V];
8697   // Check to see if we've folded this expression at this loop before.
8698   for (auto &LS : Values)
8699     if (LS.first == L)
8700       return LS.second ? LS.second : V;
8701 
8702   Values.emplace_back(L, nullptr);
8703 
8704   // Otherwise compute it.
8705   const SCEV *C = computeSCEVAtScope(V, L);
8706   for (auto &LS : reverse(ValuesAtScopes[V]))
8707     if (LS.first == L) {
8708       LS.second = C;
8709       break;
8710     }
8711   return C;
8712 }
8713 
8714 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8715 /// will return Constants for objects which aren't represented by a
8716 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8717 /// Returns NULL if the SCEV isn't representable as a Constant.
8718 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8719   switch (V->getSCEVType()) {
8720   case scCouldNotCompute:
8721   case scAddRecExpr:
8722     return nullptr;
8723   case scConstant:
8724     return cast<SCEVConstant>(V)->getValue();
8725   case scUnknown:
8726     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8727   case scSignExtend: {
8728     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8729     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8730       return ConstantExpr::getSExt(CastOp, SS->getType());
8731     return nullptr;
8732   }
8733   case scZeroExtend: {
8734     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8735     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8736       return ConstantExpr::getZExt(CastOp, SZ->getType());
8737     return nullptr;
8738   }
8739   case scPtrToInt: {
8740     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8741     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8742       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8743 
8744     return nullptr;
8745   }
8746   case scTruncate: {
8747     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8748     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8749       return ConstantExpr::getTrunc(CastOp, ST->getType());
8750     return nullptr;
8751   }
8752   case scAddExpr: {
8753     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8754     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8755       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8756         unsigned AS = PTy->getAddressSpace();
8757         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8758         C = ConstantExpr::getBitCast(C, DestPtrTy);
8759       }
8760       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8761         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8762         if (!C2)
8763           return nullptr;
8764 
8765         // First pointer!
8766         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8767           unsigned AS = C2->getType()->getPointerAddressSpace();
8768           std::swap(C, C2);
8769           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8770           // The offsets have been converted to bytes.  We can add bytes to an
8771           // i8* by GEP with the byte count in the first index.
8772           C = ConstantExpr::getBitCast(C, DestPtrTy);
8773         }
8774 
8775         // Don't bother trying to sum two pointers. We probably can't
8776         // statically compute a load that results from it anyway.
8777         if (C2->getType()->isPointerTy())
8778           return nullptr;
8779 
8780         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8781           if (PTy->getElementType()->isStructTy())
8782             C2 = ConstantExpr::getIntegerCast(
8783                 C2, Type::getInt32Ty(C->getContext()), true);
8784           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8785         } else
8786           C = ConstantExpr::getAdd(C, C2);
8787       }
8788       return C;
8789     }
8790     return nullptr;
8791   }
8792   case scMulExpr: {
8793     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8794     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8795       // Don't bother with pointers at all.
8796       if (C->getType()->isPointerTy())
8797         return nullptr;
8798       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8799         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8800         if (!C2 || C2->getType()->isPointerTy())
8801           return nullptr;
8802         C = ConstantExpr::getMul(C, C2);
8803       }
8804       return C;
8805     }
8806     return nullptr;
8807   }
8808   case scUDivExpr: {
8809     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8810     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8811       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8812         if (LHS->getType() == RHS->getType())
8813           return ConstantExpr::getUDiv(LHS, RHS);
8814     return nullptr;
8815   }
8816   case scSMaxExpr:
8817   case scUMaxExpr:
8818   case scSMinExpr:
8819   case scUMinExpr:
8820     return nullptr; // TODO: smax, umax, smin, umax.
8821   }
8822   llvm_unreachable("Unknown SCEV kind!");
8823 }
8824 
8825 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8826   if (isa<SCEVConstant>(V)) return V;
8827 
8828   // If this instruction is evolved from a constant-evolving PHI, compute the
8829   // exit value from the loop without using SCEVs.
8830   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8831     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8832       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8833         const Loop *CurrLoop = this->LI[I->getParent()];
8834         // Looking for loop exit value.
8835         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8836             PN->getParent() == CurrLoop->getHeader()) {
8837           // Okay, there is no closed form solution for the PHI node.  Check
8838           // to see if the loop that contains it has a known backedge-taken
8839           // count.  If so, we may be able to force computation of the exit
8840           // value.
8841           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8842           // This trivial case can show up in some degenerate cases where
8843           // the incoming IR has not yet been fully simplified.
8844           if (BackedgeTakenCount->isZero()) {
8845             Value *InitValue = nullptr;
8846             bool MultipleInitValues = false;
8847             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8848               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8849                 if (!InitValue)
8850                   InitValue = PN->getIncomingValue(i);
8851                 else if (InitValue != PN->getIncomingValue(i)) {
8852                   MultipleInitValues = true;
8853                   break;
8854                 }
8855               }
8856             }
8857             if (!MultipleInitValues && InitValue)
8858               return getSCEV(InitValue);
8859           }
8860           // Do we have a loop invariant value flowing around the backedge
8861           // for a loop which must execute the backedge?
8862           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8863               isKnownPositive(BackedgeTakenCount) &&
8864               PN->getNumIncomingValues() == 2) {
8865 
8866             unsigned InLoopPred =
8867                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8868             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8869             if (CurrLoop->isLoopInvariant(BackedgeVal))
8870               return getSCEV(BackedgeVal);
8871           }
8872           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8873             // Okay, we know how many times the containing loop executes.  If
8874             // this is a constant evolving PHI node, get the final value at
8875             // the specified iteration number.
8876             Constant *RV = getConstantEvolutionLoopExitValue(
8877                 PN, BTCC->getAPInt(), CurrLoop);
8878             if (RV) return getSCEV(RV);
8879           }
8880         }
8881 
8882         // If there is a single-input Phi, evaluate it at our scope. If we can
8883         // prove that this replacement does not break LCSSA form, use new value.
8884         if (PN->getNumOperands() == 1) {
8885           const SCEV *Input = getSCEV(PN->getOperand(0));
8886           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8887           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8888           // for the simplest case just support constants.
8889           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8890         }
8891       }
8892 
8893       // Okay, this is an expression that we cannot symbolically evaluate
8894       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8895       // the arguments into constants, and if so, try to constant propagate the
8896       // result.  This is particularly useful for computing loop exit values.
8897       if (CanConstantFold(I)) {
8898         SmallVector<Constant *, 4> Operands;
8899         bool MadeImprovement = false;
8900         for (Value *Op : I->operands()) {
8901           if (Constant *C = dyn_cast<Constant>(Op)) {
8902             Operands.push_back(C);
8903             continue;
8904           }
8905 
8906           // If any of the operands is non-constant and if they are
8907           // non-integer and non-pointer, don't even try to analyze them
8908           // with scev techniques.
8909           if (!isSCEVable(Op->getType()))
8910             return V;
8911 
8912           const SCEV *OrigV = getSCEV(Op);
8913           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8914           MadeImprovement |= OrigV != OpV;
8915 
8916           Constant *C = BuildConstantFromSCEV(OpV);
8917           if (!C) return V;
8918           if (C->getType() != Op->getType())
8919             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8920                                                               Op->getType(),
8921                                                               false),
8922                                       C, Op->getType());
8923           Operands.push_back(C);
8924         }
8925 
8926         // Check to see if getSCEVAtScope actually made an improvement.
8927         if (MadeImprovement) {
8928           Constant *C = nullptr;
8929           const DataLayout &DL = getDataLayout();
8930           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8931             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8932                                                 Operands[1], DL, &TLI);
8933           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8934             if (!Load->isVolatile())
8935               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8936                                                DL);
8937           } else
8938             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8939           if (!C) return V;
8940           return getSCEV(C);
8941         }
8942       }
8943     }
8944 
8945     // This is some other type of SCEVUnknown, just return it.
8946     return V;
8947   }
8948 
8949   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8950     // Avoid performing the look-up in the common case where the specified
8951     // expression has no loop-variant portions.
8952     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8953       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8954       if (OpAtScope != Comm->getOperand(i)) {
8955         // Okay, at least one of these operands is loop variant but might be
8956         // foldable.  Build a new instance of the folded commutative expression.
8957         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8958                                             Comm->op_begin()+i);
8959         NewOps.push_back(OpAtScope);
8960 
8961         for (++i; i != e; ++i) {
8962           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8963           NewOps.push_back(OpAtScope);
8964         }
8965         if (isa<SCEVAddExpr>(Comm))
8966           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8967         if (isa<SCEVMulExpr>(Comm))
8968           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8969         if (isa<SCEVMinMaxExpr>(Comm))
8970           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8971         llvm_unreachable("Unknown commutative SCEV type!");
8972       }
8973     }
8974     // If we got here, all operands are loop invariant.
8975     return Comm;
8976   }
8977 
8978   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8979     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8980     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8981     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8982       return Div;   // must be loop invariant
8983     return getUDivExpr(LHS, RHS);
8984   }
8985 
8986   // If this is a loop recurrence for a loop that does not contain L, then we
8987   // are dealing with the final value computed by the loop.
8988   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8989     // First, attempt to evaluate each operand.
8990     // Avoid performing the look-up in the common case where the specified
8991     // expression has no loop-variant portions.
8992     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8993       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8994       if (OpAtScope == AddRec->getOperand(i))
8995         continue;
8996 
8997       // Okay, at least one of these operands is loop variant but might be
8998       // foldable.  Build a new instance of the folded commutative expression.
8999       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9000                                           AddRec->op_begin()+i);
9001       NewOps.push_back(OpAtScope);
9002       for (++i; i != e; ++i)
9003         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9004 
9005       const SCEV *FoldedRec =
9006         getAddRecExpr(NewOps, AddRec->getLoop(),
9007                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9008       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9009       // The addrec may be folded to a nonrecurrence, for example, if the
9010       // induction variable is multiplied by zero after constant folding. Go
9011       // ahead and return the folded value.
9012       if (!AddRec)
9013         return FoldedRec;
9014       break;
9015     }
9016 
9017     // If the scope is outside the addrec's loop, evaluate it by using the
9018     // loop exit value of the addrec.
9019     if (!AddRec->getLoop()->contains(L)) {
9020       // To evaluate this recurrence, we need to know how many times the AddRec
9021       // loop iterates.  Compute this now.
9022       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9023       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9024 
9025       // Then, evaluate the AddRec.
9026       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9027     }
9028 
9029     return AddRec;
9030   }
9031 
9032   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
9033     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9034     if (Op == Cast->getOperand())
9035       return Cast;  // must be loop invariant
9036     return getZeroExtendExpr(Op, Cast->getType());
9037   }
9038 
9039   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
9040     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9041     if (Op == Cast->getOperand())
9042       return Cast;  // must be loop invariant
9043     return getSignExtendExpr(Op, Cast->getType());
9044   }
9045 
9046   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
9047     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9048     if (Op == Cast->getOperand())
9049       return Cast;  // must be loop invariant
9050     return getTruncateExpr(Op, Cast->getType());
9051   }
9052 
9053   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
9054     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9055     if (Op == Cast->getOperand())
9056       return Cast; // must be loop invariant
9057     return getPtrToIntExpr(Op, Cast->getType());
9058   }
9059 
9060   llvm_unreachable("Unknown SCEV type!");
9061 }
9062 
9063 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9064   return getSCEVAtScope(getSCEV(V), L);
9065 }
9066 
9067 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9068   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9069     return stripInjectiveFunctions(ZExt->getOperand());
9070   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9071     return stripInjectiveFunctions(SExt->getOperand());
9072   return S;
9073 }
9074 
9075 /// Finds the minimum unsigned root of the following equation:
9076 ///
9077 ///     A * X = B (mod N)
9078 ///
9079 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9080 /// A and B isn't important.
9081 ///
9082 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9083 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9084                                                ScalarEvolution &SE) {
9085   uint32_t BW = A.getBitWidth();
9086   assert(BW == SE.getTypeSizeInBits(B->getType()));
9087   assert(A != 0 && "A must be non-zero.");
9088 
9089   // 1. D = gcd(A, N)
9090   //
9091   // The gcd of A and N may have only one prime factor: 2. The number of
9092   // trailing zeros in A is its multiplicity
9093   uint32_t Mult2 = A.countTrailingZeros();
9094   // D = 2^Mult2
9095 
9096   // 2. Check if B is divisible by D.
9097   //
9098   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9099   // is not less than multiplicity of this prime factor for D.
9100   if (SE.GetMinTrailingZeros(B) < Mult2)
9101     return SE.getCouldNotCompute();
9102 
9103   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9104   // modulo (N / D).
9105   //
9106   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9107   // (N / D) in general. The inverse itself always fits into BW bits, though,
9108   // so we immediately truncate it.
9109   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9110   APInt Mod(BW + 1, 0);
9111   Mod.setBit(BW - Mult2);  // Mod = N / D
9112   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9113 
9114   // 4. Compute the minimum unsigned root of the equation:
9115   // I * (B / D) mod (N / D)
9116   // To simplify the computation, we factor out the divide by D:
9117   // (I * B mod N) / D
9118   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9119   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9120 }
9121 
9122 /// For a given quadratic addrec, generate coefficients of the corresponding
9123 /// quadratic equation, multiplied by a common value to ensure that they are
9124 /// integers.
9125 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9126 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9127 /// were multiplied by, and BitWidth is the bit width of the original addrec
9128 /// coefficients.
9129 /// This function returns None if the addrec coefficients are not compile-
9130 /// time constants.
9131 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9132 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9133   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9134   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9135   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9136   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9137   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9138                     << *AddRec << '\n');
9139 
9140   // We currently can only solve this if the coefficients are constants.
9141   if (!LC || !MC || !NC) {
9142     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9143     return None;
9144   }
9145 
9146   APInt L = LC->getAPInt();
9147   APInt M = MC->getAPInt();
9148   APInt N = NC->getAPInt();
9149   assert(!N.isNullValue() && "This is not a quadratic addrec");
9150 
9151   unsigned BitWidth = LC->getAPInt().getBitWidth();
9152   unsigned NewWidth = BitWidth + 1;
9153   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9154                     << BitWidth << '\n');
9155   // The sign-extension (as opposed to a zero-extension) here matches the
9156   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9157   N = N.sext(NewWidth);
9158   M = M.sext(NewWidth);
9159   L = L.sext(NewWidth);
9160 
9161   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9162   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9163   //   L+M, L+2M+N, L+3M+3N, ...
9164   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9165   //
9166   // The equation Acc = 0 is then
9167   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9168   // In a quadratic form it becomes:
9169   //   N n^2 + (2M-N) n + 2L = 0.
9170 
9171   APInt A = N;
9172   APInt B = 2 * M - A;
9173   APInt C = 2 * L;
9174   APInt T = APInt(NewWidth, 2);
9175   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9176                     << "x + " << C << ", coeff bw: " << NewWidth
9177                     << ", multiplied by " << T << '\n');
9178   return std::make_tuple(A, B, C, T, BitWidth);
9179 }
9180 
9181 /// Helper function to compare optional APInts:
9182 /// (a) if X and Y both exist, return min(X, Y),
9183 /// (b) if neither X nor Y exist, return None,
9184 /// (c) if exactly one of X and Y exists, return that value.
9185 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9186   if (X.hasValue() && Y.hasValue()) {
9187     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9188     APInt XW = X->sextOrSelf(W);
9189     APInt YW = Y->sextOrSelf(W);
9190     return XW.slt(YW) ? *X : *Y;
9191   }
9192   if (!X.hasValue() && !Y.hasValue())
9193     return None;
9194   return X.hasValue() ? *X : *Y;
9195 }
9196 
9197 /// Helper function to truncate an optional APInt to a given BitWidth.
9198 /// When solving addrec-related equations, it is preferable to return a value
9199 /// that has the same bit width as the original addrec's coefficients. If the
9200 /// solution fits in the original bit width, truncate it (except for i1).
9201 /// Returning a value of a different bit width may inhibit some optimizations.
9202 ///
9203 /// In general, a solution to a quadratic equation generated from an addrec
9204 /// may require BW+1 bits, where BW is the bit width of the addrec's
9205 /// coefficients. The reason is that the coefficients of the quadratic
9206 /// equation are BW+1 bits wide (to avoid truncation when converting from
9207 /// the addrec to the equation).
9208 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9209   if (!X.hasValue())
9210     return None;
9211   unsigned W = X->getBitWidth();
9212   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9213     return X->trunc(BitWidth);
9214   return X;
9215 }
9216 
9217 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9218 /// iterations. The values L, M, N are assumed to be signed, and they
9219 /// should all have the same bit widths.
9220 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9221 /// where BW is the bit width of the addrec's coefficients.
9222 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9223 /// returned as such, otherwise the bit width of the returned value may
9224 /// be greater than BW.
9225 ///
9226 /// This function returns None if
9227 /// (a) the addrec coefficients are not constant, or
9228 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9229 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9230 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9231 static Optional<APInt>
9232 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9233   APInt A, B, C, M;
9234   unsigned BitWidth;
9235   auto T = GetQuadraticEquation(AddRec);
9236   if (!T.hasValue())
9237     return None;
9238 
9239   std::tie(A, B, C, M, BitWidth) = *T;
9240   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9241   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9242   if (!X.hasValue())
9243     return None;
9244 
9245   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9246   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9247   if (!V->isZero())
9248     return None;
9249 
9250   return TruncIfPossible(X, BitWidth);
9251 }
9252 
9253 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9254 /// iterations. The values M, N are assumed to be signed, and they
9255 /// should all have the same bit widths.
9256 /// Find the least n such that c(n) does not belong to the given range,
9257 /// while c(n-1) does.
9258 ///
9259 /// This function returns None if
9260 /// (a) the addrec coefficients are not constant, or
9261 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9262 ///     bounds of the range.
9263 static Optional<APInt>
9264 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9265                           const ConstantRange &Range, ScalarEvolution &SE) {
9266   assert(AddRec->getOperand(0)->isZero() &&
9267          "Starting value of addrec should be 0");
9268   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9269                     << Range << ", addrec " << *AddRec << '\n');
9270   // This case is handled in getNumIterationsInRange. Here we can assume that
9271   // we start in the range.
9272   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9273          "Addrec's initial value should be in range");
9274 
9275   APInt A, B, C, M;
9276   unsigned BitWidth;
9277   auto T = GetQuadraticEquation(AddRec);
9278   if (!T.hasValue())
9279     return None;
9280 
9281   // Be careful about the return value: there can be two reasons for not
9282   // returning an actual number. First, if no solutions to the equations
9283   // were found, and second, if the solutions don't leave the given range.
9284   // The first case means that the actual solution is "unknown", the second
9285   // means that it's known, but not valid. If the solution is unknown, we
9286   // cannot make any conclusions.
9287   // Return a pair: the optional solution and a flag indicating if the
9288   // solution was found.
9289   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9290     // Solve for signed overflow and unsigned overflow, pick the lower
9291     // solution.
9292     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9293                       << Bound << " (before multiplying by " << M << ")\n");
9294     Bound *= M; // The quadratic equation multiplier.
9295 
9296     Optional<APInt> SO = None;
9297     if (BitWidth > 1) {
9298       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9299                            "signed overflow\n");
9300       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9301     }
9302     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9303                          "unsigned overflow\n");
9304     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9305                                                               BitWidth+1);
9306 
9307     auto LeavesRange = [&] (const APInt &X) {
9308       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9309       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9310       if (Range.contains(V0->getValue()))
9311         return false;
9312       // X should be at least 1, so X-1 is non-negative.
9313       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9314       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9315       if (Range.contains(V1->getValue()))
9316         return true;
9317       return false;
9318     };
9319 
9320     // If SolveQuadraticEquationWrap returns None, it means that there can
9321     // be a solution, but the function failed to find it. We cannot treat it
9322     // as "no solution".
9323     if (!SO.hasValue() || !UO.hasValue())
9324       return { None, false };
9325 
9326     // Check the smaller value first to see if it leaves the range.
9327     // At this point, both SO and UO must have values.
9328     Optional<APInt> Min = MinOptional(SO, UO);
9329     if (LeavesRange(*Min))
9330       return { Min, true };
9331     Optional<APInt> Max = Min == SO ? UO : SO;
9332     if (LeavesRange(*Max))
9333       return { Max, true };
9334 
9335     // Solutions were found, but were eliminated, hence the "true".
9336     return { None, true };
9337   };
9338 
9339   std::tie(A, B, C, M, BitWidth) = *T;
9340   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9341   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9342   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9343   auto SL = SolveForBoundary(Lower);
9344   auto SU = SolveForBoundary(Upper);
9345   // If any of the solutions was unknown, no meaninigful conclusions can
9346   // be made.
9347   if (!SL.second || !SU.second)
9348     return None;
9349 
9350   // Claim: The correct solution is not some value between Min and Max.
9351   //
9352   // Justification: Assuming that Min and Max are different values, one of
9353   // them is when the first signed overflow happens, the other is when the
9354   // first unsigned overflow happens. Crossing the range boundary is only
9355   // possible via an overflow (treating 0 as a special case of it, modeling
9356   // an overflow as crossing k*2^W for some k).
9357   //
9358   // The interesting case here is when Min was eliminated as an invalid
9359   // solution, but Max was not. The argument is that if there was another
9360   // overflow between Min and Max, it would also have been eliminated if
9361   // it was considered.
9362   //
9363   // For a given boundary, it is possible to have two overflows of the same
9364   // type (signed/unsigned) without having the other type in between: this
9365   // can happen when the vertex of the parabola is between the iterations
9366   // corresponding to the overflows. This is only possible when the two
9367   // overflows cross k*2^W for the same k. In such case, if the second one
9368   // left the range (and was the first one to do so), the first overflow
9369   // would have to enter the range, which would mean that either we had left
9370   // the range before or that we started outside of it. Both of these cases
9371   // are contradictions.
9372   //
9373   // Claim: In the case where SolveForBoundary returns None, the correct
9374   // solution is not some value between the Max for this boundary and the
9375   // Min of the other boundary.
9376   //
9377   // Justification: Assume that we had such Max_A and Min_B corresponding
9378   // to range boundaries A and B and such that Max_A < Min_B. If there was
9379   // a solution between Max_A and Min_B, it would have to be caused by an
9380   // overflow corresponding to either A or B. It cannot correspond to B,
9381   // since Min_B is the first occurrence of such an overflow. If it
9382   // corresponded to A, it would have to be either a signed or an unsigned
9383   // overflow that is larger than both eliminated overflows for A. But
9384   // between the eliminated overflows and this overflow, the values would
9385   // cover the entire value space, thus crossing the other boundary, which
9386   // is a contradiction.
9387 
9388   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9389 }
9390 
9391 ScalarEvolution::ExitLimit
9392 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9393                               bool AllowPredicates) {
9394 
9395   // This is only used for loops with a "x != y" exit test. The exit condition
9396   // is now expressed as a single expression, V = x-y. So the exit test is
9397   // effectively V != 0.  We know and take advantage of the fact that this
9398   // expression only being used in a comparison by zero context.
9399 
9400   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9401   // If the value is a constant
9402   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9403     // If the value is already zero, the branch will execute zero times.
9404     if (C->getValue()->isZero()) return C;
9405     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9406   }
9407 
9408   const SCEVAddRecExpr *AddRec =
9409       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9410 
9411   if (!AddRec && AllowPredicates)
9412     // Try to make this an AddRec using runtime tests, in the first X
9413     // iterations of this loop, where X is the SCEV expression found by the
9414     // algorithm below.
9415     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9416 
9417   if (!AddRec || AddRec->getLoop() != L)
9418     return getCouldNotCompute();
9419 
9420   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9421   // the quadratic equation to solve it.
9422   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9423     // We can only use this value if the chrec ends up with an exact zero
9424     // value at this index.  When solving for "X*X != 5", for example, we
9425     // should not accept a root of 2.
9426     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9427       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9428       return ExitLimit(R, R, false, Predicates);
9429     }
9430     return getCouldNotCompute();
9431   }
9432 
9433   // Otherwise we can only handle this if it is affine.
9434   if (!AddRec->isAffine())
9435     return getCouldNotCompute();
9436 
9437   // If this is an affine expression, the execution count of this branch is
9438   // the minimum unsigned root of the following equation:
9439   //
9440   //     Start + Step*N = 0 (mod 2^BW)
9441   //
9442   // equivalent to:
9443   //
9444   //             Step*N = -Start (mod 2^BW)
9445   //
9446   // where BW is the common bit width of Start and Step.
9447 
9448   // Get the initial value for the loop.
9449   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9450   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9451 
9452   // For now we handle only constant steps.
9453   //
9454   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9455   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9456   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9457   // We have not yet seen any such cases.
9458   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9459   if (!StepC || StepC->getValue()->isZero())
9460     return getCouldNotCompute();
9461 
9462   // For positive steps (counting up until unsigned overflow):
9463   //   N = -Start/Step (as unsigned)
9464   // For negative steps (counting down to zero):
9465   //   N = Start/-Step
9466   // First compute the unsigned distance from zero in the direction of Step.
9467   bool CountDown = StepC->getAPInt().isNegative();
9468   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9469 
9470   // Handle unitary steps, which cannot wraparound.
9471   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9472   //   N = Distance (as unsigned)
9473   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9474     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9475     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9476     if (MaxBECountBase.ult(MaxBECount))
9477       MaxBECount = MaxBECountBase;
9478 
9479     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9480     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9481     // case, and see if we can improve the bound.
9482     //
9483     // Explicitly handling this here is necessary because getUnsignedRange
9484     // isn't context-sensitive; it doesn't know that we only care about the
9485     // range inside the loop.
9486     const SCEV *Zero = getZero(Distance->getType());
9487     const SCEV *One = getOne(Distance->getType());
9488     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9489     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9490       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9491       // as "unsigned_max(Distance + 1) - 1".
9492       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9493       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9494     }
9495     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9496   }
9497 
9498   // If the condition controls loop exit (the loop exits only if the expression
9499   // is true) and the addition is no-wrap we can use unsigned divide to
9500   // compute the backedge count.  In this case, the step may not divide the
9501   // distance, but we don't care because if the condition is "missed" the loop
9502   // will have undefined behavior due to wrapping.
9503   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9504       loopHasNoAbnormalExits(AddRec->getLoop())) {
9505     const SCEV *Exact =
9506         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9507     const SCEV *Max = getCouldNotCompute();
9508     if (Exact != getCouldNotCompute()) {
9509       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
9510       APInt BaseMaxInt = getUnsignedRangeMax(Exact);
9511       if (BaseMaxInt.ult(MaxInt))
9512         Max = getConstant(BaseMaxInt);
9513       else
9514         Max = getConstant(MaxInt);
9515     }
9516     return ExitLimit(Exact, Max, false, Predicates);
9517   }
9518 
9519   // Solve the general equation.
9520   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9521                                                getNegativeSCEV(Start), *this);
9522   const SCEV *M = E == getCouldNotCompute()
9523                       ? E
9524                       : getConstant(getUnsignedRangeMax(E));
9525   return ExitLimit(E, M, false, Predicates);
9526 }
9527 
9528 ScalarEvolution::ExitLimit
9529 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9530   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9531   // handle them yet except for the trivial case.  This could be expanded in the
9532   // future as needed.
9533 
9534   // If the value is a constant, check to see if it is known to be non-zero
9535   // already.  If so, the backedge will execute zero times.
9536   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9537     if (!C->getValue()->isZero())
9538       return getZero(C->getType());
9539     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9540   }
9541 
9542   // We could implement others, but I really doubt anyone writes loops like
9543   // this, and if they did, they would already be constant folded.
9544   return getCouldNotCompute();
9545 }
9546 
9547 std::pair<const BasicBlock *, const BasicBlock *>
9548 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9549     const {
9550   // If the block has a unique predecessor, then there is no path from the
9551   // predecessor to the block that does not go through the direct edge
9552   // from the predecessor to the block.
9553   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9554     return {Pred, BB};
9555 
9556   // A loop's header is defined to be a block that dominates the loop.
9557   // If the header has a unique predecessor outside the loop, it must be
9558   // a block that has exactly one successor that can reach the loop.
9559   if (const Loop *L = LI.getLoopFor(BB))
9560     return {L->getLoopPredecessor(), L->getHeader()};
9561 
9562   return {nullptr, nullptr};
9563 }
9564 
9565 /// SCEV structural equivalence is usually sufficient for testing whether two
9566 /// expressions are equal, however for the purposes of looking for a condition
9567 /// guarding a loop, it can be useful to be a little more general, since a
9568 /// front-end may have replicated the controlling expression.
9569 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9570   // Quick check to see if they are the same SCEV.
9571   if (A == B) return true;
9572 
9573   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9574     // Not all instructions that are "identical" compute the same value.  For
9575     // instance, two distinct alloca instructions allocating the same type are
9576     // identical and do not read memory; but compute distinct values.
9577     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9578   };
9579 
9580   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9581   // two different instructions with the same value. Check for this case.
9582   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9583     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9584       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9585         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9586           if (ComputesEqualValues(AI, BI))
9587             return true;
9588 
9589   // Otherwise assume they may have a different value.
9590   return false;
9591 }
9592 
9593 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9594                                            const SCEV *&LHS, const SCEV *&RHS,
9595                                            unsigned Depth) {
9596   bool Changed = false;
9597   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9598   // '0 != 0'.
9599   auto TrivialCase = [&](bool TriviallyTrue) {
9600     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9601     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9602     return true;
9603   };
9604   // If we hit the max recursion limit bail out.
9605   if (Depth >= 3)
9606     return false;
9607 
9608   // Canonicalize a constant to the right side.
9609   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9610     // Check for both operands constant.
9611     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9612       if (ConstantExpr::getICmp(Pred,
9613                                 LHSC->getValue(),
9614                                 RHSC->getValue())->isNullValue())
9615         return TrivialCase(false);
9616       else
9617         return TrivialCase(true);
9618     }
9619     // Otherwise swap the operands to put the constant on the right.
9620     std::swap(LHS, RHS);
9621     Pred = ICmpInst::getSwappedPredicate(Pred);
9622     Changed = true;
9623   }
9624 
9625   // If we're comparing an addrec with a value which is loop-invariant in the
9626   // addrec's loop, put the addrec on the left. Also make a dominance check,
9627   // as both operands could be addrecs loop-invariant in each other's loop.
9628   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9629     const Loop *L = AR->getLoop();
9630     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9631       std::swap(LHS, RHS);
9632       Pred = ICmpInst::getSwappedPredicate(Pred);
9633       Changed = true;
9634     }
9635   }
9636 
9637   // If there's a constant operand, canonicalize comparisons with boundary
9638   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9639   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9640     const APInt &RA = RC->getAPInt();
9641 
9642     bool SimplifiedByConstantRange = false;
9643 
9644     if (!ICmpInst::isEquality(Pred)) {
9645       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9646       if (ExactCR.isFullSet())
9647         return TrivialCase(true);
9648       else if (ExactCR.isEmptySet())
9649         return TrivialCase(false);
9650 
9651       APInt NewRHS;
9652       CmpInst::Predicate NewPred;
9653       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9654           ICmpInst::isEquality(NewPred)) {
9655         // We were able to convert an inequality to an equality.
9656         Pred = NewPred;
9657         RHS = getConstant(NewRHS);
9658         Changed = SimplifiedByConstantRange = true;
9659       }
9660     }
9661 
9662     if (!SimplifiedByConstantRange) {
9663       switch (Pred) {
9664       default:
9665         break;
9666       case ICmpInst::ICMP_EQ:
9667       case ICmpInst::ICMP_NE:
9668         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9669         if (!RA)
9670           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9671             if (const SCEVMulExpr *ME =
9672                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9673               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9674                   ME->getOperand(0)->isAllOnesValue()) {
9675                 RHS = AE->getOperand(1);
9676                 LHS = ME->getOperand(1);
9677                 Changed = true;
9678               }
9679         break;
9680 
9681 
9682         // The "Should have been caught earlier!" messages refer to the fact
9683         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9684         // should have fired on the corresponding cases, and canonicalized the
9685         // check to trivial case.
9686 
9687       case ICmpInst::ICMP_UGE:
9688         assert(!RA.isMinValue() && "Should have been caught earlier!");
9689         Pred = ICmpInst::ICMP_UGT;
9690         RHS = getConstant(RA - 1);
9691         Changed = true;
9692         break;
9693       case ICmpInst::ICMP_ULE:
9694         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9695         Pred = ICmpInst::ICMP_ULT;
9696         RHS = getConstant(RA + 1);
9697         Changed = true;
9698         break;
9699       case ICmpInst::ICMP_SGE:
9700         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9701         Pred = ICmpInst::ICMP_SGT;
9702         RHS = getConstant(RA - 1);
9703         Changed = true;
9704         break;
9705       case ICmpInst::ICMP_SLE:
9706         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9707         Pred = ICmpInst::ICMP_SLT;
9708         RHS = getConstant(RA + 1);
9709         Changed = true;
9710         break;
9711       }
9712     }
9713   }
9714 
9715   // Check for obvious equality.
9716   if (HasSameValue(LHS, RHS)) {
9717     if (ICmpInst::isTrueWhenEqual(Pred))
9718       return TrivialCase(true);
9719     if (ICmpInst::isFalseWhenEqual(Pred))
9720       return TrivialCase(false);
9721   }
9722 
9723   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9724   // adding or subtracting 1 from one of the operands.
9725   switch (Pred) {
9726   case ICmpInst::ICMP_SLE:
9727     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9728       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9729                        SCEV::FlagNSW);
9730       Pred = ICmpInst::ICMP_SLT;
9731       Changed = true;
9732     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9733       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9734                        SCEV::FlagNSW);
9735       Pred = ICmpInst::ICMP_SLT;
9736       Changed = true;
9737     }
9738     break;
9739   case ICmpInst::ICMP_SGE:
9740     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9741       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9742                        SCEV::FlagNSW);
9743       Pred = ICmpInst::ICMP_SGT;
9744       Changed = true;
9745     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9746       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9747                        SCEV::FlagNSW);
9748       Pred = ICmpInst::ICMP_SGT;
9749       Changed = true;
9750     }
9751     break;
9752   case ICmpInst::ICMP_ULE:
9753     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9754       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9755                        SCEV::FlagNUW);
9756       Pred = ICmpInst::ICMP_ULT;
9757       Changed = true;
9758     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9759       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9760       Pred = ICmpInst::ICMP_ULT;
9761       Changed = true;
9762     }
9763     break;
9764   case ICmpInst::ICMP_UGE:
9765     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9766       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9767       Pred = ICmpInst::ICMP_UGT;
9768       Changed = true;
9769     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9770       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9771                        SCEV::FlagNUW);
9772       Pred = ICmpInst::ICMP_UGT;
9773       Changed = true;
9774     }
9775     break;
9776   default:
9777     break;
9778   }
9779 
9780   // TODO: More simplifications are possible here.
9781 
9782   // Recursively simplify until we either hit a recursion limit or nothing
9783   // changes.
9784   if (Changed)
9785     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9786 
9787   return Changed;
9788 }
9789 
9790 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9791   return getSignedRangeMax(S).isNegative();
9792 }
9793 
9794 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9795   return getSignedRangeMin(S).isStrictlyPositive();
9796 }
9797 
9798 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9799   return !getSignedRangeMin(S).isNegative();
9800 }
9801 
9802 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9803   return !getSignedRangeMax(S).isStrictlyPositive();
9804 }
9805 
9806 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9807   return isKnownNegative(S) || isKnownPositive(S);
9808 }
9809 
9810 std::pair<const SCEV *, const SCEV *>
9811 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9812   // Compute SCEV on entry of loop L.
9813   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9814   if (Start == getCouldNotCompute())
9815     return { Start, Start };
9816   // Compute post increment SCEV for loop L.
9817   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9818   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9819   return { Start, PostInc };
9820 }
9821 
9822 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9823                                           const SCEV *LHS, const SCEV *RHS) {
9824   // First collect all loops.
9825   SmallPtrSet<const Loop *, 8> LoopsUsed;
9826   getUsedLoops(LHS, LoopsUsed);
9827   getUsedLoops(RHS, LoopsUsed);
9828 
9829   if (LoopsUsed.empty())
9830     return false;
9831 
9832   // Domination relationship must be a linear order on collected loops.
9833 #ifndef NDEBUG
9834   for (auto *L1 : LoopsUsed)
9835     for (auto *L2 : LoopsUsed)
9836       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9837               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9838              "Domination relationship is not a linear order");
9839 #endif
9840 
9841   const Loop *MDL =
9842       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9843                         [&](const Loop *L1, const Loop *L2) {
9844          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9845        });
9846 
9847   // Get init and post increment value for LHS.
9848   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9849   // if LHS contains unknown non-invariant SCEV then bail out.
9850   if (SplitLHS.first == getCouldNotCompute())
9851     return false;
9852   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9853   // Get init and post increment value for RHS.
9854   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9855   // if RHS contains unknown non-invariant SCEV then bail out.
9856   if (SplitRHS.first == getCouldNotCompute())
9857     return false;
9858   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9859   // It is possible that init SCEV contains an invariant load but it does
9860   // not dominate MDL and is not available at MDL loop entry, so we should
9861   // check it here.
9862   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9863       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9864     return false;
9865 
9866   // It seems backedge guard check is faster than entry one so in some cases
9867   // it can speed up whole estimation by short circuit
9868   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9869                                      SplitRHS.second) &&
9870          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9871 }
9872 
9873 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9874                                        const SCEV *LHS, const SCEV *RHS) {
9875   // Canonicalize the inputs first.
9876   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9877 
9878   if (isKnownViaInduction(Pred, LHS, RHS))
9879     return true;
9880 
9881   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9882     return true;
9883 
9884   // Otherwise see what can be done with some simple reasoning.
9885   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9886 }
9887 
9888 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
9889                                                   const SCEV *LHS,
9890                                                   const SCEV *RHS) {
9891   if (isKnownPredicate(Pred, LHS, RHS))
9892     return true;
9893   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
9894     return false;
9895   return None;
9896 }
9897 
9898 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9899                                          const SCEV *LHS, const SCEV *RHS,
9900                                          const Instruction *Context) {
9901   // TODO: Analyze guards and assumes from Context's block.
9902   return isKnownPredicate(Pred, LHS, RHS) ||
9903          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9904 }
9905 
9906 Optional<bool>
9907 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
9908                                      const SCEV *RHS,
9909                                      const Instruction *Context) {
9910   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
9911   if (KnownWithoutContext)
9912     return KnownWithoutContext;
9913 
9914   if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS))
9915     return true;
9916   else if (isBasicBlockEntryGuardedByCond(Context->getParent(),
9917                                           ICmpInst::getInversePredicate(Pred),
9918                                           LHS, RHS))
9919     return false;
9920   return None;
9921 }
9922 
9923 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9924                                               const SCEVAddRecExpr *LHS,
9925                                               const SCEV *RHS) {
9926   const Loop *L = LHS->getLoop();
9927   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9928          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9929 }
9930 
9931 Optional<ScalarEvolution::MonotonicPredicateType>
9932 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9933                                            ICmpInst::Predicate Pred) {
9934   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9935 
9936 #ifndef NDEBUG
9937   // Verify an invariant: inverting the predicate should turn a monotonically
9938   // increasing change to a monotonically decreasing one, and vice versa.
9939   if (Result) {
9940     auto ResultSwapped =
9941         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9942 
9943     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9944     assert(ResultSwapped.getValue() != Result.getValue() &&
9945            "monotonicity should flip as we flip the predicate");
9946   }
9947 #endif
9948 
9949   return Result;
9950 }
9951 
9952 Optional<ScalarEvolution::MonotonicPredicateType>
9953 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9954                                                ICmpInst::Predicate Pred) {
9955   // A zero step value for LHS means the induction variable is essentially a
9956   // loop invariant value. We don't really depend on the predicate actually
9957   // flipping from false to true (for increasing predicates, and the other way
9958   // around for decreasing predicates), all we care about is that *if* the
9959   // predicate changes then it only changes from false to true.
9960   //
9961   // A zero step value in itself is not very useful, but there may be places
9962   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9963   // as general as possible.
9964 
9965   // Only handle LE/LT/GE/GT predicates.
9966   if (!ICmpInst::isRelational(Pred))
9967     return None;
9968 
9969   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9970   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9971          "Should be greater or less!");
9972 
9973   // Check that AR does not wrap.
9974   if (ICmpInst::isUnsigned(Pred)) {
9975     if (!LHS->hasNoUnsignedWrap())
9976       return None;
9977     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9978   } else {
9979     assert(ICmpInst::isSigned(Pred) &&
9980            "Relational predicate is either signed or unsigned!");
9981     if (!LHS->hasNoSignedWrap())
9982       return None;
9983 
9984     const SCEV *Step = LHS->getStepRecurrence(*this);
9985 
9986     if (isKnownNonNegative(Step))
9987       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9988 
9989     if (isKnownNonPositive(Step))
9990       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9991 
9992     return None;
9993   }
9994 }
9995 
9996 Optional<ScalarEvolution::LoopInvariantPredicate>
9997 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9998                                            const SCEV *LHS, const SCEV *RHS,
9999                                            const Loop *L) {
10000 
10001   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10002   if (!isLoopInvariant(RHS, L)) {
10003     if (!isLoopInvariant(LHS, L))
10004       return None;
10005 
10006     std::swap(LHS, RHS);
10007     Pred = ICmpInst::getSwappedPredicate(Pred);
10008   }
10009 
10010   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10011   if (!ArLHS || ArLHS->getLoop() != L)
10012     return None;
10013 
10014   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10015   if (!MonotonicType)
10016     return None;
10017   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10018   // true as the loop iterates, and the backedge is control dependent on
10019   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10020   //
10021   //   * if the predicate was false in the first iteration then the predicate
10022   //     is never evaluated again, since the loop exits without taking the
10023   //     backedge.
10024   //   * if the predicate was true in the first iteration then it will
10025   //     continue to be true for all future iterations since it is
10026   //     monotonically increasing.
10027   //
10028   // For both the above possibilities, we can replace the loop varying
10029   // predicate with its value on the first iteration of the loop (which is
10030   // loop invariant).
10031   //
10032   // A similar reasoning applies for a monotonically decreasing predicate, by
10033   // replacing true with false and false with true in the above two bullets.
10034   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10035   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10036 
10037   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10038     return None;
10039 
10040   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10041 }
10042 
10043 Optional<ScalarEvolution::LoopInvariantPredicate>
10044 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10045     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10046     const Instruction *Context, const SCEV *MaxIter) {
10047   // Try to prove the following set of facts:
10048   // - The predicate is monotonic in the iteration space.
10049   // - If the check does not fail on the 1st iteration:
10050   //   - No overflow will happen during first MaxIter iterations;
10051   //   - It will not fail on the MaxIter'th iteration.
10052   // If the check does fail on the 1st iteration, we leave the loop and no
10053   // other checks matter.
10054 
10055   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10056   if (!isLoopInvariant(RHS, L)) {
10057     if (!isLoopInvariant(LHS, L))
10058       return None;
10059 
10060     std::swap(LHS, RHS);
10061     Pred = ICmpInst::getSwappedPredicate(Pred);
10062   }
10063 
10064   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10065   if (!AR || AR->getLoop() != L)
10066     return None;
10067 
10068   // The predicate must be relational (i.e. <, <=, >=, >).
10069   if (!ICmpInst::isRelational(Pred))
10070     return None;
10071 
10072   // TODO: Support steps other than +/- 1.
10073   const SCEV *Step = AR->getStepRecurrence(*this);
10074   auto *One = getOne(Step->getType());
10075   auto *MinusOne = getNegativeSCEV(One);
10076   if (Step != One && Step != MinusOne)
10077     return None;
10078 
10079   // Type mismatch here means that MaxIter is potentially larger than max
10080   // unsigned value in start type, which mean we cannot prove no wrap for the
10081   // indvar.
10082   if (AR->getType() != MaxIter->getType())
10083     return None;
10084 
10085   // Value of IV on suggested last iteration.
10086   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10087   // Does it still meet the requirement?
10088   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10089     return None;
10090   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10091   // not exceed max unsigned value of this type), this effectively proves
10092   // that there is no wrap during the iteration. To prove that there is no
10093   // signed/unsigned wrap, we need to check that
10094   // Start <= Last for step = 1 or Start >= Last for step = -1.
10095   ICmpInst::Predicate NoOverflowPred =
10096       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10097   if (Step == MinusOne)
10098     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10099   const SCEV *Start = AR->getStart();
10100   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
10101     return None;
10102 
10103   // Everything is fine.
10104   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10105 }
10106 
10107 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10108     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10109   if (HasSameValue(LHS, RHS))
10110     return ICmpInst::isTrueWhenEqual(Pred);
10111 
10112   // This code is split out from isKnownPredicate because it is called from
10113   // within isLoopEntryGuardedByCond.
10114 
10115   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10116                          const ConstantRange &RangeRHS) {
10117     return RangeLHS.icmp(Pred, RangeRHS);
10118   };
10119 
10120   // The check at the top of the function catches the case where the values are
10121   // known to be equal.
10122   if (Pred == CmpInst::ICMP_EQ)
10123     return false;
10124 
10125   if (Pred == CmpInst::ICMP_NE) {
10126     if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10127         CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)))
10128       return true;
10129     auto *Diff = getMinusSCEV(LHS, RHS);
10130     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10131   }
10132 
10133   if (CmpInst::isSigned(Pred))
10134     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10135 
10136   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10137 }
10138 
10139 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10140                                                     const SCEV *LHS,
10141                                                     const SCEV *RHS) {
10142   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10143   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10144   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10145   // OutC1 and OutC2.
10146   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10147                                       APInt &OutC1, APInt &OutC2,
10148                                       SCEV::NoWrapFlags ExpectedFlags) {
10149     const SCEV *XNonConstOp, *XConstOp;
10150     const SCEV *YNonConstOp, *YConstOp;
10151     SCEV::NoWrapFlags XFlagsPresent;
10152     SCEV::NoWrapFlags YFlagsPresent;
10153 
10154     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10155       XConstOp = getZero(X->getType());
10156       XNonConstOp = X;
10157       XFlagsPresent = ExpectedFlags;
10158     }
10159     if (!isa<SCEVConstant>(XConstOp) ||
10160         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10161       return false;
10162 
10163     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10164       YConstOp = getZero(Y->getType());
10165       YNonConstOp = Y;
10166       YFlagsPresent = ExpectedFlags;
10167     }
10168 
10169     if (!isa<SCEVConstant>(YConstOp) ||
10170         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10171       return false;
10172 
10173     if (YNonConstOp != XNonConstOp)
10174       return false;
10175 
10176     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10177     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10178 
10179     return true;
10180   };
10181 
10182   APInt C1;
10183   APInt C2;
10184 
10185   switch (Pred) {
10186   default:
10187     break;
10188 
10189   case ICmpInst::ICMP_SGE:
10190     std::swap(LHS, RHS);
10191     LLVM_FALLTHROUGH;
10192   case ICmpInst::ICMP_SLE:
10193     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10194     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10195       return true;
10196 
10197     break;
10198 
10199   case ICmpInst::ICMP_SGT:
10200     std::swap(LHS, RHS);
10201     LLVM_FALLTHROUGH;
10202   case ICmpInst::ICMP_SLT:
10203     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10204     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10205       return true;
10206 
10207     break;
10208 
10209   case ICmpInst::ICMP_UGE:
10210     std::swap(LHS, RHS);
10211     LLVM_FALLTHROUGH;
10212   case ICmpInst::ICMP_ULE:
10213     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10214     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10215       return true;
10216 
10217     break;
10218 
10219   case ICmpInst::ICMP_UGT:
10220     std::swap(LHS, RHS);
10221     LLVM_FALLTHROUGH;
10222   case ICmpInst::ICMP_ULT:
10223     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10224     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10225       return true;
10226     break;
10227   }
10228 
10229   return false;
10230 }
10231 
10232 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10233                                                    const SCEV *LHS,
10234                                                    const SCEV *RHS) {
10235   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10236     return false;
10237 
10238   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10239   // the stack can result in exponential time complexity.
10240   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10241 
10242   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10243   //
10244   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10245   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10246   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10247   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10248   // use isKnownPredicate later if needed.
10249   return isKnownNonNegative(RHS) &&
10250          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10251          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10252 }
10253 
10254 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10255                                         ICmpInst::Predicate Pred,
10256                                         const SCEV *LHS, const SCEV *RHS) {
10257   // No need to even try if we know the module has no guards.
10258   if (!HasGuards)
10259     return false;
10260 
10261   return any_of(*BB, [&](const Instruction &I) {
10262     using namespace llvm::PatternMatch;
10263 
10264     Value *Condition;
10265     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10266                          m_Value(Condition))) &&
10267            isImpliedCond(Pred, LHS, RHS, Condition, false);
10268   });
10269 }
10270 
10271 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10272 /// protected by a conditional between LHS and RHS.  This is used to
10273 /// to eliminate casts.
10274 bool
10275 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10276                                              ICmpInst::Predicate Pred,
10277                                              const SCEV *LHS, const SCEV *RHS) {
10278   // Interpret a null as meaning no loop, where there is obviously no guard
10279   // (interprocedural conditions notwithstanding).
10280   if (!L) return true;
10281 
10282   if (VerifyIR)
10283     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10284            "This cannot be done on broken IR!");
10285 
10286 
10287   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10288     return true;
10289 
10290   BasicBlock *Latch = L->getLoopLatch();
10291   if (!Latch)
10292     return false;
10293 
10294   BranchInst *LoopContinuePredicate =
10295     dyn_cast<BranchInst>(Latch->getTerminator());
10296   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10297       isImpliedCond(Pred, LHS, RHS,
10298                     LoopContinuePredicate->getCondition(),
10299                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10300     return true;
10301 
10302   // We don't want more than one activation of the following loops on the stack
10303   // -- that can lead to O(n!) time complexity.
10304   if (WalkingBEDominatingConds)
10305     return false;
10306 
10307   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10308 
10309   // See if we can exploit a trip count to prove the predicate.
10310   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10311   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10312   if (LatchBECount != getCouldNotCompute()) {
10313     // We know that Latch branches back to the loop header exactly
10314     // LatchBECount times.  This means the backdege condition at Latch is
10315     // equivalent to  "{0,+,1} u< LatchBECount".
10316     Type *Ty = LatchBECount->getType();
10317     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10318     const SCEV *LoopCounter =
10319       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10320     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10321                       LatchBECount))
10322       return true;
10323   }
10324 
10325   // Check conditions due to any @llvm.assume intrinsics.
10326   for (auto &AssumeVH : AC.assumptions()) {
10327     if (!AssumeVH)
10328       continue;
10329     auto *CI = cast<CallInst>(AssumeVH);
10330     if (!DT.dominates(CI, Latch->getTerminator()))
10331       continue;
10332 
10333     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10334       return true;
10335   }
10336 
10337   // If the loop is not reachable from the entry block, we risk running into an
10338   // infinite loop as we walk up into the dom tree.  These loops do not matter
10339   // anyway, so we just return a conservative answer when we see them.
10340   if (!DT.isReachableFromEntry(L->getHeader()))
10341     return false;
10342 
10343   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10344     return true;
10345 
10346   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10347        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10348     assert(DTN && "should reach the loop header before reaching the root!");
10349 
10350     BasicBlock *BB = DTN->getBlock();
10351     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10352       return true;
10353 
10354     BasicBlock *PBB = BB->getSinglePredecessor();
10355     if (!PBB)
10356       continue;
10357 
10358     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10359     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10360       continue;
10361 
10362     Value *Condition = ContinuePredicate->getCondition();
10363 
10364     // If we have an edge `E` within the loop body that dominates the only
10365     // latch, the condition guarding `E` also guards the backedge.  This
10366     // reasoning works only for loops with a single latch.
10367 
10368     BasicBlockEdge DominatingEdge(PBB, BB);
10369     if (DominatingEdge.isSingleEdge()) {
10370       // We're constructively (and conservatively) enumerating edges within the
10371       // loop body that dominate the latch.  The dominator tree better agree
10372       // with us on this:
10373       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10374 
10375       if (isImpliedCond(Pred, LHS, RHS, Condition,
10376                         BB != ContinuePredicate->getSuccessor(0)))
10377         return true;
10378     }
10379   }
10380 
10381   return false;
10382 }
10383 
10384 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10385                                                      ICmpInst::Predicate Pred,
10386                                                      const SCEV *LHS,
10387                                                      const SCEV *RHS) {
10388   if (VerifyIR)
10389     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10390            "This cannot be done on broken IR!");
10391 
10392   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10393   // the facts (a >= b && a != b) separately. A typical situation is when the
10394   // non-strict comparison is known from ranges and non-equality is known from
10395   // dominating predicates. If we are proving strict comparison, we always try
10396   // to prove non-equality and non-strict comparison separately.
10397   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10398   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10399   bool ProvedNonStrictComparison = false;
10400   bool ProvedNonEquality = false;
10401 
10402   auto SplitAndProve =
10403     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10404     if (!ProvedNonStrictComparison)
10405       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10406     if (!ProvedNonEquality)
10407       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10408     if (ProvedNonStrictComparison && ProvedNonEquality)
10409       return true;
10410     return false;
10411   };
10412 
10413   if (ProvingStrictComparison) {
10414     auto ProofFn = [&](ICmpInst::Predicate P) {
10415       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10416     };
10417     if (SplitAndProve(ProofFn))
10418       return true;
10419   }
10420 
10421   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10422   auto ProveViaGuard = [&](const BasicBlock *Block) {
10423     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10424       return true;
10425     if (ProvingStrictComparison) {
10426       auto ProofFn = [&](ICmpInst::Predicate P) {
10427         return isImpliedViaGuard(Block, P, LHS, RHS);
10428       };
10429       if (SplitAndProve(ProofFn))
10430         return true;
10431     }
10432     return false;
10433   };
10434 
10435   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10436   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10437     const Instruction *Context = &BB->front();
10438     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10439       return true;
10440     if (ProvingStrictComparison) {
10441       auto ProofFn = [&](ICmpInst::Predicate P) {
10442         return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context);
10443       };
10444       if (SplitAndProve(ProofFn))
10445         return true;
10446     }
10447     return false;
10448   };
10449 
10450   // Starting at the block's predecessor, climb up the predecessor chain, as long
10451   // as there are predecessors that can be found that have unique successors
10452   // leading to the original block.
10453   const Loop *ContainingLoop = LI.getLoopFor(BB);
10454   const BasicBlock *PredBB;
10455   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10456     PredBB = ContainingLoop->getLoopPredecessor();
10457   else
10458     PredBB = BB->getSinglePredecessor();
10459   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10460        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10461     if (ProveViaGuard(Pair.first))
10462       return true;
10463 
10464     const BranchInst *LoopEntryPredicate =
10465         dyn_cast<BranchInst>(Pair.first->getTerminator());
10466     if (!LoopEntryPredicate ||
10467         LoopEntryPredicate->isUnconditional())
10468       continue;
10469 
10470     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10471                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10472       return true;
10473   }
10474 
10475   // Check conditions due to any @llvm.assume intrinsics.
10476   for (auto &AssumeVH : AC.assumptions()) {
10477     if (!AssumeVH)
10478       continue;
10479     auto *CI = cast<CallInst>(AssumeVH);
10480     if (!DT.dominates(CI, BB))
10481       continue;
10482 
10483     if (ProveViaCond(CI->getArgOperand(0), false))
10484       return true;
10485   }
10486 
10487   return false;
10488 }
10489 
10490 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10491                                                ICmpInst::Predicate Pred,
10492                                                const SCEV *LHS,
10493                                                const SCEV *RHS) {
10494   // Interpret a null as meaning no loop, where there is obviously no guard
10495   // (interprocedural conditions notwithstanding).
10496   if (!L)
10497     return false;
10498 
10499   // Both LHS and RHS must be available at loop entry.
10500   assert(isAvailableAtLoopEntry(LHS, L) &&
10501          "LHS is not available at Loop Entry");
10502   assert(isAvailableAtLoopEntry(RHS, L) &&
10503          "RHS is not available at Loop Entry");
10504 
10505   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10506     return true;
10507 
10508   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10509 }
10510 
10511 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10512                                     const SCEV *RHS,
10513                                     const Value *FoundCondValue, bool Inverse,
10514                                     const Instruction *Context) {
10515   // False conditions implies anything. Do not bother analyzing it further.
10516   if (FoundCondValue ==
10517       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10518     return true;
10519 
10520   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10521     return false;
10522 
10523   auto ClearOnExit =
10524       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10525 
10526   // Recursively handle And and Or conditions.
10527   const Value *Op0, *Op1;
10528   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10529     if (!Inverse)
10530       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10531               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10532   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10533     if (Inverse)
10534       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10535               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10536   }
10537 
10538   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10539   if (!ICI) return false;
10540 
10541   // Now that we found a conditional branch that dominates the loop or controls
10542   // the loop latch. Check to see if it is the comparison we are looking for.
10543   ICmpInst::Predicate FoundPred;
10544   if (Inverse)
10545     FoundPred = ICI->getInversePredicate();
10546   else
10547     FoundPred = ICI->getPredicate();
10548 
10549   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10550   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10551 
10552   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10553 }
10554 
10555 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10556                                     const SCEV *RHS,
10557                                     ICmpInst::Predicate FoundPred,
10558                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10559                                     const Instruction *Context) {
10560   // Balance the types.
10561   if (getTypeSizeInBits(LHS->getType()) <
10562       getTypeSizeInBits(FoundLHS->getType())) {
10563     // For unsigned and equality predicates, try to prove that both found
10564     // operands fit into narrow unsigned range. If so, try to prove facts in
10565     // narrow types.
10566     if (!CmpInst::isSigned(FoundPred)) {
10567       auto *NarrowType = LHS->getType();
10568       auto *WideType = FoundLHS->getType();
10569       auto BitWidth = getTypeSizeInBits(NarrowType);
10570       const SCEV *MaxValue = getZeroExtendExpr(
10571           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10572       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10573           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10574         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10575         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10576         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10577                                        TruncFoundRHS, Context))
10578           return true;
10579       }
10580     }
10581 
10582     if (CmpInst::isSigned(Pred)) {
10583       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10584       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10585     } else {
10586       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10587       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10588     }
10589   } else if (getTypeSizeInBits(LHS->getType()) >
10590       getTypeSizeInBits(FoundLHS->getType())) {
10591     if (CmpInst::isSigned(FoundPred)) {
10592       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10593       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10594     } else {
10595       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10596       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10597     }
10598   }
10599   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10600                                     FoundRHS, Context);
10601 }
10602 
10603 bool ScalarEvolution::isImpliedCondBalancedTypes(
10604     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10605     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10606     const Instruction *Context) {
10607   assert(getTypeSizeInBits(LHS->getType()) ==
10608              getTypeSizeInBits(FoundLHS->getType()) &&
10609          "Types should be balanced!");
10610   // Canonicalize the query to match the way instcombine will have
10611   // canonicalized the comparison.
10612   if (SimplifyICmpOperands(Pred, LHS, RHS))
10613     if (LHS == RHS)
10614       return CmpInst::isTrueWhenEqual(Pred);
10615   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10616     if (FoundLHS == FoundRHS)
10617       return CmpInst::isFalseWhenEqual(FoundPred);
10618 
10619   // Check to see if we can make the LHS or RHS match.
10620   if (LHS == FoundRHS || RHS == FoundLHS) {
10621     if (isa<SCEVConstant>(RHS)) {
10622       std::swap(FoundLHS, FoundRHS);
10623       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10624     } else {
10625       std::swap(LHS, RHS);
10626       Pred = ICmpInst::getSwappedPredicate(Pred);
10627     }
10628   }
10629 
10630   // Check whether the found predicate is the same as the desired predicate.
10631   if (FoundPred == Pred)
10632     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10633 
10634   // Check whether swapping the found predicate makes it the same as the
10635   // desired predicate.
10636   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10637     // We can write the implication
10638     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10639     // using one of the following ways:
10640     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10641     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10642     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10643     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10644     // Forms 1. and 2. require swapping the operands of one condition. Don't
10645     // do this if it would break canonical constant/addrec ordering.
10646     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10647       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10648                                    Context);
10649     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10650       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10651 
10652     // Don't try to getNotSCEV pointers.
10653     if (LHS->getType()->isPointerTy() || FoundLHS->getType()->isPointerTy())
10654       return false;
10655 
10656     // There's no clear preference between forms 3. and 4., try both.
10657     return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10658                                  FoundLHS, FoundRHS, Context) ||
10659            isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10660                                  getNotSCEV(FoundRHS), Context);
10661   }
10662 
10663   // Unsigned comparison is the same as signed comparison when both the operands
10664   // are non-negative.
10665   if (CmpInst::isUnsigned(FoundPred) &&
10666       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10667       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10668     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10669 
10670   // Check if we can make progress by sharpening ranges.
10671   if (FoundPred == ICmpInst::ICMP_NE &&
10672       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10673 
10674     const SCEVConstant *C = nullptr;
10675     const SCEV *V = nullptr;
10676 
10677     if (isa<SCEVConstant>(FoundLHS)) {
10678       C = cast<SCEVConstant>(FoundLHS);
10679       V = FoundRHS;
10680     } else {
10681       C = cast<SCEVConstant>(FoundRHS);
10682       V = FoundLHS;
10683     }
10684 
10685     // The guarding predicate tells us that C != V. If the known range
10686     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10687     // range we consider has to correspond to same signedness as the
10688     // predicate we're interested in folding.
10689 
10690     APInt Min = ICmpInst::isSigned(Pred) ?
10691         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10692 
10693     if (Min == C->getAPInt()) {
10694       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10695       // This is true even if (Min + 1) wraps around -- in case of
10696       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10697 
10698       APInt SharperMin = Min + 1;
10699 
10700       switch (Pred) {
10701         case ICmpInst::ICMP_SGE:
10702         case ICmpInst::ICMP_UGE:
10703           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10704           // RHS, we're done.
10705           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10706                                     Context))
10707             return true;
10708           LLVM_FALLTHROUGH;
10709 
10710         case ICmpInst::ICMP_SGT:
10711         case ICmpInst::ICMP_UGT:
10712           // We know from the range information that (V `Pred` Min ||
10713           // V == Min).  We know from the guarding condition that !(V
10714           // == Min).  This gives us
10715           //
10716           //       V `Pred` Min || V == Min && !(V == Min)
10717           //   =>  V `Pred` Min
10718           //
10719           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10720 
10721           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10722                                     Context))
10723             return true;
10724           break;
10725 
10726         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10727         case ICmpInst::ICMP_SLE:
10728         case ICmpInst::ICMP_ULE:
10729           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10730                                     LHS, V, getConstant(SharperMin), Context))
10731             return true;
10732           LLVM_FALLTHROUGH;
10733 
10734         case ICmpInst::ICMP_SLT:
10735         case ICmpInst::ICMP_ULT:
10736           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10737                                     LHS, V, getConstant(Min), Context))
10738             return true;
10739           break;
10740 
10741         default:
10742           // No change
10743           break;
10744       }
10745     }
10746   }
10747 
10748   // Check whether the actual condition is beyond sufficient.
10749   if (FoundPred == ICmpInst::ICMP_EQ)
10750     if (ICmpInst::isTrueWhenEqual(Pred))
10751       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10752         return true;
10753   if (Pred == ICmpInst::ICMP_NE)
10754     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10755       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10756                                 Context))
10757         return true;
10758 
10759   // Otherwise assume the worst.
10760   return false;
10761 }
10762 
10763 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10764                                      const SCEV *&L, const SCEV *&R,
10765                                      SCEV::NoWrapFlags &Flags) {
10766   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10767   if (!AE || AE->getNumOperands() != 2)
10768     return false;
10769 
10770   L = AE->getOperand(0);
10771   R = AE->getOperand(1);
10772   Flags = AE->getNoWrapFlags();
10773   return true;
10774 }
10775 
10776 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10777                                                            const SCEV *Less) {
10778   // We avoid subtracting expressions here because this function is usually
10779   // fairly deep in the call stack (i.e. is called many times).
10780 
10781   // X - X = 0.
10782   if (More == Less)
10783     return APInt(getTypeSizeInBits(More->getType()), 0);
10784 
10785   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10786     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10787     const auto *MAR = cast<SCEVAddRecExpr>(More);
10788 
10789     if (LAR->getLoop() != MAR->getLoop())
10790       return None;
10791 
10792     // We look at affine expressions only; not for correctness but to keep
10793     // getStepRecurrence cheap.
10794     if (!LAR->isAffine() || !MAR->isAffine())
10795       return None;
10796 
10797     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10798       return None;
10799 
10800     Less = LAR->getStart();
10801     More = MAR->getStart();
10802 
10803     // fall through
10804   }
10805 
10806   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10807     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10808     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10809     return M - L;
10810   }
10811 
10812   SCEV::NoWrapFlags Flags;
10813   const SCEV *LLess = nullptr, *RLess = nullptr;
10814   const SCEV *LMore = nullptr, *RMore = nullptr;
10815   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10816   // Compare (X + C1) vs X.
10817   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10818     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10819       if (RLess == More)
10820         return -(C1->getAPInt());
10821 
10822   // Compare X vs (X + C2).
10823   if (splitBinaryAdd(More, LMore, RMore, Flags))
10824     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10825       if (RMore == Less)
10826         return C2->getAPInt();
10827 
10828   // Compare (X + C1) vs (X + C2).
10829   if (C1 && C2 && RLess == RMore)
10830     return C2->getAPInt() - C1->getAPInt();
10831 
10832   return None;
10833 }
10834 
10835 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10836     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10837     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10838   // Try to recognize the following pattern:
10839   //
10840   //   FoundRHS = ...
10841   // ...
10842   // loop:
10843   //   FoundLHS = {Start,+,W}
10844   // context_bb: // Basic block from the same loop
10845   //   known(Pred, FoundLHS, FoundRHS)
10846   //
10847   // If some predicate is known in the context of a loop, it is also known on
10848   // each iteration of this loop, including the first iteration. Therefore, in
10849   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10850   // prove the original pred using this fact.
10851   if (!Context)
10852     return false;
10853   const BasicBlock *ContextBB = Context->getParent();
10854   // Make sure AR varies in the context block.
10855   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10856     const Loop *L = AR->getLoop();
10857     // Make sure that context belongs to the loop and executes on 1st iteration
10858     // (if it ever executes at all).
10859     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10860       return false;
10861     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10862       return false;
10863     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10864   }
10865 
10866   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10867     const Loop *L = AR->getLoop();
10868     // Make sure that context belongs to the loop and executes on 1st iteration
10869     // (if it ever executes at all).
10870     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10871       return false;
10872     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10873       return false;
10874     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10875   }
10876 
10877   return false;
10878 }
10879 
10880 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10881     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10882     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10883   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10884     return false;
10885 
10886   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10887   if (!AddRecLHS)
10888     return false;
10889 
10890   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10891   if (!AddRecFoundLHS)
10892     return false;
10893 
10894   // We'd like to let SCEV reason about control dependencies, so we constrain
10895   // both the inequalities to be about add recurrences on the same loop.  This
10896   // way we can use isLoopEntryGuardedByCond later.
10897 
10898   const Loop *L = AddRecFoundLHS->getLoop();
10899   if (L != AddRecLHS->getLoop())
10900     return false;
10901 
10902   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10903   //
10904   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10905   //                                                                  ... (2)
10906   //
10907   // Informal proof for (2), assuming (1) [*]:
10908   //
10909   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10910   //
10911   // Then
10912   //
10913   //       FoundLHS s< FoundRHS s< INT_MIN - C
10914   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10915   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10916   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10917   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10918   // <=>  FoundLHS + C s< FoundRHS + C
10919   //
10920   // [*]: (1) can be proved by ruling out overflow.
10921   //
10922   // [**]: This can be proved by analyzing all the four possibilities:
10923   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10924   //    (A s>= 0, B s>= 0).
10925   //
10926   // Note:
10927   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10928   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10929   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10930   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10931   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10932   // C)".
10933 
10934   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10935   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10936   if (!LDiff || !RDiff || *LDiff != *RDiff)
10937     return false;
10938 
10939   if (LDiff->isMinValue())
10940     return true;
10941 
10942   APInt FoundRHSLimit;
10943 
10944   if (Pred == CmpInst::ICMP_ULT) {
10945     FoundRHSLimit = -(*RDiff);
10946   } else {
10947     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10948     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10949   }
10950 
10951   // Try to prove (1) or (2), as needed.
10952   return isAvailableAtLoopEntry(FoundRHS, L) &&
10953          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10954                                   getConstant(FoundRHSLimit));
10955 }
10956 
10957 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10958                                         const SCEV *LHS, const SCEV *RHS,
10959                                         const SCEV *FoundLHS,
10960                                         const SCEV *FoundRHS, unsigned Depth) {
10961   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10962 
10963   auto ClearOnExit = make_scope_exit([&]() {
10964     if (LPhi) {
10965       bool Erased = PendingMerges.erase(LPhi);
10966       assert(Erased && "Failed to erase LPhi!");
10967       (void)Erased;
10968     }
10969     if (RPhi) {
10970       bool Erased = PendingMerges.erase(RPhi);
10971       assert(Erased && "Failed to erase RPhi!");
10972       (void)Erased;
10973     }
10974   });
10975 
10976   // Find respective Phis and check that they are not being pending.
10977   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10978     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10979       if (!PendingMerges.insert(Phi).second)
10980         return false;
10981       LPhi = Phi;
10982     }
10983   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10984     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10985       // If we detect a loop of Phi nodes being processed by this method, for
10986       // example:
10987       //
10988       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10989       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10990       //
10991       // we don't want to deal with a case that complex, so return conservative
10992       // answer false.
10993       if (!PendingMerges.insert(Phi).second)
10994         return false;
10995       RPhi = Phi;
10996     }
10997 
10998   // If none of LHS, RHS is a Phi, nothing to do here.
10999   if (!LPhi && !RPhi)
11000     return false;
11001 
11002   // If there is a SCEVUnknown Phi we are interested in, make it left.
11003   if (!LPhi) {
11004     std::swap(LHS, RHS);
11005     std::swap(FoundLHS, FoundRHS);
11006     std::swap(LPhi, RPhi);
11007     Pred = ICmpInst::getSwappedPredicate(Pred);
11008   }
11009 
11010   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11011   const BasicBlock *LBB = LPhi->getParent();
11012   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11013 
11014   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11015     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11016            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11017            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11018   };
11019 
11020   if (RPhi && RPhi->getParent() == LBB) {
11021     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11022     // If we compare two Phis from the same block, and for each entry block
11023     // the predicate is true for incoming values from this block, then the
11024     // predicate is also true for the Phis.
11025     for (const BasicBlock *IncBB : predecessors(LBB)) {
11026       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11027       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11028       if (!ProvedEasily(L, R))
11029         return false;
11030     }
11031   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11032     // Case two: RHS is also a Phi from the same basic block, and it is an
11033     // AddRec. It means that there is a loop which has both AddRec and Unknown
11034     // PHIs, for it we can compare incoming values of AddRec from above the loop
11035     // and latch with their respective incoming values of LPhi.
11036     // TODO: Generalize to handle loops with many inputs in a header.
11037     if (LPhi->getNumIncomingValues() != 2) return false;
11038 
11039     auto *RLoop = RAR->getLoop();
11040     auto *Predecessor = RLoop->getLoopPredecessor();
11041     assert(Predecessor && "Loop with AddRec with no predecessor?");
11042     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11043     if (!ProvedEasily(L1, RAR->getStart()))
11044       return false;
11045     auto *Latch = RLoop->getLoopLatch();
11046     assert(Latch && "Loop with AddRec with no latch?");
11047     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11048     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11049       return false;
11050   } else {
11051     // In all other cases go over inputs of LHS and compare each of them to RHS,
11052     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11053     // At this point RHS is either a non-Phi, or it is a Phi from some block
11054     // different from LBB.
11055     for (const BasicBlock *IncBB : predecessors(LBB)) {
11056       // Check that RHS is available in this block.
11057       if (!dominates(RHS, IncBB))
11058         return false;
11059       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11060       // Make sure L does not refer to a value from a potentially previous
11061       // iteration of a loop.
11062       if (!properlyDominates(L, IncBB))
11063         return false;
11064       if (!ProvedEasily(L, RHS))
11065         return false;
11066     }
11067   }
11068   return true;
11069 }
11070 
11071 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11072                                             const SCEV *LHS, const SCEV *RHS,
11073                                             const SCEV *FoundLHS,
11074                                             const SCEV *FoundRHS,
11075                                             const Instruction *Context) {
11076   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11077     return true;
11078 
11079   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11080     return true;
11081 
11082   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11083                                           Context))
11084     return true;
11085 
11086   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11087                                      FoundLHS, FoundRHS);
11088 }
11089 
11090 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11091 template <typename MinMaxExprType>
11092 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11093                                  const SCEV *Candidate) {
11094   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11095   if (!MinMaxExpr)
11096     return false;
11097 
11098   return is_contained(MinMaxExpr->operands(), Candidate);
11099 }
11100 
11101 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11102                                            ICmpInst::Predicate Pred,
11103                                            const SCEV *LHS, const SCEV *RHS) {
11104   // If both sides are affine addrecs for the same loop, with equal
11105   // steps, and we know the recurrences don't wrap, then we only
11106   // need to check the predicate on the starting values.
11107 
11108   if (!ICmpInst::isRelational(Pred))
11109     return false;
11110 
11111   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11112   if (!LAR)
11113     return false;
11114   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11115   if (!RAR)
11116     return false;
11117   if (LAR->getLoop() != RAR->getLoop())
11118     return false;
11119   if (!LAR->isAffine() || !RAR->isAffine())
11120     return false;
11121 
11122   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11123     return false;
11124 
11125   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11126                          SCEV::FlagNSW : SCEV::FlagNUW;
11127   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11128     return false;
11129 
11130   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11131 }
11132 
11133 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11134 /// expression?
11135 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11136                                         ICmpInst::Predicate Pred,
11137                                         const SCEV *LHS, const SCEV *RHS) {
11138   switch (Pred) {
11139   default:
11140     return false;
11141 
11142   case ICmpInst::ICMP_SGE:
11143     std::swap(LHS, RHS);
11144     LLVM_FALLTHROUGH;
11145   case ICmpInst::ICMP_SLE:
11146     return
11147         // min(A, ...) <= A
11148         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11149         // A <= max(A, ...)
11150         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11151 
11152   case ICmpInst::ICMP_UGE:
11153     std::swap(LHS, RHS);
11154     LLVM_FALLTHROUGH;
11155   case ICmpInst::ICMP_ULE:
11156     return
11157         // min(A, ...) <= A
11158         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11159         // A <= max(A, ...)
11160         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11161   }
11162 
11163   llvm_unreachable("covered switch fell through?!");
11164 }
11165 
11166 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11167                                              const SCEV *LHS, const SCEV *RHS,
11168                                              const SCEV *FoundLHS,
11169                                              const SCEV *FoundRHS,
11170                                              unsigned Depth) {
11171   assert(getTypeSizeInBits(LHS->getType()) ==
11172              getTypeSizeInBits(RHS->getType()) &&
11173          "LHS and RHS have different sizes?");
11174   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11175              getTypeSizeInBits(FoundRHS->getType()) &&
11176          "FoundLHS and FoundRHS have different sizes?");
11177   // We want to avoid hurting the compile time with analysis of too big trees.
11178   if (Depth > MaxSCEVOperationsImplicationDepth)
11179     return false;
11180 
11181   // We only want to work with GT comparison so far.
11182   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11183     Pred = CmpInst::getSwappedPredicate(Pred);
11184     std::swap(LHS, RHS);
11185     std::swap(FoundLHS, FoundRHS);
11186   }
11187 
11188   // For unsigned, try to reduce it to corresponding signed comparison.
11189   if (Pred == ICmpInst::ICMP_UGT)
11190     // We can replace unsigned predicate with its signed counterpart if all
11191     // involved values are non-negative.
11192     // TODO: We could have better support for unsigned.
11193     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11194       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11195       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11196       // use this fact to prove that LHS and RHS are non-negative.
11197       const SCEV *MinusOne = getMinusOne(LHS->getType());
11198       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11199                                 FoundRHS) &&
11200           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11201                                 FoundRHS))
11202         Pred = ICmpInst::ICMP_SGT;
11203     }
11204 
11205   if (Pred != ICmpInst::ICMP_SGT)
11206     return false;
11207 
11208   auto GetOpFromSExt = [&](const SCEV *S) {
11209     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11210       return Ext->getOperand();
11211     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11212     // the constant in some cases.
11213     return S;
11214   };
11215 
11216   // Acquire values from extensions.
11217   auto *OrigLHS = LHS;
11218   auto *OrigFoundLHS = FoundLHS;
11219   LHS = GetOpFromSExt(LHS);
11220   FoundLHS = GetOpFromSExt(FoundLHS);
11221 
11222   // Is the SGT predicate can be proved trivially or using the found context.
11223   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11224     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11225            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11226                                   FoundRHS, Depth + 1);
11227   };
11228 
11229   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11230     // We want to avoid creation of any new non-constant SCEV. Since we are
11231     // going to compare the operands to RHS, we should be certain that we don't
11232     // need any size extensions for this. So let's decline all cases when the
11233     // sizes of types of LHS and RHS do not match.
11234     // TODO: Maybe try to get RHS from sext to catch more cases?
11235     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11236       return false;
11237 
11238     // Should not overflow.
11239     if (!LHSAddExpr->hasNoSignedWrap())
11240       return false;
11241 
11242     auto *LL = LHSAddExpr->getOperand(0);
11243     auto *LR = LHSAddExpr->getOperand(1);
11244     auto *MinusOne = getMinusOne(RHS->getType());
11245 
11246     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11247     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11248       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11249     };
11250     // Try to prove the following rule:
11251     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11252     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11253     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11254       return true;
11255   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11256     Value *LL, *LR;
11257     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11258 
11259     using namespace llvm::PatternMatch;
11260 
11261     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11262       // Rules for division.
11263       // We are going to perform some comparisons with Denominator and its
11264       // derivative expressions. In general case, creating a SCEV for it may
11265       // lead to a complex analysis of the entire graph, and in particular it
11266       // can request trip count recalculation for the same loop. This would
11267       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11268       // this, we only want to create SCEVs that are constants in this section.
11269       // So we bail if Denominator is not a constant.
11270       if (!isa<ConstantInt>(LR))
11271         return false;
11272 
11273       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11274 
11275       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11276       // then a SCEV for the numerator already exists and matches with FoundLHS.
11277       auto *Numerator = getExistingSCEV(LL);
11278       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11279         return false;
11280 
11281       // Make sure that the numerator matches with FoundLHS and the denominator
11282       // is positive.
11283       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11284         return false;
11285 
11286       auto *DTy = Denominator->getType();
11287       auto *FRHSTy = FoundRHS->getType();
11288       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11289         // One of types is a pointer and another one is not. We cannot extend
11290         // them properly to a wider type, so let us just reject this case.
11291         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11292         // to avoid this check.
11293         return false;
11294 
11295       // Given that:
11296       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11297       auto *WTy = getWiderType(DTy, FRHSTy);
11298       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11299       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11300 
11301       // Try to prove the following rule:
11302       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11303       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11304       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11305       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11306       if (isKnownNonPositive(RHS) &&
11307           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11308         return true;
11309 
11310       // Try to prove the following rule:
11311       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11312       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11313       // If we divide it by Denominator > 2, then:
11314       // 1. If FoundLHS is negative, then the result is 0.
11315       // 2. If FoundLHS is non-negative, then the result is non-negative.
11316       // Anyways, the result is non-negative.
11317       auto *MinusOne = getMinusOne(WTy);
11318       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11319       if (isKnownNegative(RHS) &&
11320           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11321         return true;
11322     }
11323   }
11324 
11325   // If our expression contained SCEVUnknown Phis, and we split it down and now
11326   // need to prove something for them, try to prove the predicate for every
11327   // possible incoming values of those Phis.
11328   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11329     return true;
11330 
11331   return false;
11332 }
11333 
11334 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11335                                         const SCEV *LHS, const SCEV *RHS) {
11336   // zext x u<= sext x, sext x s<= zext x
11337   switch (Pred) {
11338   case ICmpInst::ICMP_SGE:
11339     std::swap(LHS, RHS);
11340     LLVM_FALLTHROUGH;
11341   case ICmpInst::ICMP_SLE: {
11342     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11343     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11344     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11345     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11346       return true;
11347     break;
11348   }
11349   case ICmpInst::ICMP_UGE:
11350     std::swap(LHS, RHS);
11351     LLVM_FALLTHROUGH;
11352   case ICmpInst::ICMP_ULE: {
11353     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11354     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11355     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11356     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11357       return true;
11358     break;
11359   }
11360   default:
11361     break;
11362   };
11363   return false;
11364 }
11365 
11366 bool
11367 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11368                                            const SCEV *LHS, const SCEV *RHS) {
11369   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11370          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11371          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11372          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11373          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11374 }
11375 
11376 bool
11377 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11378                                              const SCEV *LHS, const SCEV *RHS,
11379                                              const SCEV *FoundLHS,
11380                                              const SCEV *FoundRHS) {
11381   switch (Pred) {
11382   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11383   case ICmpInst::ICMP_EQ:
11384   case ICmpInst::ICMP_NE:
11385     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11386       return true;
11387     break;
11388   case ICmpInst::ICMP_SLT:
11389   case ICmpInst::ICMP_SLE:
11390     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11391         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11392       return true;
11393     break;
11394   case ICmpInst::ICMP_SGT:
11395   case ICmpInst::ICMP_SGE:
11396     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11397         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11398       return true;
11399     break;
11400   case ICmpInst::ICMP_ULT:
11401   case ICmpInst::ICMP_ULE:
11402     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11403         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11404       return true;
11405     break;
11406   case ICmpInst::ICMP_UGT:
11407   case ICmpInst::ICMP_UGE:
11408     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11409         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11410       return true;
11411     break;
11412   }
11413 
11414   // Maybe it can be proved via operations?
11415   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11416     return true;
11417 
11418   return false;
11419 }
11420 
11421 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11422                                                      const SCEV *LHS,
11423                                                      const SCEV *RHS,
11424                                                      const SCEV *FoundLHS,
11425                                                      const SCEV *FoundRHS) {
11426   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11427     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11428     // reduce the compile time impact of this optimization.
11429     return false;
11430 
11431   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11432   if (!Addend)
11433     return false;
11434 
11435   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11436 
11437   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11438   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11439   ConstantRange FoundLHSRange =
11440       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
11441 
11442   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11443   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11444 
11445   // We can also compute the range of values for `LHS` that satisfy the
11446   // consequent, "`LHS` `Pred` `RHS`":
11447   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11448   // The antecedent implies the consequent if every value of `LHS` that
11449   // satisfies the antecedent also satisfies the consequent.
11450   return LHSRange.icmp(Pred, ConstRHS);
11451 }
11452 
11453 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11454                                         bool IsSigned) {
11455   assert(isKnownPositive(Stride) && "Positive stride expected!");
11456 
11457   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11458   const SCEV *One = getOne(Stride->getType());
11459 
11460   if (IsSigned) {
11461     APInt MaxRHS = getSignedRangeMax(RHS);
11462     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11463     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11464 
11465     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11466     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11467   }
11468 
11469   APInt MaxRHS = getUnsignedRangeMax(RHS);
11470   APInt MaxValue = APInt::getMaxValue(BitWidth);
11471   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11472 
11473   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11474   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11475 }
11476 
11477 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11478                                         bool IsSigned) {
11479 
11480   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11481   const SCEV *One = getOne(Stride->getType());
11482 
11483   if (IsSigned) {
11484     APInt MinRHS = getSignedRangeMin(RHS);
11485     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11486     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11487 
11488     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11489     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11490   }
11491 
11492   APInt MinRHS = getUnsignedRangeMin(RHS);
11493   APInt MinValue = APInt::getMinValue(BitWidth);
11494   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11495 
11496   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11497   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11498 }
11499 
11500 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta,
11501                                             const SCEV *Step) {
11502   const SCEV *One = getOne(Step->getType());
11503   Delta = getAddExpr(Delta, getMinusSCEV(Step, One));
11504   return getUDivExpr(Delta, Step);
11505 }
11506 
11507 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11508                                                     const SCEV *Stride,
11509                                                     const SCEV *End,
11510                                                     unsigned BitWidth,
11511                                                     bool IsSigned) {
11512 
11513   assert(!isKnownNonPositive(Stride) &&
11514          "Stride is expected strictly positive!");
11515   // Calculate the maximum backedge count based on the range of values
11516   // permitted by Start, End, and Stride.
11517   const SCEV *MaxBECount;
11518   APInt MinStart =
11519       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11520 
11521   APInt StrideForMaxBECount =
11522       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11523 
11524   // We already know that the stride is positive, so we paper over conservatism
11525   // in our range computation by forcing StrideForMaxBECount to be at least one.
11526   // In theory this is unnecessary, but we expect MaxBECount to be a
11527   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11528   // is nothing to constant fold it to).
11529   APInt One(BitWidth, 1, IsSigned);
11530   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11531 
11532   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11533                             : APInt::getMaxValue(BitWidth);
11534   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11535 
11536   // Although End can be a MAX expression we estimate MaxEnd considering only
11537   // the case End = RHS of the loop termination condition. This is safe because
11538   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11539   // taken count.
11540   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11541                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11542 
11543   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11544                               getConstant(StrideForMaxBECount) /* Step */);
11545 
11546   return MaxBECount;
11547 }
11548 
11549 ScalarEvolution::ExitLimit
11550 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11551                                   const Loop *L, bool IsSigned,
11552                                   bool ControlsExit, bool AllowPredicates) {
11553   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11554 
11555   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11556   bool PredicatedIV = false;
11557 
11558   if (!IV && AllowPredicates) {
11559     // Try to make this an AddRec using runtime tests, in the first X
11560     // iterations of this loop, where X is the SCEV expression found by the
11561     // algorithm below.
11562     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11563     PredicatedIV = true;
11564   }
11565 
11566   // Avoid weird loops
11567   if (!IV || IV->getLoop() != L || !IV->isAffine())
11568     return getCouldNotCompute();
11569 
11570   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11571   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11572   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
11573 
11574   const SCEV *Stride = IV->getStepRecurrence(*this);
11575 
11576   bool PositiveStride = isKnownPositive(Stride);
11577 
11578   // Avoid negative or zero stride values.
11579   if (!PositiveStride) {
11580     // We can compute the correct backedge taken count for loops with unknown
11581     // strides if we can prove that the loop is not an infinite loop with side
11582     // effects. Here's the loop structure we are trying to handle -
11583     //
11584     // i = start
11585     // do {
11586     //   A[i] = i;
11587     //   i += s;
11588     // } while (i < end);
11589     //
11590     // The backedge taken count for such loops is evaluated as -
11591     // (max(end, start + stride) - start - 1) /u stride
11592     //
11593     // The additional preconditions that we need to check to prove correctness
11594     // of the above formula is as follows -
11595     //
11596     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11597     //    NoWrap flag).
11598     // b) loop is single exit with no side effects.
11599     //
11600     //
11601     // Precondition a) implies that if the stride is negative, this is a single
11602     // trip loop. The backedge taken count formula reduces to zero in this case.
11603     //
11604     // Precondition b) implies that the unknown stride cannot be zero otherwise
11605     // we have UB.
11606     //
11607     // The positive stride case is the same as isKnownPositive(Stride) returning
11608     // true (original behavior of the function).
11609     //
11610     // We want to make sure that the stride is truly unknown as there are edge
11611     // cases where ScalarEvolution propagates no wrap flags to the
11612     // post-increment/decrement IV even though the increment/decrement operation
11613     // itself is wrapping. The computed backedge taken count may be wrong in
11614     // such cases. This is prevented by checking that the stride is not known to
11615     // be either positive or non-positive. For example, no wrap flags are
11616     // propagated to the post-increment IV of this loop with a trip count of 2 -
11617     //
11618     // unsigned char i;
11619     // for(i=127; i<128; i+=129)
11620     //   A[i] = i;
11621     //
11622     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11623         !loopIsFiniteByAssumption(L))
11624       return getCouldNotCompute();
11625   } else if (!Stride->isOne() && !NoWrap) {
11626     auto isUBOnWrap = [&]() {
11627       // Can we prove this loop *must* be UB if overflow of IV occurs?
11628       // Reasoning goes as follows:
11629       // * Suppose the IV did self wrap.
11630       // * If Stride evenly divides the iteration space, then once wrap
11631       //   occurs, the loop must revisit the same values.
11632       // * We know that RHS is invariant, and that none of those values
11633       //   caused this exit to be taken previously.  Thus, this exit is
11634       //   dynamically dead.
11635       // * If this is the sole exit, then a dead exit implies the loop
11636       //   must be infinite if there are no abnormal exits.
11637       // * If the loop were infinite, then it must either not be mustprogress
11638       //   or have side effects. Otherwise, it must be UB.
11639       // * It can't (by assumption), be UB so we have contradicted our
11640       //   premise and can conclude the IV did not in fact self-wrap.
11641       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
11642       // follows trivially from the fact that every (un)signed-wrapped, but
11643       // not self-wrapped value must be LT than the last value before
11644       // (un)signed wrap.  Since we know that last value didn't exit, nor
11645       // will any smaller one.
11646 
11647       if (!isLoopInvariant(RHS, L))
11648         return false;
11649 
11650       auto *StrideC = dyn_cast<SCEVConstant>(Stride);
11651       if (!StrideC || !StrideC->getAPInt().isPowerOf2())
11652         return false;
11653 
11654       if (!ControlsExit || !loopHasNoAbnormalExits(L))
11655         return false;
11656 
11657       return loopIsFiniteByAssumption(L);
11658     };
11659 
11660     // Avoid proven overflow cases: this will ensure that the backedge taken
11661     // count will not generate any unsigned overflow. Relaxed no-overflow
11662     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11663     // undefined behaviors like the case of C language.
11664     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
11665       return getCouldNotCompute();
11666   }
11667 
11668   const SCEV *Start = IV->getStart();
11669 
11670   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
11671   // Use integer-typed versions for actual computation.
11672   const SCEV *OrigStart = Start;
11673   const SCEV *OrigRHS = RHS;
11674   if (Start->getType()->isPointerTy()) {
11675     Start = getLosslessPtrToIntExpr(Start);
11676     if (isa<SCEVCouldNotCompute>(Start))
11677       return Start;
11678   }
11679   if (RHS->getType()->isPointerTy()) {
11680     RHS = getLosslessPtrToIntExpr(RHS);
11681     if (isa<SCEVCouldNotCompute>(RHS))
11682       return RHS;
11683   }
11684 
11685   const SCEV *End = RHS;
11686   // When the RHS is not invariant, we do not know the end bound of the loop and
11687   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11688   // calculate the MaxBECount, given the start, stride and max value for the end
11689   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11690   // checked above).
11691   if (!isLoopInvariant(RHS, L)) {
11692     const SCEV *MaxBECount = computeMaxBECountForLT(
11693         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11694     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11695                      false /*MaxOrZero*/, Predicates);
11696   }
11697   // If the backedge is taken at least once, then it will be taken
11698   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11699   // is the LHS value of the less-than comparison the first time it is evaluated
11700   // and End is the RHS.
11701   const SCEV *BECountIfBackedgeTaken =
11702     computeBECount(getMinusSCEV(End, Start), Stride);
11703   // If the loop entry is guarded by the result of the backedge test of the
11704   // first loop iteration, then we know the backedge will be taken at least
11705   // once and so the backedge taken count is as above. If not then we use the
11706   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11707   // as if the backedge is taken at least once max(End,Start) is End and so the
11708   // result is as above, and if not max(End,Start) is Start so we get a backedge
11709   // count of zero.
11710   const SCEV *BECount;
11711   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(OrigStart, Stride), OrigRHS))
11712     BECount = BECountIfBackedgeTaken;
11713   else {
11714     // If we know that RHS >= Start in the context of loop, then we know that
11715     // max(RHS, Start) = RHS at this point.
11716     if (isLoopEntryGuardedByCond(
11717             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, OrigRHS, OrigStart))
11718       End = RHS;
11719     else
11720       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11721     BECount = computeBECount(getMinusSCEV(End, Start), Stride);
11722   }
11723 
11724   const SCEV *MaxBECount;
11725   bool MaxOrZero = false;
11726   if (isa<SCEVConstant>(BECount))
11727     MaxBECount = BECount;
11728   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11729     // If we know exactly how many times the backedge will be taken if it's
11730     // taken at least once, then the backedge count will either be that or
11731     // zero.
11732     MaxBECount = BECountIfBackedgeTaken;
11733     MaxOrZero = true;
11734   } else {
11735     MaxBECount = computeMaxBECountForLT(
11736         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11737   }
11738 
11739   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11740       !isa<SCEVCouldNotCompute>(BECount))
11741     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11742 
11743   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11744 }
11745 
11746 ScalarEvolution::ExitLimit
11747 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11748                                      const Loop *L, bool IsSigned,
11749                                      bool ControlsExit, bool AllowPredicates) {
11750   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11751   // We handle only IV > Invariant
11752   if (!isLoopInvariant(RHS, L))
11753     return getCouldNotCompute();
11754 
11755   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11756   if (!IV && AllowPredicates)
11757     // Try to make this an AddRec using runtime tests, in the first X
11758     // iterations of this loop, where X is the SCEV expression found by the
11759     // algorithm below.
11760     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11761 
11762   // Avoid weird loops
11763   if (!IV || IV->getLoop() != L || !IV->isAffine())
11764     return getCouldNotCompute();
11765 
11766   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
11767   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
11768   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
11769 
11770   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11771 
11772   // Avoid negative or zero stride values
11773   if (!isKnownPositive(Stride))
11774     return getCouldNotCompute();
11775 
11776   // Avoid proven overflow cases: this will ensure that the backedge taken count
11777   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11778   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11779   // behaviors like the case of C language.
11780   if (!Stride->isOne() && !NoWrap)
11781     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
11782       return getCouldNotCompute();
11783 
11784   const SCEV *Start = IV->getStart();
11785   const SCEV *End = RHS;
11786   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11787     // If we know that Start >= RHS in the context of loop, then we know that
11788     // min(RHS, Start) = RHS at this point.
11789     if (isLoopEntryGuardedByCond(
11790             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11791       End = RHS;
11792     else
11793       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11794   }
11795 
11796   if (Start->getType()->isPointerTy()) {
11797     Start = getLosslessPtrToIntExpr(Start);
11798     if (isa<SCEVCouldNotCompute>(Start))
11799       return Start;
11800   }
11801   if (End->getType()->isPointerTy()) {
11802     End = getLosslessPtrToIntExpr(End);
11803     if (isa<SCEVCouldNotCompute>(End))
11804       return End;
11805   }
11806 
11807   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride);
11808 
11809   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11810                             : getUnsignedRangeMax(Start);
11811 
11812   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11813                              : getUnsignedRangeMin(Stride);
11814 
11815   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11816   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11817                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11818 
11819   // Although End can be a MIN expression we estimate MinEnd considering only
11820   // the case End = RHS. This is safe because in the other case (Start - End)
11821   // is zero, leading to a zero maximum backedge taken count.
11822   APInt MinEnd =
11823     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11824              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11825 
11826   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11827                                ? BECount
11828                                : computeBECount(getConstant(MaxStart - MinEnd),
11829                                                 getConstant(MinStride));
11830 
11831   if (isa<SCEVCouldNotCompute>(MaxBECount))
11832     MaxBECount = BECount;
11833 
11834   return ExitLimit(BECount, MaxBECount, false, Predicates);
11835 }
11836 
11837 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11838                                                     ScalarEvolution &SE) const {
11839   if (Range.isFullSet())  // Infinite loop.
11840     return SE.getCouldNotCompute();
11841 
11842   // If the start is a non-zero constant, shift the range to simplify things.
11843   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11844     if (!SC->getValue()->isZero()) {
11845       SmallVector<const SCEV *, 4> Operands(operands());
11846       Operands[0] = SE.getZero(SC->getType());
11847       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11848                                              getNoWrapFlags(FlagNW));
11849       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11850         return ShiftedAddRec->getNumIterationsInRange(
11851             Range.subtract(SC->getAPInt()), SE);
11852       // This is strange and shouldn't happen.
11853       return SE.getCouldNotCompute();
11854     }
11855 
11856   // The only time we can solve this is when we have all constant indices.
11857   // Otherwise, we cannot determine the overflow conditions.
11858   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11859     return SE.getCouldNotCompute();
11860 
11861   // Okay at this point we know that all elements of the chrec are constants and
11862   // that the start element is zero.
11863 
11864   // First check to see if the range contains zero.  If not, the first
11865   // iteration exits.
11866   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11867   if (!Range.contains(APInt(BitWidth, 0)))
11868     return SE.getZero(getType());
11869 
11870   if (isAffine()) {
11871     // If this is an affine expression then we have this situation:
11872     //   Solve {0,+,A} in Range  ===  Ax in Range
11873 
11874     // We know that zero is in the range.  If A is positive then we know that
11875     // the upper value of the range must be the first possible exit value.
11876     // If A is negative then the lower of the range is the last possible loop
11877     // value.  Also note that we already checked for a full range.
11878     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11879     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11880 
11881     // The exit value should be (End+A)/A.
11882     APInt ExitVal = (End + A).udiv(A);
11883     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11884 
11885     // Evaluate at the exit value.  If we really did fall out of the valid
11886     // range, then we computed our trip count, otherwise wrap around or other
11887     // things must have happened.
11888     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11889     if (Range.contains(Val->getValue()))
11890       return SE.getCouldNotCompute();  // Something strange happened
11891 
11892     // Ensure that the previous value is in the range.  This is a sanity check.
11893     assert(Range.contains(
11894            EvaluateConstantChrecAtConstant(this,
11895            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11896            "Linear scev computation is off in a bad way!");
11897     return SE.getConstant(ExitValue);
11898   }
11899 
11900   if (isQuadratic()) {
11901     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11902       return SE.getConstant(S.getValue());
11903   }
11904 
11905   return SE.getCouldNotCompute();
11906 }
11907 
11908 const SCEVAddRecExpr *
11909 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11910   assert(getNumOperands() > 1 && "AddRec with zero step?");
11911   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11912   // but in this case we cannot guarantee that the value returned will be an
11913   // AddRec because SCEV does not have a fixed point where it stops
11914   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11915   // may happen if we reach arithmetic depth limit while simplifying. So we
11916   // construct the returned value explicitly.
11917   SmallVector<const SCEV *, 3> Ops;
11918   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11919   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11920   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11921     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11922   // We know that the last operand is not a constant zero (otherwise it would
11923   // have been popped out earlier). This guarantees us that if the result has
11924   // the same last operand, then it will also not be popped out, meaning that
11925   // the returned value will be an AddRec.
11926   const SCEV *Last = getOperand(getNumOperands() - 1);
11927   assert(!Last->isZero() && "Recurrency with zero step?");
11928   Ops.push_back(Last);
11929   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11930                                                SCEV::FlagAnyWrap));
11931 }
11932 
11933 // Return true when S contains at least an undef value.
11934 static inline bool containsUndefs(const SCEV *S) {
11935   return SCEVExprContains(S, [](const SCEV *S) {
11936     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11937       return isa<UndefValue>(SU->getValue());
11938     return false;
11939   });
11940 }
11941 
11942 namespace {
11943 
11944 // Collect all steps of SCEV expressions.
11945 struct SCEVCollectStrides {
11946   ScalarEvolution &SE;
11947   SmallVectorImpl<const SCEV *> &Strides;
11948 
11949   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11950       : SE(SE), Strides(S) {}
11951 
11952   bool follow(const SCEV *S) {
11953     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11954       Strides.push_back(AR->getStepRecurrence(SE));
11955     return true;
11956   }
11957 
11958   bool isDone() const { return false; }
11959 };
11960 
11961 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11962 struct SCEVCollectTerms {
11963   SmallVectorImpl<const SCEV *> &Terms;
11964 
11965   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11966 
11967   bool follow(const SCEV *S) {
11968     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11969         isa<SCEVSignExtendExpr>(S)) {
11970       if (!containsUndefs(S))
11971         Terms.push_back(S);
11972 
11973       // Stop recursion: once we collected a term, do not walk its operands.
11974       return false;
11975     }
11976 
11977     // Keep looking.
11978     return true;
11979   }
11980 
11981   bool isDone() const { return false; }
11982 };
11983 
11984 // Check if a SCEV contains an AddRecExpr.
11985 struct SCEVHasAddRec {
11986   bool &ContainsAddRec;
11987 
11988   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11989     ContainsAddRec = false;
11990   }
11991 
11992   bool follow(const SCEV *S) {
11993     if (isa<SCEVAddRecExpr>(S)) {
11994       ContainsAddRec = true;
11995 
11996       // Stop recursion: once we collected a term, do not walk its operands.
11997       return false;
11998     }
11999 
12000     // Keep looking.
12001     return true;
12002   }
12003 
12004   bool isDone() const { return false; }
12005 };
12006 
12007 // Find factors that are multiplied with an expression that (possibly as a
12008 // subexpression) contains an AddRecExpr. In the expression:
12009 //
12010 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
12011 //
12012 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
12013 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
12014 // parameters as they form a product with an induction variable.
12015 //
12016 // This collector expects all array size parameters to be in the same MulExpr.
12017 // It might be necessary to later add support for collecting parameters that are
12018 // spread over different nested MulExpr.
12019 struct SCEVCollectAddRecMultiplies {
12020   SmallVectorImpl<const SCEV *> &Terms;
12021   ScalarEvolution &SE;
12022 
12023   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
12024       : Terms(T), SE(SE) {}
12025 
12026   bool follow(const SCEV *S) {
12027     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
12028       bool HasAddRec = false;
12029       SmallVector<const SCEV *, 0> Operands;
12030       for (auto Op : Mul->operands()) {
12031         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
12032         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
12033           Operands.push_back(Op);
12034         } else if (Unknown) {
12035           HasAddRec = true;
12036         } else {
12037           bool ContainsAddRec = false;
12038           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
12039           visitAll(Op, ContiansAddRec);
12040           HasAddRec |= ContainsAddRec;
12041         }
12042       }
12043       if (Operands.size() == 0)
12044         return true;
12045 
12046       if (!HasAddRec)
12047         return false;
12048 
12049       Terms.push_back(SE.getMulExpr(Operands));
12050       // Stop recursion: once we collected a term, do not walk its operands.
12051       return false;
12052     }
12053 
12054     // Keep looking.
12055     return true;
12056   }
12057 
12058   bool isDone() const { return false; }
12059 };
12060 
12061 } // end anonymous namespace
12062 
12063 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
12064 /// two places:
12065 ///   1) The strides of AddRec expressions.
12066 ///   2) Unknowns that are multiplied with AddRec expressions.
12067 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
12068     SmallVectorImpl<const SCEV *> &Terms) {
12069   SmallVector<const SCEV *, 4> Strides;
12070   SCEVCollectStrides StrideCollector(*this, Strides);
12071   visitAll(Expr, StrideCollector);
12072 
12073   LLVM_DEBUG({
12074     dbgs() << "Strides:\n";
12075     for (const SCEV *S : Strides)
12076       dbgs() << *S << "\n";
12077   });
12078 
12079   for (const SCEV *S : Strides) {
12080     SCEVCollectTerms TermCollector(Terms);
12081     visitAll(S, TermCollector);
12082   }
12083 
12084   LLVM_DEBUG({
12085     dbgs() << "Terms:\n";
12086     for (const SCEV *T : Terms)
12087       dbgs() << *T << "\n";
12088   });
12089 
12090   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
12091   visitAll(Expr, MulCollector);
12092 }
12093 
12094 static bool findArrayDimensionsRec(ScalarEvolution &SE,
12095                                    SmallVectorImpl<const SCEV *> &Terms,
12096                                    SmallVectorImpl<const SCEV *> &Sizes) {
12097   int Last = Terms.size() - 1;
12098   const SCEV *Step = Terms[Last];
12099 
12100   // End of recursion.
12101   if (Last == 0) {
12102     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
12103       SmallVector<const SCEV *, 2> Qs;
12104       for (const SCEV *Op : M->operands())
12105         if (!isa<SCEVConstant>(Op))
12106           Qs.push_back(Op);
12107 
12108       Step = SE.getMulExpr(Qs);
12109     }
12110 
12111     Sizes.push_back(Step);
12112     return true;
12113   }
12114 
12115   for (const SCEV *&Term : Terms) {
12116     // Normalize the terms before the next call to findArrayDimensionsRec.
12117     const SCEV *Q, *R;
12118     SCEVDivision::divide(SE, Term, Step, &Q, &R);
12119 
12120     // Bail out when GCD does not evenly divide one of the terms.
12121     if (!R->isZero())
12122       return false;
12123 
12124     Term = Q;
12125   }
12126 
12127   // Remove all SCEVConstants.
12128   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
12129 
12130   if (Terms.size() > 0)
12131     if (!findArrayDimensionsRec(SE, Terms, Sizes))
12132       return false;
12133 
12134   Sizes.push_back(Step);
12135   return true;
12136 }
12137 
12138 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
12139 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
12140   for (const SCEV *T : Terms)
12141     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
12142       return true;
12143 
12144   return false;
12145 }
12146 
12147 // Return the number of product terms in S.
12148 static inline int numberOfTerms(const SCEV *S) {
12149   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
12150     return Expr->getNumOperands();
12151   return 1;
12152 }
12153 
12154 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
12155   if (isa<SCEVConstant>(T))
12156     return nullptr;
12157 
12158   if (isa<SCEVUnknown>(T))
12159     return T;
12160 
12161   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
12162     SmallVector<const SCEV *, 2> Factors;
12163     for (const SCEV *Op : M->operands())
12164       if (!isa<SCEVConstant>(Op))
12165         Factors.push_back(Op);
12166 
12167     return SE.getMulExpr(Factors);
12168   }
12169 
12170   return T;
12171 }
12172 
12173 /// Return the size of an element read or written by Inst.
12174 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12175   Type *Ty;
12176   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12177     Ty = Store->getValueOperand()->getType();
12178   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12179     Ty = Load->getType();
12180   else
12181     return nullptr;
12182 
12183   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12184   return getSizeOfExpr(ETy, Ty);
12185 }
12186 
12187 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
12188                                           SmallVectorImpl<const SCEV *> &Sizes,
12189                                           const SCEV *ElementSize) {
12190   if (Terms.size() < 1 || !ElementSize)
12191     return;
12192 
12193   // Early return when Terms do not contain parameters: we do not delinearize
12194   // non parametric SCEVs.
12195   if (!containsParameters(Terms))
12196     return;
12197 
12198   LLVM_DEBUG({
12199     dbgs() << "Terms:\n";
12200     for (const SCEV *T : Terms)
12201       dbgs() << *T << "\n";
12202   });
12203 
12204   // Remove duplicates.
12205   array_pod_sort(Terms.begin(), Terms.end());
12206   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
12207 
12208   // Put larger terms first.
12209   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
12210     return numberOfTerms(LHS) > numberOfTerms(RHS);
12211   });
12212 
12213   // Try to divide all terms by the element size. If term is not divisible by
12214   // element size, proceed with the original term.
12215   for (const SCEV *&Term : Terms) {
12216     const SCEV *Q, *R;
12217     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
12218     if (!Q->isZero())
12219       Term = Q;
12220   }
12221 
12222   SmallVector<const SCEV *, 4> NewTerms;
12223 
12224   // Remove constant factors.
12225   for (const SCEV *T : Terms)
12226     if (const SCEV *NewT = removeConstantFactors(*this, T))
12227       NewTerms.push_back(NewT);
12228 
12229   LLVM_DEBUG({
12230     dbgs() << "Terms after sorting:\n";
12231     for (const SCEV *T : NewTerms)
12232       dbgs() << *T << "\n";
12233   });
12234 
12235   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
12236     Sizes.clear();
12237     return;
12238   }
12239 
12240   // The last element to be pushed into Sizes is the size of an element.
12241   Sizes.push_back(ElementSize);
12242 
12243   LLVM_DEBUG({
12244     dbgs() << "Sizes:\n";
12245     for (const SCEV *S : Sizes)
12246       dbgs() << *S << "\n";
12247   });
12248 }
12249 
12250 void ScalarEvolution::computeAccessFunctions(
12251     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
12252     SmallVectorImpl<const SCEV *> &Sizes) {
12253   // Early exit in case this SCEV is not an affine multivariate function.
12254   if (Sizes.empty())
12255     return;
12256 
12257   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
12258     if (!AR->isAffine())
12259       return;
12260 
12261   const SCEV *Res = Expr;
12262   int Last = Sizes.size() - 1;
12263   for (int i = Last; i >= 0; i--) {
12264     const SCEV *Q, *R;
12265     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
12266 
12267     LLVM_DEBUG({
12268       dbgs() << "Res: " << *Res << "\n";
12269       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
12270       dbgs() << "Res divided by Sizes[i]:\n";
12271       dbgs() << "Quotient: " << *Q << "\n";
12272       dbgs() << "Remainder: " << *R << "\n";
12273     });
12274 
12275     Res = Q;
12276 
12277     // Do not record the last subscript corresponding to the size of elements in
12278     // the array.
12279     if (i == Last) {
12280 
12281       // Bail out if the remainder is too complex.
12282       if (isa<SCEVAddRecExpr>(R)) {
12283         Subscripts.clear();
12284         Sizes.clear();
12285         return;
12286       }
12287 
12288       continue;
12289     }
12290 
12291     // Record the access function for the current subscript.
12292     Subscripts.push_back(R);
12293   }
12294 
12295   // Also push in last position the remainder of the last division: it will be
12296   // the access function of the innermost dimension.
12297   Subscripts.push_back(Res);
12298 
12299   std::reverse(Subscripts.begin(), Subscripts.end());
12300 
12301   LLVM_DEBUG({
12302     dbgs() << "Subscripts:\n";
12303     for (const SCEV *S : Subscripts)
12304       dbgs() << *S << "\n";
12305   });
12306 }
12307 
12308 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
12309 /// sizes of an array access. Returns the remainder of the delinearization that
12310 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
12311 /// the multiples of SCEV coefficients: that is a pattern matching of sub
12312 /// expressions in the stride and base of a SCEV corresponding to the
12313 /// computation of a GCD (greatest common divisor) of base and stride.  When
12314 /// SCEV->delinearize fails, it returns the SCEV unchanged.
12315 ///
12316 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
12317 ///
12318 ///  void foo(long n, long m, long o, double A[n][m][o]) {
12319 ///
12320 ///    for (long i = 0; i < n; i++)
12321 ///      for (long j = 0; j < m; j++)
12322 ///        for (long k = 0; k < o; k++)
12323 ///          A[i][j][k] = 1.0;
12324 ///  }
12325 ///
12326 /// the delinearization input is the following AddRec SCEV:
12327 ///
12328 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
12329 ///
12330 /// From this SCEV, we are able to say that the base offset of the access is %A
12331 /// because it appears as an offset that does not divide any of the strides in
12332 /// the loops:
12333 ///
12334 ///  CHECK: Base offset: %A
12335 ///
12336 /// and then SCEV->delinearize determines the size of some of the dimensions of
12337 /// the array as these are the multiples by which the strides are happening:
12338 ///
12339 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
12340 ///
12341 /// Note that the outermost dimension remains of UnknownSize because there are
12342 /// no strides that would help identifying the size of the last dimension: when
12343 /// the array has been statically allocated, one could compute the size of that
12344 /// dimension by dividing the overall size of the array by the size of the known
12345 /// dimensions: %m * %o * 8.
12346 ///
12347 /// Finally delinearize provides the access functions for the array reference
12348 /// that does correspond to A[i][j][k] of the above C testcase:
12349 ///
12350 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
12351 ///
12352 /// The testcases are checking the output of a function pass:
12353 /// DelinearizationPass that walks through all loads and stores of a function
12354 /// asking for the SCEV of the memory access with respect to all enclosing
12355 /// loops, calling SCEV->delinearize on that and printing the results.
12356 void ScalarEvolution::delinearize(const SCEV *Expr,
12357                                  SmallVectorImpl<const SCEV *> &Subscripts,
12358                                  SmallVectorImpl<const SCEV *> &Sizes,
12359                                  const SCEV *ElementSize) {
12360   // First step: collect parametric terms.
12361   SmallVector<const SCEV *, 4> Terms;
12362   collectParametricTerms(Expr, Terms);
12363 
12364   if (Terms.empty())
12365     return;
12366 
12367   // Second step: find subscript sizes.
12368   findArrayDimensions(Terms, Sizes, ElementSize);
12369 
12370   if (Sizes.empty())
12371     return;
12372 
12373   // Third step: compute the access functions for each subscript.
12374   computeAccessFunctions(Expr, Subscripts, Sizes);
12375 
12376   if (Subscripts.empty())
12377     return;
12378 
12379   LLVM_DEBUG({
12380     dbgs() << "succeeded to delinearize " << *Expr << "\n";
12381     dbgs() << "ArrayDecl[UnknownSize]";
12382     for (const SCEV *S : Sizes)
12383       dbgs() << "[" << *S << "]";
12384 
12385     dbgs() << "\nArrayRef";
12386     for (const SCEV *S : Subscripts)
12387       dbgs() << "[" << *S << "]";
12388     dbgs() << "\n";
12389   });
12390 }
12391 
12392 bool ScalarEvolution::getIndexExpressionsFromGEP(
12393     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
12394     SmallVectorImpl<int> &Sizes) {
12395   assert(Subscripts.empty() && Sizes.empty() &&
12396          "Expected output lists to be empty on entry to this function.");
12397   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
12398   Type *Ty = GEP->getPointerOperandType();
12399   bool DroppedFirstDim = false;
12400   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
12401     const SCEV *Expr = getSCEV(GEP->getOperand(i));
12402     if (i == 1) {
12403       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
12404         Ty = PtrTy->getElementType();
12405       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
12406         Ty = ArrayTy->getElementType();
12407       } else {
12408         Subscripts.clear();
12409         Sizes.clear();
12410         return false;
12411       }
12412       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
12413         if (Const->getValue()->isZero()) {
12414           DroppedFirstDim = true;
12415           continue;
12416         }
12417       Subscripts.push_back(Expr);
12418       continue;
12419     }
12420 
12421     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
12422     if (!ArrayTy) {
12423       Subscripts.clear();
12424       Sizes.clear();
12425       return false;
12426     }
12427 
12428     Subscripts.push_back(Expr);
12429     if (!(DroppedFirstDim && i == 2))
12430       Sizes.push_back(ArrayTy->getNumElements());
12431 
12432     Ty = ArrayTy->getElementType();
12433   }
12434   return !Subscripts.empty();
12435 }
12436 
12437 //===----------------------------------------------------------------------===//
12438 //                   SCEVCallbackVH Class Implementation
12439 //===----------------------------------------------------------------------===//
12440 
12441 void ScalarEvolution::SCEVCallbackVH::deleted() {
12442   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12443   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12444     SE->ConstantEvolutionLoopExitValue.erase(PN);
12445   SE->eraseValueFromMap(getValPtr());
12446   // this now dangles!
12447 }
12448 
12449 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12450   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12451 
12452   // Forget all the expressions associated with users of the old value,
12453   // so that future queries will recompute the expressions using the new
12454   // value.
12455   Value *Old = getValPtr();
12456   SmallVector<User *, 16> Worklist(Old->users());
12457   SmallPtrSet<User *, 8> Visited;
12458   while (!Worklist.empty()) {
12459     User *U = Worklist.pop_back_val();
12460     // Deleting the Old value will cause this to dangle. Postpone
12461     // that until everything else is done.
12462     if (U == Old)
12463       continue;
12464     if (!Visited.insert(U).second)
12465       continue;
12466     if (PHINode *PN = dyn_cast<PHINode>(U))
12467       SE->ConstantEvolutionLoopExitValue.erase(PN);
12468     SE->eraseValueFromMap(U);
12469     llvm::append_range(Worklist, U->users());
12470   }
12471   // Delete the Old value.
12472   if (PHINode *PN = dyn_cast<PHINode>(Old))
12473     SE->ConstantEvolutionLoopExitValue.erase(PN);
12474   SE->eraseValueFromMap(Old);
12475   // this now dangles!
12476 }
12477 
12478 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12479   : CallbackVH(V), SE(se) {}
12480 
12481 //===----------------------------------------------------------------------===//
12482 //                   ScalarEvolution Class Implementation
12483 //===----------------------------------------------------------------------===//
12484 
12485 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12486                                  AssumptionCache &AC, DominatorTree &DT,
12487                                  LoopInfo &LI)
12488     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12489       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12490       LoopDispositions(64), BlockDispositions(64) {
12491   // To use guards for proving predicates, we need to scan every instruction in
12492   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12493   // time if the IR does not actually contain any calls to
12494   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12495   //
12496   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12497   // to _add_ guards to the module when there weren't any before, and wants
12498   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12499   // efficient in lieu of being smart in that rather obscure case.
12500 
12501   auto *GuardDecl = F.getParent()->getFunction(
12502       Intrinsic::getName(Intrinsic::experimental_guard));
12503   HasGuards = GuardDecl && !GuardDecl->use_empty();
12504 }
12505 
12506 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12507     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12508       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12509       ValueExprMap(std::move(Arg.ValueExprMap)),
12510       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12511       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12512       PendingMerges(std::move(Arg.PendingMerges)),
12513       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12514       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12515       PredicatedBackedgeTakenCounts(
12516           std::move(Arg.PredicatedBackedgeTakenCounts)),
12517       ConstantEvolutionLoopExitValue(
12518           std::move(Arg.ConstantEvolutionLoopExitValue)),
12519       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12520       LoopDispositions(std::move(Arg.LoopDispositions)),
12521       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12522       BlockDispositions(std::move(Arg.BlockDispositions)),
12523       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12524       SignedRanges(std::move(Arg.SignedRanges)),
12525       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12526       UniquePreds(std::move(Arg.UniquePreds)),
12527       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12528       LoopUsers(std::move(Arg.LoopUsers)),
12529       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12530       FirstUnknown(Arg.FirstUnknown) {
12531   Arg.FirstUnknown = nullptr;
12532 }
12533 
12534 ScalarEvolution::~ScalarEvolution() {
12535   // Iterate through all the SCEVUnknown instances and call their
12536   // destructors, so that they release their references to their values.
12537   for (SCEVUnknown *U = FirstUnknown; U;) {
12538     SCEVUnknown *Tmp = U;
12539     U = U->Next;
12540     Tmp->~SCEVUnknown();
12541   }
12542   FirstUnknown = nullptr;
12543 
12544   ExprValueMap.clear();
12545   ValueExprMap.clear();
12546   HasRecMap.clear();
12547   BackedgeTakenCounts.clear();
12548   PredicatedBackedgeTakenCounts.clear();
12549 
12550   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12551   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12552   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12553   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12554   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12555 }
12556 
12557 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12558   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12559 }
12560 
12561 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12562                           const Loop *L) {
12563   // Print all inner loops first
12564   for (Loop *I : *L)
12565     PrintLoopInfo(OS, SE, I);
12566 
12567   OS << "Loop ";
12568   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12569   OS << ": ";
12570 
12571   SmallVector<BasicBlock *, 8> ExitingBlocks;
12572   L->getExitingBlocks(ExitingBlocks);
12573   if (ExitingBlocks.size() != 1)
12574     OS << "<multiple exits> ";
12575 
12576   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12577     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12578   else
12579     OS << "Unpredictable backedge-taken count.\n";
12580 
12581   if (ExitingBlocks.size() > 1)
12582     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12583       OS << "  exit count for " << ExitingBlock->getName() << ": "
12584          << *SE->getExitCount(L, ExitingBlock) << "\n";
12585     }
12586 
12587   OS << "Loop ";
12588   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12589   OS << ": ";
12590 
12591   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12592     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12593     if (SE->isBackedgeTakenCountMaxOrZero(L))
12594       OS << ", actual taken count either this or zero.";
12595   } else {
12596     OS << "Unpredictable max backedge-taken count. ";
12597   }
12598 
12599   OS << "\n"
12600         "Loop ";
12601   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12602   OS << ": ";
12603 
12604   SCEVUnionPredicate Pred;
12605   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12606   if (!isa<SCEVCouldNotCompute>(PBT)) {
12607     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12608     OS << " Predicates:\n";
12609     Pred.print(OS, 4);
12610   } else {
12611     OS << "Unpredictable predicated backedge-taken count. ";
12612   }
12613   OS << "\n";
12614 
12615   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12616     OS << "Loop ";
12617     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12618     OS << ": ";
12619     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12620   }
12621 }
12622 
12623 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12624   switch (LD) {
12625   case ScalarEvolution::LoopVariant:
12626     return "Variant";
12627   case ScalarEvolution::LoopInvariant:
12628     return "Invariant";
12629   case ScalarEvolution::LoopComputable:
12630     return "Computable";
12631   }
12632   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12633 }
12634 
12635 void ScalarEvolution::print(raw_ostream &OS) const {
12636   // ScalarEvolution's implementation of the print method is to print
12637   // out SCEV values of all instructions that are interesting. Doing
12638   // this potentially causes it to create new SCEV objects though,
12639   // which technically conflicts with the const qualifier. This isn't
12640   // observable from outside the class though, so casting away the
12641   // const isn't dangerous.
12642   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12643 
12644   if (ClassifyExpressions) {
12645     OS << "Classifying expressions for: ";
12646     F.printAsOperand(OS, /*PrintType=*/false);
12647     OS << "\n";
12648     for (Instruction &I : instructions(F))
12649       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12650         OS << I << '\n';
12651         OS << "  -->  ";
12652         const SCEV *SV = SE.getSCEV(&I);
12653         SV->print(OS);
12654         if (!isa<SCEVCouldNotCompute>(SV)) {
12655           OS << " U: ";
12656           SE.getUnsignedRange(SV).print(OS);
12657           OS << " S: ";
12658           SE.getSignedRange(SV).print(OS);
12659         }
12660 
12661         const Loop *L = LI.getLoopFor(I.getParent());
12662 
12663         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12664         if (AtUse != SV) {
12665           OS << "  -->  ";
12666           AtUse->print(OS);
12667           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12668             OS << " U: ";
12669             SE.getUnsignedRange(AtUse).print(OS);
12670             OS << " S: ";
12671             SE.getSignedRange(AtUse).print(OS);
12672           }
12673         }
12674 
12675         if (L) {
12676           OS << "\t\t" "Exits: ";
12677           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12678           if (!SE.isLoopInvariant(ExitValue, L)) {
12679             OS << "<<Unknown>>";
12680           } else {
12681             OS << *ExitValue;
12682           }
12683 
12684           bool First = true;
12685           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12686             if (First) {
12687               OS << "\t\t" "LoopDispositions: { ";
12688               First = false;
12689             } else {
12690               OS << ", ";
12691             }
12692 
12693             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12694             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12695           }
12696 
12697           for (auto *InnerL : depth_first(L)) {
12698             if (InnerL == L)
12699               continue;
12700             if (First) {
12701               OS << "\t\t" "LoopDispositions: { ";
12702               First = false;
12703             } else {
12704               OS << ", ";
12705             }
12706 
12707             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12708             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12709           }
12710 
12711           OS << " }";
12712         }
12713 
12714         OS << "\n";
12715       }
12716   }
12717 
12718   OS << "Determining loop execution counts for: ";
12719   F.printAsOperand(OS, /*PrintType=*/false);
12720   OS << "\n";
12721   for (Loop *I : LI)
12722     PrintLoopInfo(OS, &SE, I);
12723 }
12724 
12725 ScalarEvolution::LoopDisposition
12726 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12727   auto &Values = LoopDispositions[S];
12728   for (auto &V : Values) {
12729     if (V.getPointer() == L)
12730       return V.getInt();
12731   }
12732   Values.emplace_back(L, LoopVariant);
12733   LoopDisposition D = computeLoopDisposition(S, L);
12734   auto &Values2 = LoopDispositions[S];
12735   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12736     if (V.getPointer() == L) {
12737       V.setInt(D);
12738       break;
12739     }
12740   }
12741   return D;
12742 }
12743 
12744 ScalarEvolution::LoopDisposition
12745 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12746   switch (S->getSCEVType()) {
12747   case scConstant:
12748     return LoopInvariant;
12749   case scPtrToInt:
12750   case scTruncate:
12751   case scZeroExtend:
12752   case scSignExtend:
12753     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12754   case scAddRecExpr: {
12755     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12756 
12757     // If L is the addrec's loop, it's computable.
12758     if (AR->getLoop() == L)
12759       return LoopComputable;
12760 
12761     // Add recurrences are never invariant in the function-body (null loop).
12762     if (!L)
12763       return LoopVariant;
12764 
12765     // Everything that is not defined at loop entry is variant.
12766     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12767       return LoopVariant;
12768     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12769            " dominate the contained loop's header?");
12770 
12771     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12772     if (AR->getLoop()->contains(L))
12773       return LoopInvariant;
12774 
12775     // This recurrence is variant w.r.t. L if any of its operands
12776     // are variant.
12777     for (auto *Op : AR->operands())
12778       if (!isLoopInvariant(Op, L))
12779         return LoopVariant;
12780 
12781     // Otherwise it's loop-invariant.
12782     return LoopInvariant;
12783   }
12784   case scAddExpr:
12785   case scMulExpr:
12786   case scUMaxExpr:
12787   case scSMaxExpr:
12788   case scUMinExpr:
12789   case scSMinExpr: {
12790     bool HasVarying = false;
12791     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12792       LoopDisposition D = getLoopDisposition(Op, L);
12793       if (D == LoopVariant)
12794         return LoopVariant;
12795       if (D == LoopComputable)
12796         HasVarying = true;
12797     }
12798     return HasVarying ? LoopComputable : LoopInvariant;
12799   }
12800   case scUDivExpr: {
12801     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12802     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12803     if (LD == LoopVariant)
12804       return LoopVariant;
12805     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12806     if (RD == LoopVariant)
12807       return LoopVariant;
12808     return (LD == LoopInvariant && RD == LoopInvariant) ?
12809            LoopInvariant : LoopComputable;
12810   }
12811   case scUnknown:
12812     // All non-instruction values are loop invariant.  All instructions are loop
12813     // invariant if they are not contained in the specified loop.
12814     // Instructions are never considered invariant in the function body
12815     // (null loop) because they are defined within the "loop".
12816     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12817       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12818     return LoopInvariant;
12819   case scCouldNotCompute:
12820     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12821   }
12822   llvm_unreachable("Unknown SCEV kind!");
12823 }
12824 
12825 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12826   return getLoopDisposition(S, L) == LoopInvariant;
12827 }
12828 
12829 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12830   return getLoopDisposition(S, L) == LoopComputable;
12831 }
12832 
12833 ScalarEvolution::BlockDisposition
12834 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12835   auto &Values = BlockDispositions[S];
12836   for (auto &V : Values) {
12837     if (V.getPointer() == BB)
12838       return V.getInt();
12839   }
12840   Values.emplace_back(BB, DoesNotDominateBlock);
12841   BlockDisposition D = computeBlockDisposition(S, BB);
12842   auto &Values2 = BlockDispositions[S];
12843   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12844     if (V.getPointer() == BB) {
12845       V.setInt(D);
12846       break;
12847     }
12848   }
12849   return D;
12850 }
12851 
12852 ScalarEvolution::BlockDisposition
12853 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12854   switch (S->getSCEVType()) {
12855   case scConstant:
12856     return ProperlyDominatesBlock;
12857   case scPtrToInt:
12858   case scTruncate:
12859   case scZeroExtend:
12860   case scSignExtend:
12861     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12862   case scAddRecExpr: {
12863     // This uses a "dominates" query instead of "properly dominates" query
12864     // to test for proper dominance too, because the instruction which
12865     // produces the addrec's value is a PHI, and a PHI effectively properly
12866     // dominates its entire containing block.
12867     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12868     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12869       return DoesNotDominateBlock;
12870 
12871     // Fall through into SCEVNAryExpr handling.
12872     LLVM_FALLTHROUGH;
12873   }
12874   case scAddExpr:
12875   case scMulExpr:
12876   case scUMaxExpr:
12877   case scSMaxExpr:
12878   case scUMinExpr:
12879   case scSMinExpr: {
12880     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12881     bool Proper = true;
12882     for (const SCEV *NAryOp : NAry->operands()) {
12883       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12884       if (D == DoesNotDominateBlock)
12885         return DoesNotDominateBlock;
12886       if (D == DominatesBlock)
12887         Proper = false;
12888     }
12889     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12890   }
12891   case scUDivExpr: {
12892     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12893     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12894     BlockDisposition LD = getBlockDisposition(LHS, BB);
12895     if (LD == DoesNotDominateBlock)
12896       return DoesNotDominateBlock;
12897     BlockDisposition RD = getBlockDisposition(RHS, BB);
12898     if (RD == DoesNotDominateBlock)
12899       return DoesNotDominateBlock;
12900     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12901       ProperlyDominatesBlock : DominatesBlock;
12902   }
12903   case scUnknown:
12904     if (Instruction *I =
12905           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12906       if (I->getParent() == BB)
12907         return DominatesBlock;
12908       if (DT.properlyDominates(I->getParent(), BB))
12909         return ProperlyDominatesBlock;
12910       return DoesNotDominateBlock;
12911     }
12912     return ProperlyDominatesBlock;
12913   case scCouldNotCompute:
12914     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12915   }
12916   llvm_unreachable("Unknown SCEV kind!");
12917 }
12918 
12919 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12920   return getBlockDisposition(S, BB) >= DominatesBlock;
12921 }
12922 
12923 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12924   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12925 }
12926 
12927 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12928   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12929 }
12930 
12931 void
12932 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12933   ValuesAtScopes.erase(S);
12934   LoopDispositions.erase(S);
12935   BlockDispositions.erase(S);
12936   UnsignedRanges.erase(S);
12937   SignedRanges.erase(S);
12938   ExprValueMap.erase(S);
12939   HasRecMap.erase(S);
12940   MinTrailingZerosCache.erase(S);
12941 
12942   for (auto I = PredicatedSCEVRewrites.begin();
12943        I != PredicatedSCEVRewrites.end();) {
12944     std::pair<const SCEV *, const Loop *> Entry = I->first;
12945     if (Entry.first == S)
12946       PredicatedSCEVRewrites.erase(I++);
12947     else
12948       ++I;
12949   }
12950 
12951   auto RemoveSCEVFromBackedgeMap =
12952       [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12953         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12954           BackedgeTakenInfo &BEInfo = I->second;
12955           if (BEInfo.hasOperand(S))
12956             Map.erase(I++);
12957           else
12958             ++I;
12959         }
12960       };
12961 
12962   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12963   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12964 }
12965 
12966 void
12967 ScalarEvolution::getUsedLoops(const SCEV *S,
12968                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12969   struct FindUsedLoops {
12970     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12971         : LoopsUsed(LoopsUsed) {}
12972     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12973     bool follow(const SCEV *S) {
12974       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12975         LoopsUsed.insert(AR->getLoop());
12976       return true;
12977     }
12978 
12979     bool isDone() const { return false; }
12980   };
12981 
12982   FindUsedLoops F(LoopsUsed);
12983   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12984 }
12985 
12986 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12987   SmallPtrSet<const Loop *, 8> LoopsUsed;
12988   getUsedLoops(S, LoopsUsed);
12989   for (auto *L : LoopsUsed)
12990     LoopUsers[L].push_back(S);
12991 }
12992 
12993 void ScalarEvolution::verify() const {
12994   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12995   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12996 
12997   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12998 
12999   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13000   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13001     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13002 
13003     const SCEV *visitConstant(const SCEVConstant *Constant) {
13004       return SE.getConstant(Constant->getAPInt());
13005     }
13006 
13007     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13008       return SE.getUnknown(Expr->getValue());
13009     }
13010 
13011     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13012       return SE.getCouldNotCompute();
13013     }
13014   };
13015 
13016   SCEVMapper SCM(SE2);
13017 
13018   while (!LoopStack.empty()) {
13019     auto *L = LoopStack.pop_back_val();
13020     llvm::append_range(LoopStack, *L);
13021 
13022     auto *CurBECount = SCM.visit(
13023         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
13024     auto *NewBECount = SE2.getBackedgeTakenCount(L);
13025 
13026     if (CurBECount == SE2.getCouldNotCompute() ||
13027         NewBECount == SE2.getCouldNotCompute()) {
13028       // NB! This situation is legal, but is very suspicious -- whatever pass
13029       // change the loop to make a trip count go from could not compute to
13030       // computable or vice-versa *should have* invalidated SCEV.  However, we
13031       // choose not to assert here (for now) since we don't want false
13032       // positives.
13033       continue;
13034     }
13035 
13036     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
13037       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13038       // not propagate undef aggressively).  This means we can (and do) fail
13039       // verification in cases where a transform makes the trip count of a loop
13040       // go from "undef" to "undef+1" (say).  The transform is fine, since in
13041       // both cases the loop iterates "undef" times, but SCEV thinks we
13042       // increased the trip count of the loop by 1 incorrectly.
13043       continue;
13044     }
13045 
13046     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13047         SE.getTypeSizeInBits(NewBECount->getType()))
13048       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13049     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13050              SE.getTypeSizeInBits(NewBECount->getType()))
13051       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13052 
13053     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
13054 
13055     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13056     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
13057       dbgs() << "Trip Count for " << *L << " Changed!\n";
13058       dbgs() << "Old: " << *CurBECount << "\n";
13059       dbgs() << "New: " << *NewBECount << "\n";
13060       dbgs() << "Delta: " << *Delta << "\n";
13061       std::abort();
13062     }
13063   }
13064 
13065   // Collect all valid loops currently in LoopInfo.
13066   SmallPtrSet<Loop *, 32> ValidLoops;
13067   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13068   while (!Worklist.empty()) {
13069     Loop *L = Worklist.pop_back_val();
13070     if (ValidLoops.contains(L))
13071       continue;
13072     ValidLoops.insert(L);
13073     Worklist.append(L->begin(), L->end());
13074   }
13075   // Check for SCEV expressions referencing invalid/deleted loops.
13076   for (auto &KV : ValueExprMap) {
13077     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
13078     if (!AR)
13079       continue;
13080     assert(ValidLoops.contains(AR->getLoop()) &&
13081            "AddRec references invalid loop");
13082   }
13083 }
13084 
13085 bool ScalarEvolution::invalidate(
13086     Function &F, const PreservedAnalyses &PA,
13087     FunctionAnalysisManager::Invalidator &Inv) {
13088   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13089   // of its dependencies is invalidated.
13090   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13091   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13092          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13093          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13094          Inv.invalidate<LoopAnalysis>(F, PA);
13095 }
13096 
13097 AnalysisKey ScalarEvolutionAnalysis::Key;
13098 
13099 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13100                                              FunctionAnalysisManager &AM) {
13101   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13102                          AM.getResult<AssumptionAnalysis>(F),
13103                          AM.getResult<DominatorTreeAnalysis>(F),
13104                          AM.getResult<LoopAnalysis>(F));
13105 }
13106 
13107 PreservedAnalyses
13108 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13109   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13110   return PreservedAnalyses::all();
13111 }
13112 
13113 PreservedAnalyses
13114 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13115   // For compatibility with opt's -analyze feature under legacy pass manager
13116   // which was not ported to NPM. This keeps tests using
13117   // update_analyze_test_checks.py working.
13118   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13119      << F.getName() << "':\n";
13120   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13121   return PreservedAnalyses::all();
13122 }
13123 
13124 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13125                       "Scalar Evolution Analysis", false, true)
13126 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13127 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13128 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13129 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13130 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13131                     "Scalar Evolution Analysis", false, true)
13132 
13133 char ScalarEvolutionWrapperPass::ID = 0;
13134 
13135 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13136   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13137 }
13138 
13139 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13140   SE.reset(new ScalarEvolution(
13141       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13142       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13143       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13144       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13145   return false;
13146 }
13147 
13148 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13149 
13150 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13151   SE->print(OS);
13152 }
13153 
13154 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13155   if (!VerifySCEV)
13156     return;
13157 
13158   SE->verify();
13159 }
13160 
13161 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13162   AU.setPreservesAll();
13163   AU.addRequiredTransitive<AssumptionCacheTracker>();
13164   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13165   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13166   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13167 }
13168 
13169 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13170                                                         const SCEV *RHS) {
13171   FoldingSetNodeID ID;
13172   assert(LHS->getType() == RHS->getType() &&
13173          "Type mismatch between LHS and RHS");
13174   // Unique this node based on the arguments
13175   ID.AddInteger(SCEVPredicate::P_Equal);
13176   ID.AddPointer(LHS);
13177   ID.AddPointer(RHS);
13178   void *IP = nullptr;
13179   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13180     return S;
13181   SCEVEqualPredicate *Eq = new (SCEVAllocator)
13182       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
13183   UniquePreds.InsertNode(Eq, IP);
13184   return Eq;
13185 }
13186 
13187 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13188     const SCEVAddRecExpr *AR,
13189     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13190   FoldingSetNodeID ID;
13191   // Unique this node based on the arguments
13192   ID.AddInteger(SCEVPredicate::P_Wrap);
13193   ID.AddPointer(AR);
13194   ID.AddInteger(AddedFlags);
13195   void *IP = nullptr;
13196   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13197     return S;
13198   auto *OF = new (SCEVAllocator)
13199       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13200   UniquePreds.InsertNode(OF, IP);
13201   return OF;
13202 }
13203 
13204 namespace {
13205 
13206 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13207 public:
13208 
13209   /// Rewrites \p S in the context of a loop L and the SCEV predication
13210   /// infrastructure.
13211   ///
13212   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13213   /// equivalences present in \p Pred.
13214   ///
13215   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13216   /// \p NewPreds such that the result will be an AddRecExpr.
13217   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13218                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13219                              SCEVUnionPredicate *Pred) {
13220     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13221     return Rewriter.visit(S);
13222   }
13223 
13224   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13225     if (Pred) {
13226       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
13227       for (auto *Pred : ExprPreds)
13228         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
13229           if (IPred->getLHS() == Expr)
13230             return IPred->getRHS();
13231     }
13232     return convertToAddRecWithPreds(Expr);
13233   }
13234 
13235   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13236     const SCEV *Operand = visit(Expr->getOperand());
13237     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13238     if (AR && AR->getLoop() == L && AR->isAffine()) {
13239       // This couldn't be folded because the operand didn't have the nuw
13240       // flag. Add the nusw flag as an assumption that we could make.
13241       const SCEV *Step = AR->getStepRecurrence(SE);
13242       Type *Ty = Expr->getType();
13243       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13244         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13245                                 SE.getSignExtendExpr(Step, Ty), L,
13246                                 AR->getNoWrapFlags());
13247     }
13248     return SE.getZeroExtendExpr(Operand, Expr->getType());
13249   }
13250 
13251   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13252     const SCEV *Operand = visit(Expr->getOperand());
13253     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13254     if (AR && AR->getLoop() == L && AR->isAffine()) {
13255       // This couldn't be folded because the operand didn't have the nsw
13256       // flag. Add the nssw flag as an assumption that we could make.
13257       const SCEV *Step = AR->getStepRecurrence(SE);
13258       Type *Ty = Expr->getType();
13259       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13260         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13261                                 SE.getSignExtendExpr(Step, Ty), L,
13262                                 AR->getNoWrapFlags());
13263     }
13264     return SE.getSignExtendExpr(Operand, Expr->getType());
13265   }
13266 
13267 private:
13268   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13269                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13270                         SCEVUnionPredicate *Pred)
13271       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13272 
13273   bool addOverflowAssumption(const SCEVPredicate *P) {
13274     if (!NewPreds) {
13275       // Check if we've already made this assumption.
13276       return Pred && Pred->implies(P);
13277     }
13278     NewPreds->insert(P);
13279     return true;
13280   }
13281 
13282   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13283                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13284     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13285     return addOverflowAssumption(A);
13286   }
13287 
13288   // If \p Expr represents a PHINode, we try to see if it can be represented
13289   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13290   // to add this predicate as a runtime overflow check, we return the AddRec.
13291   // If \p Expr does not meet these conditions (is not a PHI node, or we
13292   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13293   // return \p Expr.
13294   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13295     if (!isa<PHINode>(Expr->getValue()))
13296       return Expr;
13297     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13298     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13299     if (!PredicatedRewrite)
13300       return Expr;
13301     for (auto *P : PredicatedRewrite->second){
13302       // Wrap predicates from outer loops are not supported.
13303       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13304         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
13305         if (L != AR->getLoop())
13306           return Expr;
13307       }
13308       if (!addOverflowAssumption(P))
13309         return Expr;
13310     }
13311     return PredicatedRewrite->first;
13312   }
13313 
13314   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13315   SCEVUnionPredicate *Pred;
13316   const Loop *L;
13317 };
13318 
13319 } // end anonymous namespace
13320 
13321 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13322                                                    SCEVUnionPredicate &Preds) {
13323   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13324 }
13325 
13326 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13327     const SCEV *S, const Loop *L,
13328     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13329   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13330   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13331   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13332 
13333   if (!AddRec)
13334     return nullptr;
13335 
13336   // Since the transformation was successful, we can now transfer the SCEV
13337   // predicates.
13338   for (auto *P : TransformPreds)
13339     Preds.insert(P);
13340 
13341   return AddRec;
13342 }
13343 
13344 /// SCEV predicates
13345 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13346                              SCEVPredicateKind Kind)
13347     : FastID(ID), Kind(Kind) {}
13348 
13349 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13350                                        const SCEV *LHS, const SCEV *RHS)
13351     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13352   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13353   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13354 }
13355 
13356 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13357   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13358 
13359   if (!Op)
13360     return false;
13361 
13362   return Op->LHS == LHS && Op->RHS == RHS;
13363 }
13364 
13365 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13366 
13367 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13368 
13369 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13370   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13371 }
13372 
13373 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13374                                      const SCEVAddRecExpr *AR,
13375                                      IncrementWrapFlags Flags)
13376     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13377 
13378 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13379 
13380 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13381   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13382 
13383   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13384 }
13385 
13386 bool SCEVWrapPredicate::isAlwaysTrue() const {
13387   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13388   IncrementWrapFlags IFlags = Flags;
13389 
13390   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13391     IFlags = clearFlags(IFlags, IncrementNSSW);
13392 
13393   return IFlags == IncrementAnyWrap;
13394 }
13395 
13396 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13397   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13398   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13399     OS << "<nusw>";
13400   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13401     OS << "<nssw>";
13402   OS << "\n";
13403 }
13404 
13405 SCEVWrapPredicate::IncrementWrapFlags
13406 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13407                                    ScalarEvolution &SE) {
13408   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13409   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13410 
13411   // We can safely transfer the NSW flag as NSSW.
13412   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13413     ImpliedFlags = IncrementNSSW;
13414 
13415   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13416     // If the increment is positive, the SCEV NUW flag will also imply the
13417     // WrapPredicate NUSW flag.
13418     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13419       if (Step->getValue()->getValue().isNonNegative())
13420         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13421   }
13422 
13423   return ImpliedFlags;
13424 }
13425 
13426 /// Union predicates don't get cached so create a dummy set ID for it.
13427 SCEVUnionPredicate::SCEVUnionPredicate()
13428     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13429 
13430 bool SCEVUnionPredicate::isAlwaysTrue() const {
13431   return all_of(Preds,
13432                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13433 }
13434 
13435 ArrayRef<const SCEVPredicate *>
13436 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13437   auto I = SCEVToPreds.find(Expr);
13438   if (I == SCEVToPreds.end())
13439     return ArrayRef<const SCEVPredicate *>();
13440   return I->second;
13441 }
13442 
13443 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13444   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13445     return all_of(Set->Preds,
13446                   [this](const SCEVPredicate *I) { return this->implies(I); });
13447 
13448   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13449   if (ScevPredsIt == SCEVToPreds.end())
13450     return false;
13451   auto &SCEVPreds = ScevPredsIt->second;
13452 
13453   return any_of(SCEVPreds,
13454                 [N](const SCEVPredicate *I) { return I->implies(N); });
13455 }
13456 
13457 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13458 
13459 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13460   for (auto Pred : Preds)
13461     Pred->print(OS, Depth);
13462 }
13463 
13464 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13465   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13466     for (auto Pred : Set->Preds)
13467       add(Pred);
13468     return;
13469   }
13470 
13471   if (implies(N))
13472     return;
13473 
13474   const SCEV *Key = N->getExpr();
13475   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13476                 " associated expression!");
13477 
13478   SCEVToPreds[Key].push_back(N);
13479   Preds.push_back(N);
13480 }
13481 
13482 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13483                                                      Loop &L)
13484     : SE(SE), L(L) {}
13485 
13486 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13487   const SCEV *Expr = SE.getSCEV(V);
13488   RewriteEntry &Entry = RewriteMap[Expr];
13489 
13490   // If we already have an entry and the version matches, return it.
13491   if (Entry.second && Generation == Entry.first)
13492     return Entry.second;
13493 
13494   // We found an entry but it's stale. Rewrite the stale entry
13495   // according to the current predicate.
13496   if (Entry.second)
13497     Expr = Entry.second;
13498 
13499   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13500   Entry = {Generation, NewSCEV};
13501 
13502   return NewSCEV;
13503 }
13504 
13505 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13506   if (!BackedgeCount) {
13507     SCEVUnionPredicate BackedgePred;
13508     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13509     addPredicate(BackedgePred);
13510   }
13511   return BackedgeCount;
13512 }
13513 
13514 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13515   if (Preds.implies(&Pred))
13516     return;
13517   Preds.add(&Pred);
13518   updateGeneration();
13519 }
13520 
13521 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13522   return Preds;
13523 }
13524 
13525 void PredicatedScalarEvolution::updateGeneration() {
13526   // If the generation number wrapped recompute everything.
13527   if (++Generation == 0) {
13528     for (auto &II : RewriteMap) {
13529       const SCEV *Rewritten = II.second.second;
13530       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13531     }
13532   }
13533 }
13534 
13535 void PredicatedScalarEvolution::setNoOverflow(
13536     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13537   const SCEV *Expr = getSCEV(V);
13538   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13539 
13540   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13541 
13542   // Clear the statically implied flags.
13543   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13544   addPredicate(*SE.getWrapPredicate(AR, Flags));
13545 
13546   auto II = FlagsMap.insert({V, Flags});
13547   if (!II.second)
13548     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13549 }
13550 
13551 bool PredicatedScalarEvolution::hasNoOverflow(
13552     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13553   const SCEV *Expr = getSCEV(V);
13554   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13555 
13556   Flags = SCEVWrapPredicate::clearFlags(
13557       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13558 
13559   auto II = FlagsMap.find(V);
13560 
13561   if (II != FlagsMap.end())
13562     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13563 
13564   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13565 }
13566 
13567 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13568   const SCEV *Expr = this->getSCEV(V);
13569   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13570   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13571 
13572   if (!New)
13573     return nullptr;
13574 
13575   for (auto *P : NewPreds)
13576     Preds.add(P);
13577 
13578   updateGeneration();
13579   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13580   return New;
13581 }
13582 
13583 PredicatedScalarEvolution::PredicatedScalarEvolution(
13584     const PredicatedScalarEvolution &Init)
13585     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13586       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13587   for (auto I : Init.FlagsMap)
13588     FlagsMap.insert(I);
13589 }
13590 
13591 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13592   // For each block.
13593   for (auto *BB : L.getBlocks())
13594     for (auto &I : *BB) {
13595       if (!SE.isSCEVable(I.getType()))
13596         continue;
13597 
13598       auto *Expr = SE.getSCEV(&I);
13599       auto II = RewriteMap.find(Expr);
13600 
13601       if (II == RewriteMap.end())
13602         continue;
13603 
13604       // Don't print things that are not interesting.
13605       if (II->second.second == Expr)
13606         continue;
13607 
13608       OS.indent(Depth) << "[PSE]" << I << ":\n";
13609       OS.indent(Depth + 2) << *Expr << "\n";
13610       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13611     }
13612 }
13613 
13614 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13615 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13616 // for URem with constant power-of-2 second operands.
13617 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13618 // 4, A / B becomes X / 8).
13619 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13620                                 const SCEV *&RHS) {
13621   // Try to match 'zext (trunc A to iB) to iY', which is used
13622   // for URem with constant power-of-2 second operands. Make sure the size of
13623   // the operand A matches the size of the whole expressions.
13624   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13625     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13626       LHS = Trunc->getOperand();
13627       // Bail out if the type of the LHS is larger than the type of the
13628       // expression for now.
13629       if (getTypeSizeInBits(LHS->getType()) >
13630           getTypeSizeInBits(Expr->getType()))
13631         return false;
13632       if (LHS->getType() != Expr->getType())
13633         LHS = getZeroExtendExpr(LHS, Expr->getType());
13634       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13635                         << getTypeSizeInBits(Trunc->getType()));
13636       return true;
13637     }
13638   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13639   if (Add == nullptr || Add->getNumOperands() != 2)
13640     return false;
13641 
13642   const SCEV *A = Add->getOperand(1);
13643   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13644 
13645   if (Mul == nullptr)
13646     return false;
13647 
13648   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13649     // (SomeExpr + (-(SomeExpr / B) * B)).
13650     if (Expr == getURemExpr(A, B)) {
13651       LHS = A;
13652       RHS = B;
13653       return true;
13654     }
13655     return false;
13656   };
13657 
13658   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13659   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13660     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13661            MatchURemWithDivisor(Mul->getOperand(2));
13662 
13663   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13664   if (Mul->getNumOperands() == 2)
13665     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13666            MatchURemWithDivisor(Mul->getOperand(0)) ||
13667            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13668            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13669   return false;
13670 }
13671 
13672 const SCEV *
13673 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13674   SmallVector<BasicBlock*, 16> ExitingBlocks;
13675   L->getExitingBlocks(ExitingBlocks);
13676 
13677   // Form an expression for the maximum exit count possible for this loop. We
13678   // merge the max and exact information to approximate a version of
13679   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13680   SmallVector<const SCEV*, 4> ExitCounts;
13681   for (BasicBlock *ExitingBB : ExitingBlocks) {
13682     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13683     if (isa<SCEVCouldNotCompute>(ExitCount))
13684       ExitCount = getExitCount(L, ExitingBB,
13685                                   ScalarEvolution::ConstantMaximum);
13686     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13687       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13688              "We should only have known counts for exiting blocks that "
13689              "dominate latch!");
13690       ExitCounts.push_back(ExitCount);
13691     }
13692   }
13693   if (ExitCounts.empty())
13694     return getCouldNotCompute();
13695   return getUMinFromMismatchedTypes(ExitCounts);
13696 }
13697 
13698 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13699 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13700 /// we cannot guarantee that the replacement is loop invariant in the loop of
13701 /// the AddRec.
13702 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13703   ValueToSCEVMapTy &Map;
13704 
13705 public:
13706   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13707       : SCEVRewriteVisitor(SE), Map(M) {}
13708 
13709   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13710 
13711   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13712     auto I = Map.find(Expr->getValue());
13713     if (I == Map.end())
13714       return Expr;
13715     return I->second;
13716   }
13717 };
13718 
13719 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13720   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13721                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13722     // If we have LHS == 0, check if LHS is computing a property of some unknown
13723     // SCEV %v which we can rewrite %v to express explicitly.
13724     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13725     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13726         RHSC->getValue()->isNullValue()) {
13727       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13728       // explicitly express that.
13729       const SCEV *URemLHS = nullptr;
13730       const SCEV *URemRHS = nullptr;
13731       if (matchURem(LHS, URemLHS, URemRHS)) {
13732         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13733           Value *V = LHSUnknown->getValue();
13734           auto Multiple =
13735               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13736                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13737           RewriteMap[V] = Multiple;
13738           return;
13739         }
13740       }
13741     }
13742 
13743     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
13744       std::swap(LHS, RHS);
13745       Predicate = CmpInst::getSwappedPredicate(Predicate);
13746     }
13747 
13748     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
13749     // create this form when combining two checks of the form (X u< C2 + C1) and
13750     // (X >=u C1).
13751     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() {
13752       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
13753       if (!AddExpr || AddExpr->getNumOperands() != 2)
13754         return false;
13755 
13756       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
13757       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
13758       auto *C2 = dyn_cast<SCEVConstant>(RHS);
13759       if (!C1 || !C2 || !LHSUnknown)
13760         return false;
13761 
13762       auto ExactRegion =
13763           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
13764               .sub(C1->getAPInt());
13765 
13766       // Bail out, unless we have a non-wrapping, monotonic range.
13767       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
13768         return false;
13769       auto I = RewriteMap.find(LHSUnknown->getValue());
13770       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13771       RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(
13772           getConstant(ExactRegion.getUnsignedMin()),
13773           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
13774       return true;
13775     };
13776     if (MatchRangeCheckIdiom())
13777       return;
13778 
13779     // For now, limit to conditions that provide information about unknown
13780     // expressions. RHS also cannot contain add recurrences.
13781     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13782     if (!LHSUnknown || containsAddRecurrence(RHS))
13783       return;
13784 
13785     // Check whether LHS has already been rewritten. In that case we want to
13786     // chain further rewrites onto the already rewritten value.
13787     auto I = RewriteMap.find(LHSUnknown->getValue());
13788     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
13789     const SCEV *RewrittenRHS = nullptr;
13790     switch (Predicate) {
13791     case CmpInst::ICMP_ULT:
13792       RewrittenRHS =
13793           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13794       break;
13795     case CmpInst::ICMP_SLT:
13796       RewrittenRHS =
13797           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
13798       break;
13799     case CmpInst::ICMP_ULE:
13800       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
13801       break;
13802     case CmpInst::ICMP_SLE:
13803       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
13804       break;
13805     case CmpInst::ICMP_UGT:
13806       RewrittenRHS =
13807           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13808       break;
13809     case CmpInst::ICMP_SGT:
13810       RewrittenRHS =
13811           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
13812       break;
13813     case CmpInst::ICMP_UGE:
13814       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
13815       break;
13816     case CmpInst::ICMP_SGE:
13817       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
13818       break;
13819     case CmpInst::ICMP_EQ:
13820       if (isa<SCEVConstant>(RHS))
13821         RewrittenRHS = RHS;
13822       break;
13823     case CmpInst::ICMP_NE:
13824       if (isa<SCEVConstant>(RHS) &&
13825           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13826         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
13827       break;
13828     default:
13829       break;
13830     }
13831 
13832     if (RewrittenRHS)
13833       RewriteMap[LHSUnknown->getValue()] = RewrittenRHS;
13834   };
13835   // Starting at the loop predecessor, climb up the predecessor chain, as long
13836   // as there are predecessors that can be found that have unique successors
13837   // leading to the original header.
13838   // TODO: share this logic with isLoopEntryGuardedByCond.
13839   ValueToSCEVMapTy RewriteMap;
13840   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13841            L->getLoopPredecessor(), L->getHeader());
13842        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13843 
13844     const BranchInst *LoopEntryPredicate =
13845         dyn_cast<BranchInst>(Pair.first->getTerminator());
13846     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13847       continue;
13848 
13849     bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second;
13850     SmallVector<Value *, 8> Worklist;
13851     SmallPtrSet<Value *, 8> Visited;
13852     Worklist.push_back(LoopEntryPredicate->getCondition());
13853     while (!Worklist.empty()) {
13854       Value *Cond = Worklist.pop_back_val();
13855       if (!Visited.insert(Cond).second)
13856         continue;
13857 
13858       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13859         auto Predicate =
13860             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
13861         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13862                          getSCEV(Cmp->getOperand(1)), RewriteMap);
13863         continue;
13864       }
13865 
13866       Value *L, *R;
13867       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
13868                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
13869         Worklist.push_back(L);
13870         Worklist.push_back(R);
13871       }
13872     }
13873   }
13874 
13875   // Also collect information from assumptions dominating the loop.
13876   for (auto &AssumeVH : AC.assumptions()) {
13877     if (!AssumeVH)
13878       continue;
13879     auto *AssumeI = cast<CallInst>(AssumeVH);
13880     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13881     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13882       continue;
13883     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13884                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13885   }
13886 
13887   if (RewriteMap.empty())
13888     return Expr;
13889   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13890   return Rewriter.visit(Expr);
13891 }
13892