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     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
325          I != E; ++I) {
326       OS << **I;
327       if (std::next(I) != E)
328         OS << OpStr;
329     }
330     OS << ")";
331     switch (NAry->getSCEVType()) {
332     case scAddExpr:
333     case scMulExpr:
334       if (NAry->hasNoUnsignedWrap())
335         OS << "<nuw>";
336       if (NAry->hasNoSignedWrap())
337         OS << "<nsw>";
338       break;
339     default:
340       // Nothing to print for other nary expressions.
341       break;
342     }
343     return;
344   }
345   case scUDivExpr: {
346     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
347     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
348     return;
349   }
350   case scUnknown: {
351     const SCEVUnknown *U = cast<SCEVUnknown>(this);
352     Type *AllocTy;
353     if (U->isSizeOf(AllocTy)) {
354       OS << "sizeof(" << *AllocTy << ")";
355       return;
356     }
357     if (U->isAlignOf(AllocTy)) {
358       OS << "alignof(" << *AllocTy << ")";
359       return;
360     }
361 
362     Type *CTy;
363     Constant *FieldNo;
364     if (U->isOffsetOf(CTy, FieldNo)) {
365       OS << "offsetof(" << *CTy << ", ";
366       FieldNo->printAsOperand(OS, false);
367       OS << ")";
368       return;
369     }
370 
371     // Otherwise just print it normally.
372     U->getValue()->printAsOperand(OS, false);
373     return;
374   }
375   case scCouldNotCompute:
376     OS << "***COULDNOTCOMPUTE***";
377     return;
378   }
379   llvm_unreachable("Unknown SCEV kind!");
380 }
381 
382 Type *SCEV::getType() const {
383   switch (getSCEVType()) {
384   case scConstant:
385     return cast<SCEVConstant>(this)->getType();
386   case scPtrToInt:
387   case scTruncate:
388   case scZeroExtend:
389   case scSignExtend:
390     return cast<SCEVCastExpr>(this)->getType();
391   case scAddRecExpr:
392   case scMulExpr:
393   case scUMaxExpr:
394   case scSMaxExpr:
395   case scUMinExpr:
396   case scSMinExpr:
397     return cast<SCEVNAryExpr>(this)->getType();
398   case scAddExpr:
399     return cast<SCEVAddExpr>(this)->getType();
400   case scUDivExpr:
401     return cast<SCEVUDivExpr>(this)->getType();
402   case scUnknown:
403     return cast<SCEVUnknown>(this)->getType();
404   case scCouldNotCompute:
405     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
406   }
407   llvm_unreachable("Unknown SCEV kind!");
408 }
409 
410 bool SCEV::isZero() const {
411   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
412     return SC->getValue()->isZero();
413   return false;
414 }
415 
416 bool SCEV::isOne() const {
417   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
418     return SC->getValue()->isOne();
419   return false;
420 }
421 
422 bool SCEV::isAllOnesValue() const {
423   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
424     return SC->getValue()->isMinusOne();
425   return false;
426 }
427 
428 bool SCEV::isNonConstantNegative() const {
429   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
430   if (!Mul) return false;
431 
432   // If there is a constant factor, it will be first.
433   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
434   if (!SC) return false;
435 
436   // Return true if the value is negative, this matches things like (-42 * V).
437   return SC->getAPInt().isNegative();
438 }
439 
440 SCEVCouldNotCompute::SCEVCouldNotCompute() :
441   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
442 
443 bool SCEVCouldNotCompute::classof(const SCEV *S) {
444   return S->getSCEVType() == scCouldNotCompute;
445 }
446 
447 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
448   FoldingSetNodeID ID;
449   ID.AddInteger(scConstant);
450   ID.AddPointer(V);
451   void *IP = nullptr;
452   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
453   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
454   UniqueSCEVs.InsertNode(S, IP);
455   return S;
456 }
457 
458 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
459   return getConstant(ConstantInt::get(getContext(), Val));
460 }
461 
462 const SCEV *
463 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
464   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
465   return getConstant(ConstantInt::get(ITy, V, isSigned));
466 }
467 
468 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
469                            const SCEV *op, Type *ty)
470     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
471   Operands[0] = op;
472 }
473 
474 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
475                                    Type *ITy)
476     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
477   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
478          "Must be a non-bit-width-changing pointer-to-integer cast!");
479 }
480 
481 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
482                                            SCEVTypes SCEVTy, const SCEV *op,
483                                            Type *ty)
484     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
485 
486 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
487                                    Type *ty)
488     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
489   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
490          "Cannot truncate non-integer value!");
491 }
492 
493 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
494                                        const SCEV *op, Type *ty)
495     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
496   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
497          "Cannot zero extend non-integer value!");
498 }
499 
500 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
501                                        const SCEV *op, Type *ty)
502     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
503   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
504          "Cannot sign extend non-integer value!");
505 }
506 
507 void SCEVUnknown::deleted() {
508   // Clear this SCEVUnknown from various maps.
509   SE->forgetMemoizedResults(this);
510 
511   // Remove this SCEVUnknown from the uniquing map.
512   SE->UniqueSCEVs.RemoveNode(this);
513 
514   // Release the value.
515   setValPtr(nullptr);
516 }
517 
518 void SCEVUnknown::allUsesReplacedWith(Value *New) {
519   // Remove this SCEVUnknown from the uniquing map.
520   SE->UniqueSCEVs.RemoveNode(this);
521 
522   // Update this SCEVUnknown to point to the new value. This is needed
523   // because there may still be outstanding SCEVs which still point to
524   // this SCEVUnknown.
525   setValPtr(New);
526 }
527 
528 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
529   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
530     if (VCE->getOpcode() == Instruction::PtrToInt)
531       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
532         if (CE->getOpcode() == Instruction::GetElementPtr &&
533             CE->getOperand(0)->isNullValue() &&
534             CE->getNumOperands() == 2)
535           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
536             if (CI->isOne()) {
537               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
538                                  ->getElementType();
539               return true;
540             }
541 
542   return false;
543 }
544 
545 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
546   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
547     if (VCE->getOpcode() == Instruction::PtrToInt)
548       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
549         if (CE->getOpcode() == Instruction::GetElementPtr &&
550             CE->getOperand(0)->isNullValue()) {
551           Type *Ty =
552             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
553           if (StructType *STy = dyn_cast<StructType>(Ty))
554             if (!STy->isPacked() &&
555                 CE->getNumOperands() == 3 &&
556                 CE->getOperand(1)->isNullValue()) {
557               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
558                 if (CI->isOne() &&
559                     STy->getNumElements() == 2 &&
560                     STy->getElementType(0)->isIntegerTy(1)) {
561                   AllocTy = STy->getElementType(1);
562                   return true;
563                 }
564             }
565         }
566 
567   return false;
568 }
569 
570 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
571   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
572     if (VCE->getOpcode() == Instruction::PtrToInt)
573       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
574         if (CE->getOpcode() == Instruction::GetElementPtr &&
575             CE->getNumOperands() == 3 &&
576             CE->getOperand(0)->isNullValue() &&
577             CE->getOperand(1)->isNullValue()) {
578           Type *Ty =
579             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
580           // Ignore vector types here so that ScalarEvolutionExpander doesn't
581           // emit getelementptrs that index into vectors.
582           if (Ty->isStructTy() || Ty->isArrayTy()) {
583             CTy = Ty;
584             FieldNo = CE->getOperand(2);
585             return true;
586           }
587         }
588 
589   return false;
590 }
591 
592 //===----------------------------------------------------------------------===//
593 //                               SCEV Utilities
594 //===----------------------------------------------------------------------===//
595 
596 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
597 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
598 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
599 /// have been previously deemed to be "equally complex" by this routine.  It is
600 /// intended to avoid exponential time complexity in cases like:
601 ///
602 ///   %a = f(%x, %y)
603 ///   %b = f(%a, %a)
604 ///   %c = f(%b, %b)
605 ///
606 ///   %d = f(%x, %y)
607 ///   %e = f(%d, %d)
608 ///   %f = f(%e, %e)
609 ///
610 ///   CompareValueComplexity(%f, %c)
611 ///
612 /// Since we do not continue running this routine on expression trees once we
613 /// have seen unequal values, there is no need to track them in the cache.
614 static int
615 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
616                        const LoopInfo *const LI, Value *LV, Value *RV,
617                        unsigned Depth) {
618   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
619     return 0;
620 
621   // Order pointer values after integer values. This helps SCEVExpander form
622   // GEPs.
623   bool LIsPointer = LV->getType()->isPointerTy(),
624        RIsPointer = RV->getType()->isPointerTy();
625   if (LIsPointer != RIsPointer)
626     return (int)LIsPointer - (int)RIsPointer;
627 
628   // Compare getValueID values.
629   unsigned LID = LV->getValueID(), RID = RV->getValueID();
630   if (LID != RID)
631     return (int)LID - (int)RID;
632 
633   // Sort arguments by their position.
634   if (const auto *LA = dyn_cast<Argument>(LV)) {
635     const auto *RA = cast<Argument>(RV);
636     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
637     return (int)LArgNo - (int)RArgNo;
638   }
639 
640   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
641     const auto *RGV = cast<GlobalValue>(RV);
642 
643     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
644       auto LT = GV->getLinkage();
645       return !(GlobalValue::isPrivateLinkage(LT) ||
646                GlobalValue::isInternalLinkage(LT));
647     };
648 
649     // Use the names to distinguish the two values, but only if the
650     // names are semantically important.
651     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
652       return LGV->getName().compare(RGV->getName());
653   }
654 
655   // For instructions, compare their loop depth, and their operand count.  This
656   // is pretty loose.
657   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
658     const auto *RInst = cast<Instruction>(RV);
659 
660     // Compare loop depths.
661     const BasicBlock *LParent = LInst->getParent(),
662                      *RParent = RInst->getParent();
663     if (LParent != RParent) {
664       unsigned LDepth = LI->getLoopDepth(LParent),
665                RDepth = LI->getLoopDepth(RParent);
666       if (LDepth != RDepth)
667         return (int)LDepth - (int)RDepth;
668     }
669 
670     // Compare the number of operands.
671     unsigned LNumOps = LInst->getNumOperands(),
672              RNumOps = RInst->getNumOperands();
673     if (LNumOps != RNumOps)
674       return (int)LNumOps - (int)RNumOps;
675 
676     for (unsigned Idx : seq(0u, LNumOps)) {
677       int Result =
678           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
679                                  RInst->getOperand(Idx), Depth + 1);
680       if (Result != 0)
681         return Result;
682     }
683   }
684 
685   EqCacheValue.unionSets(LV, RV);
686   return 0;
687 }
688 
689 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
690 // than RHS, respectively. A three-way result allows recursive comparisons to be
691 // more efficient.
692 // If the max analysis depth was reached, return None, assuming we do not know
693 // if they are equivalent for sure.
694 static Optional<int>
695 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
696                       EquivalenceClasses<const Value *> &EqCacheValue,
697                       const LoopInfo *const LI, const SCEV *LHS,
698                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
699   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
700   if (LHS == RHS)
701     return 0;
702 
703   // Primarily, sort the SCEVs by their getSCEVType().
704   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
705   if (LType != RType)
706     return (int)LType - (int)RType;
707 
708   if (EqCacheSCEV.isEquivalent(LHS, RHS))
709     return 0;
710 
711   if (Depth > MaxSCEVCompareDepth)
712     return None;
713 
714   // Aside from the getSCEVType() ordering, the particular ordering
715   // isn't very important except that it's beneficial to be consistent,
716   // so that (a + b) and (b + a) don't end up as different expressions.
717   switch (LType) {
718   case scUnknown: {
719     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
720     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
721 
722     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
723                                    RU->getValue(), Depth + 1);
724     if (X == 0)
725       EqCacheSCEV.unionSets(LHS, RHS);
726     return X;
727   }
728 
729   case scConstant: {
730     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
731     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
732 
733     // Compare constant values.
734     const APInt &LA = LC->getAPInt();
735     const APInt &RA = RC->getAPInt();
736     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
737     if (LBitWidth != RBitWidth)
738       return (int)LBitWidth - (int)RBitWidth;
739     return LA.ult(RA) ? -1 : 1;
740   }
741 
742   case scAddRecExpr: {
743     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
744     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
745 
746     // There is always a dominance between two recs that are used by one SCEV,
747     // so we can safely sort recs by loop header dominance. We require such
748     // order in getAddExpr.
749     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
750     if (LLoop != RLoop) {
751       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
752       assert(LHead != RHead && "Two loops share the same header?");
753       if (DT.dominates(LHead, RHead))
754         return 1;
755       else
756         assert(DT.dominates(RHead, LHead) &&
757                "No dominance between recurrences used by one SCEV?");
758       return -1;
759     }
760 
761     // Addrec complexity grows with operand count.
762     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
763     if (LNumOps != RNumOps)
764       return (int)LNumOps - (int)RNumOps;
765 
766     // Lexicographically compare.
767     for (unsigned i = 0; i != LNumOps; ++i) {
768       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
769                                      LA->getOperand(i), RA->getOperand(i), DT,
770                                      Depth + 1);
771       if (X != 0)
772         return X;
773     }
774     EqCacheSCEV.unionSets(LHS, RHS);
775     return 0;
776   }
777 
778   case scAddExpr:
779   case scMulExpr:
780   case scSMaxExpr:
781   case scUMaxExpr:
782   case scSMinExpr:
783   case scUMinExpr: {
784     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
785     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
786 
787     // Lexicographically compare n-ary expressions.
788     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
789     if (LNumOps != RNumOps)
790       return (int)LNumOps - (int)RNumOps;
791 
792     for (unsigned i = 0; i != LNumOps; ++i) {
793       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
794                                      LC->getOperand(i), RC->getOperand(i), DT,
795                                      Depth + 1);
796       if (X != 0)
797         return X;
798     }
799     EqCacheSCEV.unionSets(LHS, RHS);
800     return 0;
801   }
802 
803   case scUDivExpr: {
804     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
805     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
806 
807     // Lexicographically compare udiv expressions.
808     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
809                                    RC->getLHS(), DT, Depth + 1);
810     if (X != 0)
811       return X;
812     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
813                               RC->getRHS(), DT, Depth + 1);
814     if (X == 0)
815       EqCacheSCEV.unionSets(LHS, RHS);
816     return X;
817   }
818 
819   case scPtrToInt:
820   case scTruncate:
821   case scZeroExtend:
822   case scSignExtend: {
823     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
824     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
825 
826     // Compare cast expressions by operand.
827     auto X =
828         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
829                               RC->getOperand(), DT, Depth + 1);
830     if (X == 0)
831       EqCacheSCEV.unionSets(LHS, RHS);
832     return X;
833   }
834 
835   case scCouldNotCompute:
836     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
837   }
838   llvm_unreachable("Unknown SCEV kind!");
839 }
840 
841 /// Given a list of SCEV objects, order them by their complexity, and group
842 /// objects of the same complexity together by value.  When this routine is
843 /// finished, we know that any duplicates in the vector are consecutive and that
844 /// complexity is monotonically increasing.
845 ///
846 /// Note that we go take special precautions to ensure that we get deterministic
847 /// results from this routine.  In other words, we don't want the results of
848 /// this to depend on where the addresses of various SCEV objects happened to
849 /// land in memory.
850 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
851                               LoopInfo *LI, DominatorTree &DT) {
852   if (Ops.size() < 2) return;  // Noop
853 
854   EquivalenceClasses<const SCEV *> EqCacheSCEV;
855   EquivalenceClasses<const Value *> EqCacheValue;
856 
857   // Whether LHS has provably less complexity than RHS.
858   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
859     auto Complexity =
860         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
861     return Complexity && *Complexity < 0;
862   };
863   if (Ops.size() == 2) {
864     // This is the common case, which also happens to be trivially simple.
865     // Special case it.
866     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
867     if (IsLessComplex(RHS, LHS))
868       std::swap(LHS, RHS);
869     return;
870   }
871 
872   // Do the rough sort by complexity.
873   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
874     return IsLessComplex(LHS, RHS);
875   });
876 
877   // Now that we are sorted by complexity, group elements of the same
878   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
879   // be extremely short in practice.  Note that we take this approach because we
880   // do not want to depend on the addresses of the objects we are grouping.
881   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
882     const SCEV *S = Ops[i];
883     unsigned Complexity = S->getSCEVType();
884 
885     // If there are any objects of the same complexity and same value as this
886     // one, group them.
887     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
888       if (Ops[j] == S) { // Found a duplicate.
889         // Move it to immediately after i'th element.
890         std::swap(Ops[i+1], Ops[j]);
891         ++i;   // no need to rescan it.
892         if (i == e-2) return;  // Done!
893       }
894     }
895   }
896 }
897 
898 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
899 /// least HugeExprThreshold nodes).
900 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
901   return any_of(Ops, [](const SCEV *S) {
902     return S->getExpressionSize() >= HugeExprThreshold;
903   });
904 }
905 
906 //===----------------------------------------------------------------------===//
907 //                      Simple SCEV method implementations
908 //===----------------------------------------------------------------------===//
909 
910 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
911 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
912                                        ScalarEvolution &SE,
913                                        Type *ResultTy) {
914   // Handle the simplest case efficiently.
915   if (K == 1)
916     return SE.getTruncateOrZeroExtend(It, ResultTy);
917 
918   // We are using the following formula for BC(It, K):
919   //
920   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
921   //
922   // Suppose, W is the bitwidth of the return value.  We must be prepared for
923   // overflow.  Hence, we must assure that the result of our computation is
924   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
925   // safe in modular arithmetic.
926   //
927   // However, this code doesn't use exactly that formula; the formula it uses
928   // is something like the following, where T is the number of factors of 2 in
929   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
930   // exponentiation:
931   //
932   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
933   //
934   // This formula is trivially equivalent to the previous formula.  However,
935   // this formula can be implemented much more efficiently.  The trick is that
936   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
937   // arithmetic.  To do exact division in modular arithmetic, all we have
938   // to do is multiply by the inverse.  Therefore, this step can be done at
939   // width W.
940   //
941   // The next issue is how to safely do the division by 2^T.  The way this
942   // is done is by doing the multiplication step at a width of at least W + T
943   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
944   // when we perform the division by 2^T (which is equivalent to a right shift
945   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
946   // truncated out after the division by 2^T.
947   //
948   // In comparison to just directly using the first formula, this technique
949   // is much more efficient; using the first formula requires W * K bits,
950   // but this formula less than W + K bits. Also, the first formula requires
951   // a division step, whereas this formula only requires multiplies and shifts.
952   //
953   // It doesn't matter whether the subtraction step is done in the calculation
954   // width or the input iteration count's width; if the subtraction overflows,
955   // the result must be zero anyway.  We prefer here to do it in the width of
956   // the induction variable because it helps a lot for certain cases; CodeGen
957   // isn't smart enough to ignore the overflow, which leads to much less
958   // efficient code if the width of the subtraction is wider than the native
959   // register width.
960   //
961   // (It's possible to not widen at all by pulling out factors of 2 before
962   // the multiplication; for example, K=2 can be calculated as
963   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
964   // extra arithmetic, so it's not an obvious win, and it gets
965   // much more complicated for K > 3.)
966 
967   // Protection from insane SCEVs; this bound is conservative,
968   // but it probably doesn't matter.
969   if (K > 1000)
970     return SE.getCouldNotCompute();
971 
972   unsigned W = SE.getTypeSizeInBits(ResultTy);
973 
974   // Calculate K! / 2^T and T; we divide out the factors of two before
975   // multiplying for calculating K! / 2^T to avoid overflow.
976   // Other overflow doesn't matter because we only care about the bottom
977   // W bits of the result.
978   APInt OddFactorial(W, 1);
979   unsigned T = 1;
980   for (unsigned i = 3; i <= K; ++i) {
981     APInt Mult(W, i);
982     unsigned TwoFactors = Mult.countTrailingZeros();
983     T += TwoFactors;
984     Mult.lshrInPlace(TwoFactors);
985     OddFactorial *= Mult;
986   }
987 
988   // We need at least W + T bits for the multiplication step
989   unsigned CalculationBits = W + T;
990 
991   // Calculate 2^T, at width T+W.
992   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
993 
994   // Calculate the multiplicative inverse of K! / 2^T;
995   // this multiplication factor will perform the exact division by
996   // K! / 2^T.
997   APInt Mod = APInt::getSignedMinValue(W+1);
998   APInt MultiplyFactor = OddFactorial.zext(W+1);
999   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1000   MultiplyFactor = MultiplyFactor.trunc(W);
1001 
1002   // Calculate the product, at width T+W
1003   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1004                                                       CalculationBits);
1005   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1006   for (unsigned i = 1; i != K; ++i) {
1007     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1008     Dividend = SE.getMulExpr(Dividend,
1009                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1010   }
1011 
1012   // Divide by 2^T
1013   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1014 
1015   // Truncate the result, and divide by K! / 2^T.
1016 
1017   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1018                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1019 }
1020 
1021 /// Return the value of this chain of recurrences at the specified iteration
1022 /// number.  We can evaluate this recurrence by multiplying each element in the
1023 /// chain by the binomial coefficient corresponding to it.  In other words, we
1024 /// can evaluate {A,+,B,+,C,+,D} as:
1025 ///
1026 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1027 ///
1028 /// where BC(It, k) stands for binomial coefficient.
1029 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1030                                                 ScalarEvolution &SE) const {
1031   const SCEV *Result = getStart();
1032   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1033     // The computation is correct in the face of overflow provided that the
1034     // multiplication is performed _after_ the evaluation of the binomial
1035     // coefficient.
1036     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1037     if (isa<SCEVCouldNotCompute>(Coeff))
1038       return Coeff;
1039 
1040     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1041   }
1042   return Result;
1043 }
1044 
1045 //===----------------------------------------------------------------------===//
1046 //                    SCEV Expression folder implementations
1047 //===----------------------------------------------------------------------===//
1048 
1049 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty,
1050                                              unsigned Depth) {
1051   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1052   assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once.");
1053 
1054   // We could be called with an integer-typed operands during SCEV rewrites.
1055   // Since the operand is an integer already, just perform zext/trunc/self cast.
1056   if (!Op->getType()->isPointerTy())
1057     return getTruncateOrZeroExtend(Op, Ty);
1058 
1059   // What would be an ID for such a SCEV cast expression?
1060   FoldingSetNodeID ID;
1061   ID.AddInteger(scPtrToInt);
1062   ID.AddPointer(Op);
1063 
1064   void *IP = nullptr;
1065 
1066   // Is there already an expression for such a cast?
1067   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1068     return getTruncateOrZeroExtend(S, Ty);
1069 
1070   // If not, is this expression something we can't reduce any further?
1071   if (isa<SCEVUnknown>(Op)) {
1072     // Create an explicit cast node.
1073     // We can reuse the existing insert position since if we get here,
1074     // we won't have made any changes which would invalidate it.
1075     Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1076     assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(
1077                Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
1078            "We can only model ptrtoint if SCEV's effective (integer) type is "
1079            "sufficiently wide to represent all possible pointer values.");
1080     SCEV *S = new (SCEVAllocator)
1081         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1082     UniqueSCEVs.InsertNode(S, IP);
1083     addToLoopUseLists(S);
1084     return getTruncateOrZeroExtend(S, Ty);
1085   }
1086 
1087   assert(Depth == 0 &&
1088          "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.");
1089 
1090   // Otherwise, we've got some expression that is more complex than just a
1091   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1092   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1093   // only, and the expressions must otherwise be integer-typed.
1094   // So sink the cast down to the SCEVUnknown's.
1095 
1096   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1097   /// which computes a pointer-typed value, and rewrites the whole expression
1098   /// tree so that *all* the computations are done on integers, and the only
1099   /// pointer-typed operands in the expression are SCEVUnknown.
1100   class SCEVPtrToIntSinkingRewriter
1101       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1102     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1103 
1104   public:
1105     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1106 
1107     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1108       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1109       return Rewriter.visit(Scev);
1110     }
1111 
1112     const SCEV *visit(const SCEV *S) {
1113       Type *STy = S->getType();
1114       // If the expression is not pointer-typed, just keep it as-is.
1115       if (!STy->isPointerTy())
1116         return S;
1117       // Else, recursively sink the cast down into it.
1118       return Base::visit(S);
1119     }
1120 
1121     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1122       SmallVector<const SCEV *, 2> Operands;
1123       bool Changed = false;
1124       for (auto *Op : Expr->operands()) {
1125         Operands.push_back(visit(Op));
1126         Changed |= Op != Operands.back();
1127       }
1128       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1129     }
1130 
1131     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1132       SmallVector<const SCEV *, 2> Operands;
1133       bool Changed = false;
1134       for (auto *Op : Expr->operands()) {
1135         Operands.push_back(visit(Op));
1136         Changed |= Op != Operands.back();
1137       }
1138       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1139     }
1140 
1141     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1142       Type *ExprPtrTy = Expr->getType();
1143       assert(ExprPtrTy->isPointerTy() &&
1144              "Should only reach pointer-typed SCEVUnknown's.");
1145       Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy);
1146       return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1);
1147     }
1148   };
1149 
1150   // And actually perform the cast sinking.
1151   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1152   assert(IntOp->getType()->isIntegerTy() &&
1153          "We must have succeeded in sinking the cast, "
1154          "and ending up with an integer-typed expression!");
1155   return getTruncateOrZeroExtend(IntOp, Ty);
1156 }
1157 
1158 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1159                                              unsigned Depth) {
1160   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1161          "This is not a truncating conversion!");
1162   assert(isSCEVable(Ty) &&
1163          "This is not a conversion to a SCEVable type!");
1164   Ty = getEffectiveSCEVType(Ty);
1165 
1166   FoldingSetNodeID ID;
1167   ID.AddInteger(scTruncate);
1168   ID.AddPointer(Op);
1169   ID.AddPointer(Ty);
1170   void *IP = nullptr;
1171   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1172 
1173   // Fold if the operand is constant.
1174   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1175     return getConstant(
1176       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1177 
1178   // trunc(trunc(x)) --> trunc(x)
1179   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1180     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1181 
1182   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1183   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1184     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1185 
1186   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1187   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1188     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1189 
1190   if (Depth > MaxCastDepth) {
1191     SCEV *S =
1192         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1193     UniqueSCEVs.InsertNode(S, IP);
1194     addToLoopUseLists(S);
1195     return S;
1196   }
1197 
1198   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1199   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1200   // if after transforming we have at most one truncate, not counting truncates
1201   // that replace other casts.
1202   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1203     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1204     SmallVector<const SCEV *, 4> Operands;
1205     unsigned numTruncs = 0;
1206     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1207          ++i) {
1208       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1209       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1210           isa<SCEVTruncateExpr>(S))
1211         numTruncs++;
1212       Operands.push_back(S);
1213     }
1214     if (numTruncs < 2) {
1215       if (isa<SCEVAddExpr>(Op))
1216         return getAddExpr(Operands);
1217       else if (isa<SCEVMulExpr>(Op))
1218         return getMulExpr(Operands);
1219       else
1220         llvm_unreachable("Unexpected SCEV type for Op.");
1221     }
1222     // Although we checked in the beginning that ID is not in the cache, it is
1223     // possible that during recursion and different modification ID was inserted
1224     // into the cache. So if we find it, just return it.
1225     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1226       return S;
1227   }
1228 
1229   // If the input value is a chrec scev, truncate the chrec's operands.
1230   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1231     SmallVector<const SCEV *, 4> Operands;
1232     for (const SCEV *Op : AddRec->operands())
1233       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1234     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1235   }
1236 
1237   // Return zero if truncating to known zeros.
1238   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1239   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1240     return getZero(Ty);
1241 
1242   // The cast wasn't folded; create an explicit cast node. We can reuse
1243   // the existing insert position since if we get here, we won't have
1244   // made any changes which would invalidate it.
1245   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1246                                                  Op, Ty);
1247   UniqueSCEVs.InsertNode(S, IP);
1248   addToLoopUseLists(S);
1249   return S;
1250 }
1251 
1252 // Get the limit of a recurrence such that incrementing by Step cannot cause
1253 // signed overflow as long as the value of the recurrence within the
1254 // loop does not exceed this limit before incrementing.
1255 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1256                                                  ICmpInst::Predicate *Pred,
1257                                                  ScalarEvolution *SE) {
1258   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1259   if (SE->isKnownPositive(Step)) {
1260     *Pred = ICmpInst::ICMP_SLT;
1261     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1262                            SE->getSignedRangeMax(Step));
1263   }
1264   if (SE->isKnownNegative(Step)) {
1265     *Pred = ICmpInst::ICMP_SGT;
1266     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1267                            SE->getSignedRangeMin(Step));
1268   }
1269   return nullptr;
1270 }
1271 
1272 // Get the limit of a recurrence such that incrementing by Step cannot cause
1273 // unsigned overflow as long as the value of the recurrence within the loop does
1274 // not exceed this limit before incrementing.
1275 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1276                                                    ICmpInst::Predicate *Pred,
1277                                                    ScalarEvolution *SE) {
1278   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1279   *Pred = ICmpInst::ICMP_ULT;
1280 
1281   return SE->getConstant(APInt::getMinValue(BitWidth) -
1282                          SE->getUnsignedRangeMax(Step));
1283 }
1284 
1285 namespace {
1286 
1287 struct ExtendOpTraitsBase {
1288   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1289                                                           unsigned);
1290 };
1291 
1292 // Used to make code generic over signed and unsigned overflow.
1293 template <typename ExtendOp> struct ExtendOpTraits {
1294   // Members present:
1295   //
1296   // static const SCEV::NoWrapFlags WrapType;
1297   //
1298   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1299   //
1300   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1301   //                                           ICmpInst::Predicate *Pred,
1302   //                                           ScalarEvolution *SE);
1303 };
1304 
1305 template <>
1306 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1307   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1308 
1309   static const GetExtendExprTy GetExtendExpr;
1310 
1311   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1312                                              ICmpInst::Predicate *Pred,
1313                                              ScalarEvolution *SE) {
1314     return getSignedOverflowLimitForStep(Step, Pred, SE);
1315   }
1316 };
1317 
1318 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1319     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1320 
1321 template <>
1322 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1323   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1324 
1325   static const GetExtendExprTy GetExtendExpr;
1326 
1327   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1328                                              ICmpInst::Predicate *Pred,
1329                                              ScalarEvolution *SE) {
1330     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1331   }
1332 };
1333 
1334 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1335     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1336 
1337 } // end anonymous namespace
1338 
1339 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1340 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1341 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1342 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1343 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1344 // expression "Step + sext/zext(PreIncAR)" is congruent with
1345 // "sext/zext(PostIncAR)"
1346 template <typename ExtendOpTy>
1347 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1348                                         ScalarEvolution *SE, unsigned Depth) {
1349   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1350   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1351 
1352   const Loop *L = AR->getLoop();
1353   const SCEV *Start = AR->getStart();
1354   const SCEV *Step = AR->getStepRecurrence(*SE);
1355 
1356   // Check for a simple looking step prior to loop entry.
1357   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1358   if (!SA)
1359     return nullptr;
1360 
1361   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1362   // subtraction is expensive. For this purpose, perform a quick and dirty
1363   // difference, by checking for Step in the operand list.
1364   SmallVector<const SCEV *, 4> DiffOps;
1365   for (const SCEV *Op : SA->operands())
1366     if (Op != Step)
1367       DiffOps.push_back(Op);
1368 
1369   if (DiffOps.size() == SA->getNumOperands())
1370     return nullptr;
1371 
1372   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1373   // `Step`:
1374 
1375   // 1. NSW/NUW flags on the step increment.
1376   auto PreStartFlags =
1377     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1378   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1379   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1380       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1381 
1382   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1383   // "S+X does not sign/unsign-overflow".
1384   //
1385 
1386   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1387   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1388       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1389     return PreStart;
1390 
1391   // 2. Direct overflow check on the step operation's expression.
1392   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1393   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1394   const SCEV *OperandExtendedStart =
1395       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1396                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1397   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1398     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1399       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1400       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1401       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1402       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1403     }
1404     return PreStart;
1405   }
1406 
1407   // 3. Loop precondition.
1408   ICmpInst::Predicate Pred;
1409   const SCEV *OverflowLimit =
1410       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1411 
1412   if (OverflowLimit &&
1413       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1414     return PreStart;
1415 
1416   return nullptr;
1417 }
1418 
1419 // Get the normalized zero or sign extended expression for this AddRec's Start.
1420 template <typename ExtendOpTy>
1421 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1422                                         ScalarEvolution *SE,
1423                                         unsigned Depth) {
1424   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1425 
1426   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1427   if (!PreStart)
1428     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1429 
1430   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1431                                              Depth),
1432                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1433 }
1434 
1435 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1436 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1437 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1438 //
1439 // Formally:
1440 //
1441 //     {S,+,X} == {S-T,+,X} + T
1442 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1443 //
1444 // If ({S-T,+,X} + T) does not overflow  ... (1)
1445 //
1446 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1447 //
1448 // If {S-T,+,X} does not overflow  ... (2)
1449 //
1450 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1451 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1452 //
1453 // If (S-T)+T does not overflow  ... (3)
1454 //
1455 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1456 //      == {Ext(S),+,Ext(X)} == LHS
1457 //
1458 // Thus, if (1), (2) and (3) are true for some T, then
1459 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1460 //
1461 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1462 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1463 // to check for (1) and (2).
1464 //
1465 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1466 // is `Delta` (defined below).
1467 template <typename ExtendOpTy>
1468 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1469                                                 const SCEV *Step,
1470                                                 const Loop *L) {
1471   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1472 
1473   // We restrict `Start` to a constant to prevent SCEV from spending too much
1474   // time here.  It is correct (but more expensive) to continue with a
1475   // non-constant `Start` and do a general SCEV subtraction to compute
1476   // `PreStart` below.
1477   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1478   if (!StartC)
1479     return false;
1480 
1481   APInt StartAI = StartC->getAPInt();
1482 
1483   for (unsigned Delta : {-2, -1, 1, 2}) {
1484     const SCEV *PreStart = getConstant(StartAI - Delta);
1485 
1486     FoldingSetNodeID ID;
1487     ID.AddInteger(scAddRecExpr);
1488     ID.AddPointer(PreStart);
1489     ID.AddPointer(Step);
1490     ID.AddPointer(L);
1491     void *IP = nullptr;
1492     const auto *PreAR =
1493       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1494 
1495     // Give up if we don't already have the add recurrence we need because
1496     // actually constructing an add recurrence is relatively expensive.
1497     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1498       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1499       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1500       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1501           DeltaS, &Pred, this);
1502       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1503         return true;
1504     }
1505   }
1506 
1507   return false;
1508 }
1509 
1510 // Finds an integer D for an expression (C + x + y + ...) such that the top
1511 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1512 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1513 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1514 // the (C + x + y + ...) expression is \p WholeAddExpr.
1515 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1516                                             const SCEVConstant *ConstantTerm,
1517                                             const SCEVAddExpr *WholeAddExpr) {
1518   const APInt &C = ConstantTerm->getAPInt();
1519   const unsigned BitWidth = C.getBitWidth();
1520   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1521   uint32_t TZ = BitWidth;
1522   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1523     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1524   if (TZ) {
1525     // Set D to be as many least significant bits of C as possible while still
1526     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1527     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1528   }
1529   return APInt(BitWidth, 0);
1530 }
1531 
1532 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1533 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1534 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1535 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1536 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1537                                             const APInt &ConstantStart,
1538                                             const SCEV *Step) {
1539   const unsigned BitWidth = ConstantStart.getBitWidth();
1540   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1541   if (TZ)
1542     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1543                          : ConstantStart;
1544   return APInt(BitWidth, 0);
1545 }
1546 
1547 const SCEV *
1548 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1549   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1550          "This is not an extending conversion!");
1551   assert(isSCEVable(Ty) &&
1552          "This is not a conversion to a SCEVable type!");
1553   Ty = getEffectiveSCEVType(Ty);
1554 
1555   // Fold if the operand is constant.
1556   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1557     return getConstant(
1558       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1559 
1560   // zext(zext(x)) --> zext(x)
1561   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1562     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1563 
1564   // Before doing any expensive analysis, check to see if we've already
1565   // computed a SCEV for this Op and Ty.
1566   FoldingSetNodeID ID;
1567   ID.AddInteger(scZeroExtend);
1568   ID.AddPointer(Op);
1569   ID.AddPointer(Ty);
1570   void *IP = nullptr;
1571   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1572   if (Depth > MaxCastDepth) {
1573     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1574                                                      Op, Ty);
1575     UniqueSCEVs.InsertNode(S, IP);
1576     addToLoopUseLists(S);
1577     return S;
1578   }
1579 
1580   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1581   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1582     // It's possible the bits taken off by the truncate were all zero bits. If
1583     // so, we should be able to simplify this further.
1584     const SCEV *X = ST->getOperand();
1585     ConstantRange CR = getUnsignedRange(X);
1586     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1587     unsigned NewBits = getTypeSizeInBits(Ty);
1588     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1589             CR.zextOrTrunc(NewBits)))
1590       return getTruncateOrZeroExtend(X, Ty, Depth);
1591   }
1592 
1593   // If the input value is a chrec scev, and we can prove that the value
1594   // did not overflow the old, smaller, value, we can zero extend all of the
1595   // operands (often constants).  This allows analysis of something like
1596   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1597   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1598     if (AR->isAffine()) {
1599       const SCEV *Start = AR->getStart();
1600       const SCEV *Step = AR->getStepRecurrence(*this);
1601       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1602       const Loop *L = AR->getLoop();
1603 
1604       if (!AR->hasNoUnsignedWrap()) {
1605         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1606         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1607       }
1608 
1609       // If we have special knowledge that this addrec won't overflow,
1610       // we don't need to do any further analysis.
1611       if (AR->hasNoUnsignedWrap())
1612         return getAddRecExpr(
1613             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1614             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1615 
1616       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1617       // Note that this serves two purposes: It filters out loops that are
1618       // simply not analyzable, and it covers the case where this code is
1619       // being called from within backedge-taken count analysis, such that
1620       // attempting to ask for the backedge-taken count would likely result
1621       // in infinite recursion. In the later case, the analysis code will
1622       // cope with a conservative value, and it will take care to purge
1623       // that value once it has finished.
1624       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1625       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1626         // Manually compute the final value for AR, checking for overflow.
1627 
1628         // Check whether the backedge-taken count can be losslessly casted to
1629         // the addrec's type. The count is always unsigned.
1630         const SCEV *CastedMaxBECount =
1631             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1632         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1633             CastedMaxBECount, MaxBECount->getType(), Depth);
1634         if (MaxBECount == RecastedMaxBECount) {
1635           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1636           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1637           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1638                                         SCEV::FlagAnyWrap, Depth + 1);
1639           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1640                                                           SCEV::FlagAnyWrap,
1641                                                           Depth + 1),
1642                                                WideTy, Depth + 1);
1643           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1644           const SCEV *WideMaxBECount =
1645             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1646           const SCEV *OperandExtendedAdd =
1647             getAddExpr(WideStart,
1648                        getMulExpr(WideMaxBECount,
1649                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1650                                   SCEV::FlagAnyWrap, Depth + 1),
1651                        SCEV::FlagAnyWrap, Depth + 1);
1652           if (ZAdd == OperandExtendedAdd) {
1653             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1654             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1655             // Return the expression with the addrec on the outside.
1656             return getAddRecExpr(
1657                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1658                                                          Depth + 1),
1659                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1660                 AR->getNoWrapFlags());
1661           }
1662           // Similar to above, only this time treat the step value as signed.
1663           // This covers loops that count down.
1664           OperandExtendedAdd =
1665             getAddExpr(WideStart,
1666                        getMulExpr(WideMaxBECount,
1667                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1668                                   SCEV::FlagAnyWrap, Depth + 1),
1669                        SCEV::FlagAnyWrap, Depth + 1);
1670           if (ZAdd == OperandExtendedAdd) {
1671             // Cache knowledge of AR NW, which is propagated to this AddRec.
1672             // Negative step causes unsigned wrap, but it still can't self-wrap.
1673             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1674             // Return the expression with the addrec on the outside.
1675             return getAddRecExpr(
1676                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1677                                                          Depth + 1),
1678                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1679                 AR->getNoWrapFlags());
1680           }
1681         }
1682       }
1683 
1684       // Normally, in the cases we can prove no-overflow via a
1685       // backedge guarding condition, we can also compute a backedge
1686       // taken count for the loop.  The exceptions are assumptions and
1687       // guards present in the loop -- SCEV is not great at exploiting
1688       // these to compute max backedge taken counts, but can still use
1689       // these to prove lack of overflow.  Use this fact to avoid
1690       // doing extra work that may not pay off.
1691       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1692           !AC.assumptions().empty()) {
1693 
1694         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1695         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1696         if (AR->hasNoUnsignedWrap()) {
1697           // Same as nuw case above - duplicated here to avoid a compile time
1698           // issue.  It's not clear that the order of checks does matter, but
1699           // it's one of two issue possible causes for a change which was
1700           // reverted.  Be conservative for the moment.
1701           return getAddRecExpr(
1702                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1703                                                          Depth + 1),
1704                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1705                 AR->getNoWrapFlags());
1706         }
1707 
1708         // For a negative step, we can extend the operands iff doing so only
1709         // traverses values in the range zext([0,UINT_MAX]).
1710         if (isKnownNegative(Step)) {
1711           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1712                                       getSignedRangeMin(Step));
1713           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1714               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1715             // Cache knowledge of AR NW, which is propagated to this
1716             // AddRec.  Negative step causes unsigned wrap, but it
1717             // still can't self-wrap.
1718             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1719             // Return the expression with the addrec on the outside.
1720             return getAddRecExpr(
1721                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1722                                                          Depth + 1),
1723                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1724                 AR->getNoWrapFlags());
1725           }
1726         }
1727       }
1728 
1729       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1730       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1731       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1732       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1733         const APInt &C = SC->getAPInt();
1734         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1735         if (D != 0) {
1736           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1737           const SCEV *SResidual =
1738               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1739           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1740           return getAddExpr(SZExtD, SZExtR,
1741                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1742                             Depth + 1);
1743         }
1744       }
1745 
1746       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1747         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1748         return getAddRecExpr(
1749             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1750             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1751       }
1752     }
1753 
1754   // zext(A % B) --> zext(A) % zext(B)
1755   {
1756     const SCEV *LHS;
1757     const SCEV *RHS;
1758     if (matchURem(Op, LHS, RHS))
1759       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1760                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1761   }
1762 
1763   // zext(A / B) --> zext(A) / zext(B).
1764   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1765     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1766                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1767 
1768   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1769     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1770     if (SA->hasNoUnsignedWrap()) {
1771       // If the addition does not unsign overflow then we can, by definition,
1772       // commute the zero extension with the addition operation.
1773       SmallVector<const SCEV *, 4> Ops;
1774       for (const auto *Op : SA->operands())
1775         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1776       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1777     }
1778 
1779     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1780     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1781     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1782     //
1783     // Often address arithmetics contain expressions like
1784     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1785     // This transformation is useful while proving that such expressions are
1786     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1787     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1788       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1789       if (D != 0) {
1790         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1791         const SCEV *SResidual =
1792             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1793         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1794         return getAddExpr(SZExtD, SZExtR,
1795                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1796                           Depth + 1);
1797       }
1798     }
1799   }
1800 
1801   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1802     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1803     if (SM->hasNoUnsignedWrap()) {
1804       // If the multiply does not unsign overflow then we can, by definition,
1805       // commute the zero extension with the multiply operation.
1806       SmallVector<const SCEV *, 4> Ops;
1807       for (const auto *Op : SM->operands())
1808         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1809       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1810     }
1811 
1812     // zext(2^K * (trunc X to iN)) to iM ->
1813     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1814     //
1815     // Proof:
1816     //
1817     //     zext(2^K * (trunc X to iN)) to iM
1818     //   = zext((trunc X to iN) << K) to iM
1819     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1820     //     (because shl removes the top K bits)
1821     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1822     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1823     //
1824     if (SM->getNumOperands() == 2)
1825       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1826         if (MulLHS->getAPInt().isPowerOf2())
1827           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1828             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1829                                MulLHS->getAPInt().logBase2();
1830             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1831             return getMulExpr(
1832                 getZeroExtendExpr(MulLHS, Ty),
1833                 getZeroExtendExpr(
1834                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1835                 SCEV::FlagNUW, Depth + 1);
1836           }
1837   }
1838 
1839   // The cast wasn't folded; create an explicit cast node.
1840   // Recompute the insert position, as it may have been invalidated.
1841   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1842   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1843                                                    Op, Ty);
1844   UniqueSCEVs.InsertNode(S, IP);
1845   addToLoopUseLists(S);
1846   return S;
1847 }
1848 
1849 const SCEV *
1850 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1851   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1852          "This is not an extending conversion!");
1853   assert(isSCEVable(Ty) &&
1854          "This is not a conversion to a SCEVable type!");
1855   Ty = getEffectiveSCEVType(Ty);
1856 
1857   // Fold if the operand is constant.
1858   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1859     return getConstant(
1860       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1861 
1862   // sext(sext(x)) --> sext(x)
1863   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1864     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1865 
1866   // sext(zext(x)) --> zext(x)
1867   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1868     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1869 
1870   // Before doing any expensive analysis, check to see if we've already
1871   // computed a SCEV for this Op and Ty.
1872   FoldingSetNodeID ID;
1873   ID.AddInteger(scSignExtend);
1874   ID.AddPointer(Op);
1875   ID.AddPointer(Ty);
1876   void *IP = nullptr;
1877   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1878   // Limit recursion depth.
1879   if (Depth > MaxCastDepth) {
1880     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1881                                                      Op, Ty);
1882     UniqueSCEVs.InsertNode(S, IP);
1883     addToLoopUseLists(S);
1884     return S;
1885   }
1886 
1887   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1888   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1889     // It's possible the bits taken off by the truncate were all sign bits. If
1890     // so, we should be able to simplify this further.
1891     const SCEV *X = ST->getOperand();
1892     ConstantRange CR = getSignedRange(X);
1893     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1894     unsigned NewBits = getTypeSizeInBits(Ty);
1895     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1896             CR.sextOrTrunc(NewBits)))
1897       return getTruncateOrSignExtend(X, Ty, Depth);
1898   }
1899 
1900   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1901     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1902     if (SA->hasNoSignedWrap()) {
1903       // If the addition does not sign overflow then we can, by definition,
1904       // commute the sign extension with the addition operation.
1905       SmallVector<const SCEV *, 4> Ops;
1906       for (const auto *Op : SA->operands())
1907         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1908       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1909     }
1910 
1911     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1912     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1913     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1914     //
1915     // For instance, this will bring two seemingly different expressions:
1916     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1917     //         sext(6 + 20 * %x + 24 * %y)
1918     // to the same form:
1919     //     2 + sext(4 + 20 * %x + 24 * %y)
1920     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1921       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1922       if (D != 0) {
1923         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1924         const SCEV *SResidual =
1925             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1926         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1927         return getAddExpr(SSExtD, SSExtR,
1928                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1929                           Depth + 1);
1930       }
1931     }
1932   }
1933   // If the input value is a chrec scev, and we can prove that the value
1934   // did not overflow the old, smaller, value, we can sign extend all of the
1935   // operands (often constants).  This allows analysis of something like
1936   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1937   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1938     if (AR->isAffine()) {
1939       const SCEV *Start = AR->getStart();
1940       const SCEV *Step = AR->getStepRecurrence(*this);
1941       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1942       const Loop *L = AR->getLoop();
1943 
1944       if (!AR->hasNoSignedWrap()) {
1945         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1946         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1947       }
1948 
1949       // If we have special knowledge that this addrec won't overflow,
1950       // we don't need to do any further analysis.
1951       if (AR->hasNoSignedWrap())
1952         return getAddRecExpr(
1953             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1954             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1955 
1956       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1957       // Note that this serves two purposes: It filters out loops that are
1958       // simply not analyzable, and it covers the case where this code is
1959       // being called from within backedge-taken count analysis, such that
1960       // attempting to ask for the backedge-taken count would likely result
1961       // in infinite recursion. In the later case, the analysis code will
1962       // cope with a conservative value, and it will take care to purge
1963       // that value once it has finished.
1964       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1965       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1966         // Manually compute the final value for AR, checking for
1967         // overflow.
1968 
1969         // Check whether the backedge-taken count can be losslessly casted to
1970         // the addrec's type. The count is always unsigned.
1971         const SCEV *CastedMaxBECount =
1972             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1973         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1974             CastedMaxBECount, MaxBECount->getType(), Depth);
1975         if (MaxBECount == RecastedMaxBECount) {
1976           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1977           // Check whether Start+Step*MaxBECount has no signed overflow.
1978           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1979                                         SCEV::FlagAnyWrap, Depth + 1);
1980           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1981                                                           SCEV::FlagAnyWrap,
1982                                                           Depth + 1),
1983                                                WideTy, Depth + 1);
1984           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1985           const SCEV *WideMaxBECount =
1986             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1987           const SCEV *OperandExtendedAdd =
1988             getAddExpr(WideStart,
1989                        getMulExpr(WideMaxBECount,
1990                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1991                                   SCEV::FlagAnyWrap, Depth + 1),
1992                        SCEV::FlagAnyWrap, Depth + 1);
1993           if (SAdd == OperandExtendedAdd) {
1994             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1995             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1996             // Return the expression with the addrec on the outside.
1997             return getAddRecExpr(
1998                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1999                                                          Depth + 1),
2000                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2001                 AR->getNoWrapFlags());
2002           }
2003           // Similar to above, only this time treat the step value as unsigned.
2004           // This covers loops that count up with an unsigned step.
2005           OperandExtendedAdd =
2006             getAddExpr(WideStart,
2007                        getMulExpr(WideMaxBECount,
2008                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2009                                   SCEV::FlagAnyWrap, Depth + 1),
2010                        SCEV::FlagAnyWrap, Depth + 1);
2011           if (SAdd == OperandExtendedAdd) {
2012             // If AR wraps around then
2013             //
2014             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2015             // => SAdd != OperandExtendedAdd
2016             //
2017             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2018             // (SAdd == OperandExtendedAdd => AR is NW)
2019 
2020             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2021 
2022             // Return the expression with the addrec on the outside.
2023             return getAddRecExpr(
2024                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2025                                                          Depth + 1),
2026                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2027                 AR->getNoWrapFlags());
2028           }
2029         }
2030       }
2031 
2032       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2033       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2034       if (AR->hasNoSignedWrap()) {
2035         // Same as nsw case above - duplicated here to avoid a compile time
2036         // issue.  It's not clear that the order of checks does matter, but
2037         // it's one of two issue possible causes for a change which was
2038         // reverted.  Be conservative for the moment.
2039         return getAddRecExpr(
2040             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2041             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2042       }
2043 
2044       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2045       // if D + (C - D + Step * n) could be proven to not signed wrap
2046       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2047       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2048         const APInt &C = SC->getAPInt();
2049         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2050         if (D != 0) {
2051           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2052           const SCEV *SResidual =
2053               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2054           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2055           return getAddExpr(SSExtD, SSExtR,
2056                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2057                             Depth + 1);
2058         }
2059       }
2060 
2061       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2062         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2063         return getAddRecExpr(
2064             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2065             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2066       }
2067     }
2068 
2069   // If the input value is provably positive and we could not simplify
2070   // away the sext build a zext instead.
2071   if (isKnownNonNegative(Op))
2072     return getZeroExtendExpr(Op, Ty, Depth + 1);
2073 
2074   // The cast wasn't folded; create an explicit cast node.
2075   // Recompute the insert position, as it may have been invalidated.
2076   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2077   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2078                                                    Op, Ty);
2079   UniqueSCEVs.InsertNode(S, IP);
2080   addToLoopUseLists(S);
2081   return S;
2082 }
2083 
2084 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2085 /// unspecified bits out to the given type.
2086 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2087                                               Type *Ty) {
2088   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2089          "This is not an extending conversion!");
2090   assert(isSCEVable(Ty) &&
2091          "This is not a conversion to a SCEVable type!");
2092   Ty = getEffectiveSCEVType(Ty);
2093 
2094   // Sign-extend negative constants.
2095   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2096     if (SC->getAPInt().isNegative())
2097       return getSignExtendExpr(Op, Ty);
2098 
2099   // Peel off a truncate cast.
2100   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2101     const SCEV *NewOp = T->getOperand();
2102     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2103       return getAnyExtendExpr(NewOp, Ty);
2104     return getTruncateOrNoop(NewOp, Ty);
2105   }
2106 
2107   // Next try a zext cast. If the cast is folded, use it.
2108   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2109   if (!isa<SCEVZeroExtendExpr>(ZExt))
2110     return ZExt;
2111 
2112   // Next try a sext cast. If the cast is folded, use it.
2113   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2114   if (!isa<SCEVSignExtendExpr>(SExt))
2115     return SExt;
2116 
2117   // Force the cast to be folded into the operands of an addrec.
2118   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2119     SmallVector<const SCEV *, 4> Ops;
2120     for (const SCEV *Op : AR->operands())
2121       Ops.push_back(getAnyExtendExpr(Op, Ty));
2122     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2123   }
2124 
2125   // If the expression is obviously signed, use the sext cast value.
2126   if (isa<SCEVSMaxExpr>(Op))
2127     return SExt;
2128 
2129   // Absent any other information, use the zext cast value.
2130   return ZExt;
2131 }
2132 
2133 /// Process the given Ops list, which is a list of operands to be added under
2134 /// the given scale, update the given map. This is a helper function for
2135 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2136 /// that would form an add expression like this:
2137 ///
2138 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2139 ///
2140 /// where A and B are constants, update the map with these values:
2141 ///
2142 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2143 ///
2144 /// and add 13 + A*B*29 to AccumulatedConstant.
2145 /// This will allow getAddRecExpr to produce this:
2146 ///
2147 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2148 ///
2149 /// This form often exposes folding opportunities that are hidden in
2150 /// the original operand list.
2151 ///
2152 /// Return true iff it appears that any interesting folding opportunities
2153 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2154 /// the common case where no interesting opportunities are present, and
2155 /// is also used as a check to avoid infinite recursion.
2156 static bool
2157 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2158                              SmallVectorImpl<const SCEV *> &NewOps,
2159                              APInt &AccumulatedConstant,
2160                              const SCEV *const *Ops, size_t NumOperands,
2161                              const APInt &Scale,
2162                              ScalarEvolution &SE) {
2163   bool Interesting = false;
2164 
2165   // Iterate over the add operands. They are sorted, with constants first.
2166   unsigned i = 0;
2167   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2168     ++i;
2169     // Pull a buried constant out to the outside.
2170     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2171       Interesting = true;
2172     AccumulatedConstant += Scale * C->getAPInt();
2173   }
2174 
2175   // Next comes everything else. We're especially interested in multiplies
2176   // here, but they're in the middle, so just visit the rest with one loop.
2177   for (; i != NumOperands; ++i) {
2178     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2179     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2180       APInt NewScale =
2181           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2182       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2183         // A multiplication of a constant with another add; recurse.
2184         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2185         Interesting |=
2186           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2187                                        Add->op_begin(), Add->getNumOperands(),
2188                                        NewScale, SE);
2189       } else {
2190         // A multiplication of a constant with some other value. Update
2191         // the map.
2192         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2193         const SCEV *Key = SE.getMulExpr(MulOps);
2194         auto Pair = M.insert({Key, NewScale});
2195         if (Pair.second) {
2196           NewOps.push_back(Pair.first->first);
2197         } else {
2198           Pair.first->second += NewScale;
2199           // The map already had an entry for this value, which may indicate
2200           // a folding opportunity.
2201           Interesting = true;
2202         }
2203       }
2204     } else {
2205       // An ordinary operand. Update the map.
2206       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2207           M.insert({Ops[i], Scale});
2208       if (Pair.second) {
2209         NewOps.push_back(Pair.first->first);
2210       } else {
2211         Pair.first->second += Scale;
2212         // The map already had an entry for this value, which may indicate
2213         // a folding opportunity.
2214         Interesting = true;
2215       }
2216     }
2217   }
2218 
2219   return Interesting;
2220 }
2221 
2222 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2223 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2224 // can't-overflow flags for the operation if possible.
2225 static SCEV::NoWrapFlags
2226 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2227                       const ArrayRef<const SCEV *> Ops,
2228                       SCEV::NoWrapFlags Flags) {
2229   using namespace std::placeholders;
2230 
2231   using OBO = OverflowingBinaryOperator;
2232 
2233   bool CanAnalyze =
2234       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2235   (void)CanAnalyze;
2236   assert(CanAnalyze && "don't call from other places!");
2237 
2238   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2239   SCEV::NoWrapFlags SignOrUnsignWrap =
2240       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2241 
2242   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2243   auto IsKnownNonNegative = [&](const SCEV *S) {
2244     return SE->isKnownNonNegative(S);
2245   };
2246 
2247   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2248     Flags =
2249         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2250 
2251   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2252 
2253   if (SignOrUnsignWrap != SignOrUnsignMask &&
2254       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2255       isa<SCEVConstant>(Ops[0])) {
2256 
2257     auto Opcode = [&] {
2258       switch (Type) {
2259       case scAddExpr:
2260         return Instruction::Add;
2261       case scMulExpr:
2262         return Instruction::Mul;
2263       default:
2264         llvm_unreachable("Unexpected SCEV op.");
2265       }
2266     }();
2267 
2268     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2269 
2270     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2271     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2272       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2273           Opcode, C, OBO::NoSignedWrap);
2274       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2275         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2276     }
2277 
2278     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2279     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2280       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2281           Opcode, C, OBO::NoUnsignedWrap);
2282       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2283         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2284     }
2285   }
2286 
2287   return Flags;
2288 }
2289 
2290 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2291   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2292 }
2293 
2294 /// Get a canonical add expression, or something simpler if possible.
2295 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2296                                         SCEV::NoWrapFlags OrigFlags,
2297                                         unsigned Depth) {
2298   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2299          "only nuw or nsw allowed");
2300   assert(!Ops.empty() && "Cannot get empty add!");
2301   if (Ops.size() == 1) return Ops[0];
2302 #ifndef NDEBUG
2303   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2304   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2305     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2306            "SCEVAddExpr operand types don't match!");
2307 #endif
2308 
2309   // Sort by complexity, this groups all similar expression types together.
2310   GroupByComplexity(Ops, &LI, DT);
2311 
2312   // If there are any constants, fold them together.
2313   unsigned Idx = 0;
2314   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2315     ++Idx;
2316     assert(Idx < Ops.size());
2317     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2318       // We found two constants, fold them together!
2319       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2320       if (Ops.size() == 2) return Ops[0];
2321       Ops.erase(Ops.begin()+1);  // Erase the folded element
2322       LHSC = cast<SCEVConstant>(Ops[0]);
2323     }
2324 
2325     // If we are left with a constant zero being added, strip it off.
2326     if (LHSC->getValue()->isZero()) {
2327       Ops.erase(Ops.begin());
2328       --Idx;
2329     }
2330 
2331     if (Ops.size() == 1) return Ops[0];
2332   }
2333 
2334   // Delay expensive flag strengthening until necessary.
2335   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2336     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2337   };
2338 
2339   // Limit recursion calls depth.
2340   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2341     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2342 
2343   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2344     // Don't strengthen flags if we have no new information.
2345     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2346     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2347       Add->setNoWrapFlags(ComputeFlags(Ops));
2348     return S;
2349   }
2350 
2351   // Okay, check to see if the same value occurs in the operand list more than
2352   // once.  If so, merge them together into an multiply expression.  Since we
2353   // sorted the list, these values are required to be adjacent.
2354   Type *Ty = Ops[0]->getType();
2355   bool FoundMatch = false;
2356   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2357     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2358       // Scan ahead to count how many equal operands there are.
2359       unsigned Count = 2;
2360       while (i+Count != e && Ops[i+Count] == Ops[i])
2361         ++Count;
2362       // Merge the values into a multiply.
2363       const SCEV *Scale = getConstant(Ty, Count);
2364       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2365       if (Ops.size() == Count)
2366         return Mul;
2367       Ops[i] = Mul;
2368       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2369       --i; e -= Count - 1;
2370       FoundMatch = true;
2371     }
2372   if (FoundMatch)
2373     return getAddExpr(Ops, OrigFlags, Depth + 1);
2374 
2375   // Check for truncates. If all the operands are truncated from the same
2376   // type, see if factoring out the truncate would permit the result to be
2377   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2378   // if the contents of the resulting outer trunc fold to something simple.
2379   auto FindTruncSrcType = [&]() -> Type * {
2380     // We're ultimately looking to fold an addrec of truncs and muls of only
2381     // constants and truncs, so if we find any other types of SCEV
2382     // as operands of the addrec then we bail and return nullptr here.
2383     // Otherwise, we return the type of the operand of a trunc that we find.
2384     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2385       return T->getOperand()->getType();
2386     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2387       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2388       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2389         return T->getOperand()->getType();
2390     }
2391     return nullptr;
2392   };
2393   if (auto *SrcType = FindTruncSrcType()) {
2394     SmallVector<const SCEV *, 8> LargeOps;
2395     bool Ok = true;
2396     // Check all the operands to see if they can be represented in the
2397     // source type of the truncate.
2398     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2399       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2400         if (T->getOperand()->getType() != SrcType) {
2401           Ok = false;
2402           break;
2403         }
2404         LargeOps.push_back(T->getOperand());
2405       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2406         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2407       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2408         SmallVector<const SCEV *, 8> LargeMulOps;
2409         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2410           if (const SCEVTruncateExpr *T =
2411                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2412             if (T->getOperand()->getType() != SrcType) {
2413               Ok = false;
2414               break;
2415             }
2416             LargeMulOps.push_back(T->getOperand());
2417           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2418             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2419           } else {
2420             Ok = false;
2421             break;
2422           }
2423         }
2424         if (Ok)
2425           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2426       } else {
2427         Ok = false;
2428         break;
2429       }
2430     }
2431     if (Ok) {
2432       // Evaluate the expression in the larger type.
2433       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2434       // If it folds to something simple, use it. Otherwise, don't.
2435       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2436         return getTruncateExpr(Fold, Ty);
2437     }
2438   }
2439 
2440   // Skip past any other cast SCEVs.
2441   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2442     ++Idx;
2443 
2444   // If there are add operands they would be next.
2445   if (Idx < Ops.size()) {
2446     bool DeletedAdd = false;
2447     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2448       if (Ops.size() > AddOpsInlineThreshold ||
2449           Add->getNumOperands() > AddOpsInlineThreshold)
2450         break;
2451       // If we have an add, expand the add operands onto the end of the operands
2452       // list.
2453       Ops.erase(Ops.begin()+Idx);
2454       Ops.append(Add->op_begin(), Add->op_end());
2455       DeletedAdd = true;
2456     }
2457 
2458     // If we deleted at least one add, we added operands to the end of the list,
2459     // and they are not necessarily sorted.  Recurse to resort and resimplify
2460     // any operands we just acquired.
2461     if (DeletedAdd)
2462       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2463   }
2464 
2465   // Skip over the add expression until we get to a multiply.
2466   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2467     ++Idx;
2468 
2469   // Check to see if there are any folding opportunities present with
2470   // operands multiplied by constant values.
2471   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2472     uint64_t BitWidth = getTypeSizeInBits(Ty);
2473     DenseMap<const SCEV *, APInt> M;
2474     SmallVector<const SCEV *, 8> NewOps;
2475     APInt AccumulatedConstant(BitWidth, 0);
2476     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2477                                      Ops.data(), Ops.size(),
2478                                      APInt(BitWidth, 1), *this)) {
2479       struct APIntCompare {
2480         bool operator()(const APInt &LHS, const APInt &RHS) const {
2481           return LHS.ult(RHS);
2482         }
2483       };
2484 
2485       // Some interesting folding opportunity is present, so its worthwhile to
2486       // re-generate the operands list. Group the operands by constant scale,
2487       // to avoid multiplying by the same constant scale multiple times.
2488       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2489       for (const SCEV *NewOp : NewOps)
2490         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2491       // Re-generate the operands list.
2492       Ops.clear();
2493       if (AccumulatedConstant != 0)
2494         Ops.push_back(getConstant(AccumulatedConstant));
2495       for (auto &MulOp : MulOpLists)
2496         if (MulOp.first != 0)
2497           Ops.push_back(getMulExpr(
2498               getConstant(MulOp.first),
2499               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2500               SCEV::FlagAnyWrap, Depth + 1));
2501       if (Ops.empty())
2502         return getZero(Ty);
2503       if (Ops.size() == 1)
2504         return Ops[0];
2505       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2506     }
2507   }
2508 
2509   // If we are adding something to a multiply expression, make sure the
2510   // something is not already an operand of the multiply.  If so, merge it into
2511   // the multiply.
2512   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2513     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2514     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2515       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2516       if (isa<SCEVConstant>(MulOpSCEV))
2517         continue;
2518       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2519         if (MulOpSCEV == Ops[AddOp]) {
2520           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2521           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2522           if (Mul->getNumOperands() != 2) {
2523             // If the multiply has more than two operands, we must get the
2524             // Y*Z term.
2525             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2526                                                 Mul->op_begin()+MulOp);
2527             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2528             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2529           }
2530           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2531           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2532           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2533                                             SCEV::FlagAnyWrap, Depth + 1);
2534           if (Ops.size() == 2) return OuterMul;
2535           if (AddOp < Idx) {
2536             Ops.erase(Ops.begin()+AddOp);
2537             Ops.erase(Ops.begin()+Idx-1);
2538           } else {
2539             Ops.erase(Ops.begin()+Idx);
2540             Ops.erase(Ops.begin()+AddOp-1);
2541           }
2542           Ops.push_back(OuterMul);
2543           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2544         }
2545 
2546       // Check this multiply against other multiplies being added together.
2547       for (unsigned OtherMulIdx = Idx+1;
2548            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2549            ++OtherMulIdx) {
2550         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2551         // If MulOp occurs in OtherMul, we can fold the two multiplies
2552         // together.
2553         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2554              OMulOp != e; ++OMulOp)
2555           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2556             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2557             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2558             if (Mul->getNumOperands() != 2) {
2559               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2560                                                   Mul->op_begin()+MulOp);
2561               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2562               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2563             }
2564             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2565             if (OtherMul->getNumOperands() != 2) {
2566               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2567                                                   OtherMul->op_begin()+OMulOp);
2568               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2569               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2570             }
2571             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2572             const SCEV *InnerMulSum =
2573                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2574             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2575                                               SCEV::FlagAnyWrap, Depth + 1);
2576             if (Ops.size() == 2) return OuterMul;
2577             Ops.erase(Ops.begin()+Idx);
2578             Ops.erase(Ops.begin()+OtherMulIdx-1);
2579             Ops.push_back(OuterMul);
2580             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2581           }
2582       }
2583     }
2584   }
2585 
2586   // If there are any add recurrences in the operands list, see if any other
2587   // added values are loop invariant.  If so, we can fold them into the
2588   // recurrence.
2589   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2590     ++Idx;
2591 
2592   // Scan over all recurrences, trying to fold loop invariants into them.
2593   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2594     // Scan all of the other operands to this add and add them to the vector if
2595     // they are loop invariant w.r.t. the recurrence.
2596     SmallVector<const SCEV *, 8> LIOps;
2597     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2598     const Loop *AddRecLoop = AddRec->getLoop();
2599     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2600       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2601         LIOps.push_back(Ops[i]);
2602         Ops.erase(Ops.begin()+i);
2603         --i; --e;
2604       }
2605 
2606     // If we found some loop invariants, fold them into the recurrence.
2607     if (!LIOps.empty()) {
2608       // Compute nowrap flags for the addition of the loop-invariant ops and
2609       // the addrec. Temporarily push it as an operand for that purpose.
2610       LIOps.push_back(AddRec);
2611       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2612       LIOps.pop_back();
2613 
2614       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2615       LIOps.push_back(AddRec->getStart());
2616 
2617       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2618       // This follows from the fact that the no-wrap flags on the outer add
2619       // expression are applicable on the 0th iteration, when the add recurrence
2620       // will be equal to its start value.
2621       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2622 
2623       // Build the new addrec. Propagate the NUW and NSW flags if both the
2624       // outer add and the inner addrec are guaranteed to have no overflow.
2625       // Always propagate NW.
2626       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2627       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2628 
2629       // If all of the other operands were loop invariant, we are done.
2630       if (Ops.size() == 1) return NewRec;
2631 
2632       // Otherwise, add the folded AddRec by the non-invariant parts.
2633       for (unsigned i = 0;; ++i)
2634         if (Ops[i] == AddRec) {
2635           Ops[i] = NewRec;
2636           break;
2637         }
2638       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2639     }
2640 
2641     // Okay, if there weren't any loop invariants to be folded, check to see if
2642     // there are multiple AddRec's with the same loop induction variable being
2643     // added together.  If so, we can fold them.
2644     for (unsigned OtherIdx = Idx+1;
2645          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2646          ++OtherIdx) {
2647       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2648       // so that the 1st found AddRecExpr is dominated by all others.
2649       assert(DT.dominates(
2650            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2651            AddRec->getLoop()->getHeader()) &&
2652         "AddRecExprs are not sorted in reverse dominance order?");
2653       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2654         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2655         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2656         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2657              ++OtherIdx) {
2658           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2659           if (OtherAddRec->getLoop() == AddRecLoop) {
2660             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2661                  i != e; ++i) {
2662               if (i >= AddRecOps.size()) {
2663                 AddRecOps.append(OtherAddRec->op_begin()+i,
2664                                  OtherAddRec->op_end());
2665                 break;
2666               }
2667               SmallVector<const SCEV *, 2> TwoOps = {
2668                   AddRecOps[i], OtherAddRec->getOperand(i)};
2669               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2670             }
2671             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2672           }
2673         }
2674         // Step size has changed, so we cannot guarantee no self-wraparound.
2675         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2676         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2677       }
2678     }
2679 
2680     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2681     // next one.
2682   }
2683 
2684   // Okay, it looks like we really DO need an add expr.  Check to see if we
2685   // already have one, otherwise create a new one.
2686   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2687 }
2688 
2689 const SCEV *
2690 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2691                                     SCEV::NoWrapFlags Flags) {
2692   FoldingSetNodeID ID;
2693   ID.AddInteger(scAddExpr);
2694   for (const SCEV *Op : Ops)
2695     ID.AddPointer(Op);
2696   void *IP = nullptr;
2697   SCEVAddExpr *S =
2698       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2699   if (!S) {
2700     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2701     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2702     S = new (SCEVAllocator)
2703         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2704     UniqueSCEVs.InsertNode(S, IP);
2705     addToLoopUseLists(S);
2706   }
2707   S->setNoWrapFlags(Flags);
2708   return S;
2709 }
2710 
2711 const SCEV *
2712 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2713                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2714   FoldingSetNodeID ID;
2715   ID.AddInteger(scAddRecExpr);
2716   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2717     ID.AddPointer(Ops[i]);
2718   ID.AddPointer(L);
2719   void *IP = nullptr;
2720   SCEVAddRecExpr *S =
2721       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2722   if (!S) {
2723     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2724     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2725     S = new (SCEVAllocator)
2726         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2727     UniqueSCEVs.InsertNode(S, IP);
2728     addToLoopUseLists(S);
2729   }
2730   setNoWrapFlags(S, Flags);
2731   return S;
2732 }
2733 
2734 const SCEV *
2735 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2736                                     SCEV::NoWrapFlags Flags) {
2737   FoldingSetNodeID ID;
2738   ID.AddInteger(scMulExpr);
2739   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2740     ID.AddPointer(Ops[i]);
2741   void *IP = nullptr;
2742   SCEVMulExpr *S =
2743     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2744   if (!S) {
2745     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2746     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2747     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2748                                         O, Ops.size());
2749     UniqueSCEVs.InsertNode(S, IP);
2750     addToLoopUseLists(S);
2751   }
2752   S->setNoWrapFlags(Flags);
2753   return S;
2754 }
2755 
2756 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2757   uint64_t k = i*j;
2758   if (j > 1 && k / j != i) Overflow = true;
2759   return k;
2760 }
2761 
2762 /// Compute the result of "n choose k", the binomial coefficient.  If an
2763 /// intermediate computation overflows, Overflow will be set and the return will
2764 /// be garbage. Overflow is not cleared on absence of overflow.
2765 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2766   // We use the multiplicative formula:
2767   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2768   // At each iteration, we take the n-th term of the numeral and divide by the
2769   // (k-n)th term of the denominator.  This division will always produce an
2770   // integral result, and helps reduce the chance of overflow in the
2771   // intermediate computations. However, we can still overflow even when the
2772   // final result would fit.
2773 
2774   if (n == 0 || n == k) return 1;
2775   if (k > n) return 0;
2776 
2777   if (k > n/2)
2778     k = n-k;
2779 
2780   uint64_t r = 1;
2781   for (uint64_t i = 1; i <= k; ++i) {
2782     r = umul_ov(r, n-(i-1), Overflow);
2783     r /= i;
2784   }
2785   return r;
2786 }
2787 
2788 /// Determine if any of the operands in this SCEV are a constant or if
2789 /// any of the add or multiply expressions in this SCEV contain a constant.
2790 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2791   struct FindConstantInAddMulChain {
2792     bool FoundConstant = false;
2793 
2794     bool follow(const SCEV *S) {
2795       FoundConstant |= isa<SCEVConstant>(S);
2796       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2797     }
2798 
2799     bool isDone() const {
2800       return FoundConstant;
2801     }
2802   };
2803 
2804   FindConstantInAddMulChain F;
2805   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2806   ST.visitAll(StartExpr);
2807   return F.FoundConstant;
2808 }
2809 
2810 /// Get a canonical multiply expression, or something simpler if possible.
2811 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2812                                         SCEV::NoWrapFlags OrigFlags,
2813                                         unsigned Depth) {
2814   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2815          "only nuw or nsw allowed");
2816   assert(!Ops.empty() && "Cannot get empty mul!");
2817   if (Ops.size() == 1) return Ops[0];
2818 #ifndef NDEBUG
2819   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2820   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2821     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2822            "SCEVMulExpr operand types don't match!");
2823 #endif
2824 
2825   // Sort by complexity, this groups all similar expression types together.
2826   GroupByComplexity(Ops, &LI, DT);
2827 
2828   // If there are any constants, fold them together.
2829   unsigned Idx = 0;
2830   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2831     ++Idx;
2832     assert(Idx < Ops.size());
2833     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2834       // We found two constants, fold them together!
2835       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2836       if (Ops.size() == 2) return Ops[0];
2837       Ops.erase(Ops.begin()+1);  // Erase the folded element
2838       LHSC = cast<SCEVConstant>(Ops[0]);
2839     }
2840 
2841     // If we have a multiply of zero, it will always be zero.
2842     if (LHSC->getValue()->isZero())
2843       return LHSC;
2844 
2845     // If we are left with a constant one being multiplied, strip it off.
2846     if (LHSC->getValue()->isOne()) {
2847       Ops.erase(Ops.begin());
2848       --Idx;
2849     }
2850 
2851     if (Ops.size() == 1)
2852       return Ops[0];
2853   }
2854 
2855   // Delay expensive flag strengthening until necessary.
2856   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2857     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2858   };
2859 
2860   // Limit recursion calls depth.
2861   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2862     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2863 
2864   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2865     // Don't strengthen flags if we have no new information.
2866     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2867     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2868       Mul->setNoWrapFlags(ComputeFlags(Ops));
2869     return S;
2870   }
2871 
2872   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2873     if (Ops.size() == 2) {
2874       // C1*(C2+V) -> C1*C2 + C1*V
2875       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2876         // If any of Add's ops are Adds or Muls with a constant, apply this
2877         // transformation as well.
2878         //
2879         // TODO: There are some cases where this transformation is not
2880         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2881         // this transformation should be narrowed down.
2882         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2883           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2884                                        SCEV::FlagAnyWrap, Depth + 1),
2885                             getMulExpr(LHSC, Add->getOperand(1),
2886                                        SCEV::FlagAnyWrap, Depth + 1),
2887                             SCEV::FlagAnyWrap, Depth + 1);
2888 
2889       if (Ops[0]->isAllOnesValue()) {
2890         // If we have a mul by -1 of an add, try distributing the -1 among the
2891         // add operands.
2892         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2893           SmallVector<const SCEV *, 4> NewOps;
2894           bool AnyFolded = false;
2895           for (const SCEV *AddOp : Add->operands()) {
2896             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2897                                          Depth + 1);
2898             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2899             NewOps.push_back(Mul);
2900           }
2901           if (AnyFolded)
2902             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2903         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2904           // Negation preserves a recurrence's no self-wrap property.
2905           SmallVector<const SCEV *, 4> Operands;
2906           for (const SCEV *AddRecOp : AddRec->operands())
2907             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2908                                           Depth + 1));
2909 
2910           return getAddRecExpr(Operands, AddRec->getLoop(),
2911                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2912         }
2913       }
2914     }
2915   }
2916 
2917   // Skip over the add expression until we get to a multiply.
2918   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2919     ++Idx;
2920 
2921   // If there are mul operands inline them all into this expression.
2922   if (Idx < Ops.size()) {
2923     bool DeletedMul = false;
2924     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2925       if (Ops.size() > MulOpsInlineThreshold)
2926         break;
2927       // If we have an mul, expand the mul operands onto the end of the
2928       // operands list.
2929       Ops.erase(Ops.begin()+Idx);
2930       Ops.append(Mul->op_begin(), Mul->op_end());
2931       DeletedMul = true;
2932     }
2933 
2934     // If we deleted at least one mul, we added operands to the end of the
2935     // list, and they are not necessarily sorted.  Recurse to resort and
2936     // resimplify any operands we just acquired.
2937     if (DeletedMul)
2938       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2939   }
2940 
2941   // If there are any add recurrences in the operands list, see if any other
2942   // added values are loop invariant.  If so, we can fold them into the
2943   // recurrence.
2944   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2945     ++Idx;
2946 
2947   // Scan over all recurrences, trying to fold loop invariants into them.
2948   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2949     // Scan all of the other operands to this mul and add them to the vector
2950     // if they are loop invariant w.r.t. the recurrence.
2951     SmallVector<const SCEV *, 8> LIOps;
2952     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2953     const Loop *AddRecLoop = AddRec->getLoop();
2954     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2955       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2956         LIOps.push_back(Ops[i]);
2957         Ops.erase(Ops.begin()+i);
2958         --i; --e;
2959       }
2960 
2961     // If we found some loop invariants, fold them into the recurrence.
2962     if (!LIOps.empty()) {
2963       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2964       SmallVector<const SCEV *, 4> NewOps;
2965       NewOps.reserve(AddRec->getNumOperands());
2966       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2967       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2968         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2969                                     SCEV::FlagAnyWrap, Depth + 1));
2970 
2971       // Build the new addrec. Propagate the NUW and NSW flags if both the
2972       // outer mul and the inner addrec are guaranteed to have no overflow.
2973       //
2974       // No self-wrap cannot be guaranteed after changing the step size, but
2975       // will be inferred if either NUW or NSW is true.
2976       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2977       const SCEV *NewRec = getAddRecExpr(
2978           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2979 
2980       // If all of the other operands were loop invariant, we are done.
2981       if (Ops.size() == 1) return NewRec;
2982 
2983       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2984       for (unsigned i = 0;; ++i)
2985         if (Ops[i] == AddRec) {
2986           Ops[i] = NewRec;
2987           break;
2988         }
2989       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2990     }
2991 
2992     // Okay, if there weren't any loop invariants to be folded, check to see
2993     // if there are multiple AddRec's with the same loop induction variable
2994     // being multiplied together.  If so, we can fold them.
2995 
2996     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2997     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2998     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2999     //   ]]],+,...up to x=2n}.
3000     // Note that the arguments to choose() are always integers with values
3001     // known at compile time, never SCEV objects.
3002     //
3003     // The implementation avoids pointless extra computations when the two
3004     // addrec's are of different length (mathematically, it's equivalent to
3005     // an infinite stream of zeros on the right).
3006     bool OpsModified = false;
3007     for (unsigned OtherIdx = Idx+1;
3008          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3009          ++OtherIdx) {
3010       const SCEVAddRecExpr *OtherAddRec =
3011         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3012       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3013         continue;
3014 
3015       // Limit max number of arguments to avoid creation of unreasonably big
3016       // SCEVAddRecs with very complex operands.
3017       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3018           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3019         continue;
3020 
3021       bool Overflow = false;
3022       Type *Ty = AddRec->getType();
3023       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3024       SmallVector<const SCEV*, 7> AddRecOps;
3025       for (int x = 0, xe = AddRec->getNumOperands() +
3026              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3027         SmallVector <const SCEV *, 7> SumOps;
3028         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3029           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3030           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3031                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3032                z < ze && !Overflow; ++z) {
3033             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3034             uint64_t Coeff;
3035             if (LargerThan64Bits)
3036               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3037             else
3038               Coeff = Coeff1*Coeff2;
3039             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3040             const SCEV *Term1 = AddRec->getOperand(y-z);
3041             const SCEV *Term2 = OtherAddRec->getOperand(z);
3042             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3043                                         SCEV::FlagAnyWrap, Depth + 1));
3044           }
3045         }
3046         if (SumOps.empty())
3047           SumOps.push_back(getZero(Ty));
3048         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3049       }
3050       if (!Overflow) {
3051         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3052                                               SCEV::FlagAnyWrap);
3053         if (Ops.size() == 2) return NewAddRec;
3054         Ops[Idx] = NewAddRec;
3055         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3056         OpsModified = true;
3057         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3058         if (!AddRec)
3059           break;
3060       }
3061     }
3062     if (OpsModified)
3063       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3064 
3065     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3066     // next one.
3067   }
3068 
3069   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3070   // already have one, otherwise create a new one.
3071   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3072 }
3073 
3074 /// Represents an unsigned remainder expression based on unsigned division.
3075 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3076                                          const SCEV *RHS) {
3077   assert(getEffectiveSCEVType(LHS->getType()) ==
3078          getEffectiveSCEVType(RHS->getType()) &&
3079          "SCEVURemExpr operand types don't match!");
3080 
3081   // Short-circuit easy cases
3082   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3083     // If constant is one, the result is trivial
3084     if (RHSC->getValue()->isOne())
3085       return getZero(LHS->getType()); // X urem 1 --> 0
3086 
3087     // If constant is a power of two, fold into a zext(trunc(LHS)).
3088     if (RHSC->getAPInt().isPowerOf2()) {
3089       Type *FullTy = LHS->getType();
3090       Type *TruncTy =
3091           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3092       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3093     }
3094   }
3095 
3096   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3097   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3098   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3099   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3100 }
3101 
3102 /// Get a canonical unsigned division expression, or something simpler if
3103 /// possible.
3104 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3105                                          const SCEV *RHS) {
3106   assert(getEffectiveSCEVType(LHS->getType()) ==
3107          getEffectiveSCEVType(RHS->getType()) &&
3108          "SCEVUDivExpr operand types don't match!");
3109 
3110   FoldingSetNodeID ID;
3111   ID.AddInteger(scUDivExpr);
3112   ID.AddPointer(LHS);
3113   ID.AddPointer(RHS);
3114   void *IP = nullptr;
3115   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3116     return S;
3117 
3118   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3119     if (RHSC->getValue()->isOne())
3120       return LHS;                               // X udiv 1 --> x
3121     // If the denominator is zero, the result of the udiv is undefined. Don't
3122     // try to analyze it, because the resolution chosen here may differ from
3123     // the resolution chosen in other parts of the compiler.
3124     if (!RHSC->getValue()->isZero()) {
3125       // Determine if the division can be folded into the operands of
3126       // its operands.
3127       // TODO: Generalize this to non-constants by using known-bits information.
3128       Type *Ty = LHS->getType();
3129       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3130       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3131       // For non-power-of-two values, effectively round the value up to the
3132       // nearest power of two.
3133       if (!RHSC->getAPInt().isPowerOf2())
3134         ++MaxShiftAmt;
3135       IntegerType *ExtTy =
3136         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3137       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3138         if (const SCEVConstant *Step =
3139             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3140           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3141           const APInt &StepInt = Step->getAPInt();
3142           const APInt &DivInt = RHSC->getAPInt();
3143           if (!StepInt.urem(DivInt) &&
3144               getZeroExtendExpr(AR, ExtTy) ==
3145               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3146                             getZeroExtendExpr(Step, ExtTy),
3147                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3148             SmallVector<const SCEV *, 4> Operands;
3149             for (const SCEV *Op : AR->operands())
3150               Operands.push_back(getUDivExpr(Op, RHS));
3151             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3152           }
3153           /// Get a canonical UDivExpr for a recurrence.
3154           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3155           // We can currently only fold X%N if X is constant.
3156           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3157           if (StartC && !DivInt.urem(StepInt) &&
3158               getZeroExtendExpr(AR, ExtTy) ==
3159               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3160                             getZeroExtendExpr(Step, ExtTy),
3161                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3162             const APInt &StartInt = StartC->getAPInt();
3163             const APInt &StartRem = StartInt.urem(StepInt);
3164             if (StartRem != 0) {
3165               const SCEV *NewLHS =
3166                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3167                                 AR->getLoop(), SCEV::FlagNW);
3168               if (LHS != NewLHS) {
3169                 LHS = NewLHS;
3170 
3171                 // Reset the ID to include the new LHS, and check if it is
3172                 // already cached.
3173                 ID.clear();
3174                 ID.AddInteger(scUDivExpr);
3175                 ID.AddPointer(LHS);
3176                 ID.AddPointer(RHS);
3177                 IP = nullptr;
3178                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3179                   return S;
3180               }
3181             }
3182           }
3183         }
3184       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3185       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3186         SmallVector<const SCEV *, 4> Operands;
3187         for (const SCEV *Op : M->operands())
3188           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3189         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3190           // Find an operand that's safely divisible.
3191           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3192             const SCEV *Op = M->getOperand(i);
3193             const SCEV *Div = getUDivExpr(Op, RHSC);
3194             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3195               Operands = SmallVector<const SCEV *, 4>(M->operands());
3196               Operands[i] = Div;
3197               return getMulExpr(Operands);
3198             }
3199           }
3200       }
3201 
3202       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3203       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3204         if (auto *DivisorConstant =
3205                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3206           bool Overflow = false;
3207           APInt NewRHS =
3208               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3209           if (Overflow) {
3210             return getConstant(RHSC->getType(), 0, false);
3211           }
3212           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3213         }
3214       }
3215 
3216       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3217       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3218         SmallVector<const SCEV *, 4> Operands;
3219         for (const SCEV *Op : A->operands())
3220           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3221         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3222           Operands.clear();
3223           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3224             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3225             if (isa<SCEVUDivExpr>(Op) ||
3226                 getMulExpr(Op, RHS) != A->getOperand(i))
3227               break;
3228             Operands.push_back(Op);
3229           }
3230           if (Operands.size() == A->getNumOperands())
3231             return getAddExpr(Operands);
3232         }
3233       }
3234 
3235       // Fold if both operands are constant.
3236       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3237         Constant *LHSCV = LHSC->getValue();
3238         Constant *RHSCV = RHSC->getValue();
3239         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3240                                                                    RHSCV)));
3241       }
3242     }
3243   }
3244 
3245   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3246   // changes). Make sure we get a new one.
3247   IP = nullptr;
3248   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3249   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3250                                              LHS, RHS);
3251   UniqueSCEVs.InsertNode(S, IP);
3252   addToLoopUseLists(S);
3253   return S;
3254 }
3255 
3256 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3257   APInt A = C1->getAPInt().abs();
3258   APInt B = C2->getAPInt().abs();
3259   uint32_t ABW = A.getBitWidth();
3260   uint32_t BBW = B.getBitWidth();
3261 
3262   if (ABW > BBW)
3263     B = B.zext(ABW);
3264   else if (ABW < BBW)
3265     A = A.zext(BBW);
3266 
3267   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3268 }
3269 
3270 /// Get a canonical unsigned division expression, or something simpler if
3271 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3272 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3273 /// it's not exact because the udiv may be clearing bits.
3274 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3275                                               const SCEV *RHS) {
3276   // TODO: we could try to find factors in all sorts of things, but for now we
3277   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3278   // end of this file for inspiration.
3279 
3280   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3281   if (!Mul || !Mul->hasNoUnsignedWrap())
3282     return getUDivExpr(LHS, RHS);
3283 
3284   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3285     // If the mulexpr multiplies by a constant, then that constant must be the
3286     // first element of the mulexpr.
3287     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3288       if (LHSCst == RHSCst) {
3289         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3290         return getMulExpr(Operands);
3291       }
3292 
3293       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3294       // that there's a factor provided by one of the other terms. We need to
3295       // check.
3296       APInt Factor = gcd(LHSCst, RHSCst);
3297       if (!Factor.isIntN(1)) {
3298         LHSCst =
3299             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3300         RHSCst =
3301             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3302         SmallVector<const SCEV *, 2> Operands;
3303         Operands.push_back(LHSCst);
3304         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3305         LHS = getMulExpr(Operands);
3306         RHS = RHSCst;
3307         Mul = dyn_cast<SCEVMulExpr>(LHS);
3308         if (!Mul)
3309           return getUDivExactExpr(LHS, RHS);
3310       }
3311     }
3312   }
3313 
3314   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3315     if (Mul->getOperand(i) == RHS) {
3316       SmallVector<const SCEV *, 2> Operands;
3317       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3318       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3319       return getMulExpr(Operands);
3320     }
3321   }
3322 
3323   return getUDivExpr(LHS, RHS);
3324 }
3325 
3326 /// Get an add recurrence expression for the specified loop.  Simplify the
3327 /// expression as much as possible.
3328 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3329                                            const Loop *L,
3330                                            SCEV::NoWrapFlags Flags) {
3331   SmallVector<const SCEV *, 4> Operands;
3332   Operands.push_back(Start);
3333   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3334     if (StepChrec->getLoop() == L) {
3335       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3336       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3337     }
3338 
3339   Operands.push_back(Step);
3340   return getAddRecExpr(Operands, L, Flags);
3341 }
3342 
3343 /// Get an add recurrence expression for the specified loop.  Simplify the
3344 /// expression as much as possible.
3345 const SCEV *
3346 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3347                                const Loop *L, SCEV::NoWrapFlags Flags) {
3348   if (Operands.size() == 1) return Operands[0];
3349 #ifndef NDEBUG
3350   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3351   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3352     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3353            "SCEVAddRecExpr operand types don't match!");
3354   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3355     assert(isLoopInvariant(Operands[i], L) &&
3356            "SCEVAddRecExpr operand is not loop-invariant!");
3357 #endif
3358 
3359   if (Operands.back()->isZero()) {
3360     Operands.pop_back();
3361     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3362   }
3363 
3364   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3365   // use that information to infer NUW and NSW flags. However, computing a
3366   // BE count requires calling getAddRecExpr, so we may not yet have a
3367   // meaningful BE count at this point (and if we don't, we'd be stuck
3368   // with a SCEVCouldNotCompute as the cached BE count).
3369 
3370   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3371 
3372   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3373   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3374     const Loop *NestedLoop = NestedAR->getLoop();
3375     if (L->contains(NestedLoop)
3376             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3377             : (!NestedLoop->contains(L) &&
3378                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3379       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3380       Operands[0] = NestedAR->getStart();
3381       // AddRecs require their operands be loop-invariant with respect to their
3382       // loops. Don't perform this transformation if it would break this
3383       // requirement.
3384       bool AllInvariant = all_of(
3385           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3386 
3387       if (AllInvariant) {
3388         // Create a recurrence for the outer loop with the same step size.
3389         //
3390         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3391         // inner recurrence has the same property.
3392         SCEV::NoWrapFlags OuterFlags =
3393           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3394 
3395         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3396         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3397           return isLoopInvariant(Op, NestedLoop);
3398         });
3399 
3400         if (AllInvariant) {
3401           // Ok, both add recurrences are valid after the transformation.
3402           //
3403           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3404           // the outer recurrence has the same property.
3405           SCEV::NoWrapFlags InnerFlags =
3406             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3407           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3408         }
3409       }
3410       // Reset Operands to its original state.
3411       Operands[0] = NestedAR;
3412     }
3413   }
3414 
3415   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3416   // already have one, otherwise create a new one.
3417   return getOrCreateAddRecExpr(Operands, L, Flags);
3418 }
3419 
3420 const SCEV *
3421 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3422                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3423   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3424   // getSCEV(Base)->getType() has the same address space as Base->getType()
3425   // because SCEV::getType() preserves the address space.
3426   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3427   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3428   // instruction to its SCEV, because the Instruction may be guarded by control
3429   // flow and the no-overflow bits may not be valid for the expression in any
3430   // context. This can be fixed similarly to how these flags are handled for
3431   // adds.
3432   SCEV::NoWrapFlags OffsetWrap =
3433       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3434 
3435   Type *CurTy = GEP->getType();
3436   bool FirstIter = true;
3437   SmallVector<const SCEV *, 4> Offsets;
3438   for (const SCEV *IndexExpr : IndexExprs) {
3439     // Compute the (potentially symbolic) offset in bytes for this index.
3440     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3441       // For a struct, add the member offset.
3442       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3443       unsigned FieldNo = Index->getZExtValue();
3444       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3445       Offsets.push_back(FieldOffset);
3446 
3447       // Update CurTy to the type of the field at Index.
3448       CurTy = STy->getTypeAtIndex(Index);
3449     } else {
3450       // Update CurTy to its element type.
3451       if (FirstIter) {
3452         assert(isa<PointerType>(CurTy) &&
3453                "The first index of a GEP indexes a pointer");
3454         CurTy = GEP->getSourceElementType();
3455         FirstIter = false;
3456       } else {
3457         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3458       }
3459       // For an array, add the element offset, explicitly scaled.
3460       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3461       // Getelementptr indices are signed.
3462       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3463 
3464       // Multiply the index by the element size to compute the element offset.
3465       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3466       Offsets.push_back(LocalOffset);
3467     }
3468   }
3469 
3470   // Handle degenerate case of GEP without offsets.
3471   if (Offsets.empty())
3472     return BaseExpr;
3473 
3474   // Add the offsets together, assuming nsw if inbounds.
3475   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3476   // Add the base address and the offset. We cannot use the nsw flag, as the
3477   // base address is unsigned. However, if we know that the offset is
3478   // non-negative, we can use nuw.
3479   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3480                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3481   return getAddExpr(BaseExpr, Offset, BaseWrap);
3482 }
3483 
3484 std::tuple<SCEV *, FoldingSetNodeID, void *>
3485 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3486                                          ArrayRef<const SCEV *> Ops) {
3487   FoldingSetNodeID ID;
3488   void *IP = nullptr;
3489   ID.AddInteger(SCEVType);
3490   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3491     ID.AddPointer(Ops[i]);
3492   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3493       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3494 }
3495 
3496 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3497   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3498   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3499 }
3500 
3501 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) {
3502   Type *Ty = Op->getType();
3503   return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty));
3504 }
3505 
3506 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3507                                            SmallVectorImpl<const SCEV *> &Ops) {
3508   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3509   if (Ops.size() == 1) return Ops[0];
3510 #ifndef NDEBUG
3511   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3512   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3513     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3514            "Operand types don't match!");
3515 #endif
3516 
3517   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3518   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3519 
3520   // Sort by complexity, this groups all similar expression types together.
3521   GroupByComplexity(Ops, &LI, DT);
3522 
3523   // Check if we have created the same expression before.
3524   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3525     return S;
3526   }
3527 
3528   // If there are any constants, fold them together.
3529   unsigned Idx = 0;
3530   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3531     ++Idx;
3532     assert(Idx < Ops.size());
3533     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3534       if (Kind == scSMaxExpr)
3535         return APIntOps::smax(LHS, RHS);
3536       else if (Kind == scSMinExpr)
3537         return APIntOps::smin(LHS, RHS);
3538       else if (Kind == scUMaxExpr)
3539         return APIntOps::umax(LHS, RHS);
3540       else if (Kind == scUMinExpr)
3541         return APIntOps::umin(LHS, RHS);
3542       llvm_unreachable("Unknown SCEV min/max opcode");
3543     };
3544 
3545     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3546       // We found two constants, fold them together!
3547       ConstantInt *Fold = ConstantInt::get(
3548           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3549       Ops[0] = getConstant(Fold);
3550       Ops.erase(Ops.begin()+1);  // Erase the folded element
3551       if (Ops.size() == 1) return Ops[0];
3552       LHSC = cast<SCEVConstant>(Ops[0]);
3553     }
3554 
3555     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3556     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3557 
3558     if (IsMax ? IsMinV : IsMaxV) {
3559       // If we are left with a constant minimum(/maximum)-int, strip it off.
3560       Ops.erase(Ops.begin());
3561       --Idx;
3562     } else if (IsMax ? IsMaxV : IsMinV) {
3563       // If we have a max(/min) with a constant maximum(/minimum)-int,
3564       // it will always be the extremum.
3565       return LHSC;
3566     }
3567 
3568     if (Ops.size() == 1) return Ops[0];
3569   }
3570 
3571   // Find the first operation of the same kind
3572   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3573     ++Idx;
3574 
3575   // Check to see if one of the operands is of the same kind. If so, expand its
3576   // operands onto our operand list, and recurse to simplify.
3577   if (Idx < Ops.size()) {
3578     bool DeletedAny = false;
3579     while (Ops[Idx]->getSCEVType() == Kind) {
3580       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3581       Ops.erase(Ops.begin()+Idx);
3582       Ops.append(SMME->op_begin(), SMME->op_end());
3583       DeletedAny = true;
3584     }
3585 
3586     if (DeletedAny)
3587       return getMinMaxExpr(Kind, Ops);
3588   }
3589 
3590   // Okay, check to see if the same value occurs in the operand list twice.  If
3591   // so, delete one.  Since we sorted the list, these values are required to
3592   // be adjacent.
3593   llvm::CmpInst::Predicate GEPred =
3594       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3595   llvm::CmpInst::Predicate LEPred =
3596       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3597   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3598   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3599   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3600     if (Ops[i] == Ops[i + 1] ||
3601         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3602       //  X op Y op Y  -->  X op Y
3603       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3604       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3605       --i;
3606       --e;
3607     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3608                                                Ops[i + 1])) {
3609       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3610       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3611       --i;
3612       --e;
3613     }
3614   }
3615 
3616   if (Ops.size() == 1) return Ops[0];
3617 
3618   assert(!Ops.empty() && "Reduced smax down to nothing!");
3619 
3620   // Okay, it looks like we really DO need an expr.  Check to see if we
3621   // already have one, otherwise create a new one.
3622   const SCEV *ExistingSCEV;
3623   FoldingSetNodeID ID;
3624   void *IP;
3625   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3626   if (ExistingSCEV)
3627     return ExistingSCEV;
3628   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3629   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3630   SCEV *S = new (SCEVAllocator)
3631       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3632 
3633   UniqueSCEVs.InsertNode(S, IP);
3634   addToLoopUseLists(S);
3635   return S;
3636 }
3637 
3638 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3639   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3640   return getSMaxExpr(Ops);
3641 }
3642 
3643 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3644   return getMinMaxExpr(scSMaxExpr, Ops);
3645 }
3646 
3647 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3648   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3649   return getUMaxExpr(Ops);
3650 }
3651 
3652 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3653   return getMinMaxExpr(scUMaxExpr, Ops);
3654 }
3655 
3656 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3657                                          const SCEV *RHS) {
3658   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3659   return getSMinExpr(Ops);
3660 }
3661 
3662 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3663   return getMinMaxExpr(scSMinExpr, Ops);
3664 }
3665 
3666 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3667                                          const SCEV *RHS) {
3668   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3669   return getUMinExpr(Ops);
3670 }
3671 
3672 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3673   return getMinMaxExpr(scUMinExpr, Ops);
3674 }
3675 
3676 const SCEV *
3677 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3678                                              ScalableVectorType *ScalableTy) {
3679   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3680   Constant *One = ConstantInt::get(IntTy, 1);
3681   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3682   // Note that the expression we created is the final expression, we don't
3683   // want to simplify it any further Also, if we call a normal getSCEV(),
3684   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3685   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3686 }
3687 
3688 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3689   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3690     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3691   // We can bypass creating a target-independent constant expression and then
3692   // folding it back into a ConstantInt. This is just a compile-time
3693   // optimization.
3694   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3695 }
3696 
3697 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3698   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3699     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3700   // We can bypass creating a target-independent constant expression and then
3701   // folding it back into a ConstantInt. This is just a compile-time
3702   // optimization.
3703   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3704 }
3705 
3706 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3707                                              StructType *STy,
3708                                              unsigned FieldNo) {
3709   // We can bypass creating a target-independent constant expression and then
3710   // folding it back into a ConstantInt. This is just a compile-time
3711   // optimization.
3712   return getConstant(
3713       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3714 }
3715 
3716 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3717   // Don't attempt to do anything other than create a SCEVUnknown object
3718   // here.  createSCEV only calls getUnknown after checking for all other
3719   // interesting possibilities, and any other code that calls getUnknown
3720   // is doing so in order to hide a value from SCEV canonicalization.
3721 
3722   FoldingSetNodeID ID;
3723   ID.AddInteger(scUnknown);
3724   ID.AddPointer(V);
3725   void *IP = nullptr;
3726   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3727     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3728            "Stale SCEVUnknown in uniquing map!");
3729     return S;
3730   }
3731   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3732                                             FirstUnknown);
3733   FirstUnknown = cast<SCEVUnknown>(S);
3734   UniqueSCEVs.InsertNode(S, IP);
3735   return S;
3736 }
3737 
3738 //===----------------------------------------------------------------------===//
3739 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3740 //
3741 
3742 /// Test if values of the given type are analyzable within the SCEV
3743 /// framework. This primarily includes integer types, and it can optionally
3744 /// include pointer types if the ScalarEvolution class has access to
3745 /// target-specific information.
3746 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3747   // Integers and pointers are always SCEVable.
3748   return Ty->isIntOrPtrTy();
3749 }
3750 
3751 /// Return the size in bits of the specified type, for which isSCEVable must
3752 /// return true.
3753 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3754   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3755   if (Ty->isPointerTy())
3756     return getDataLayout().getIndexTypeSizeInBits(Ty);
3757   return getDataLayout().getTypeSizeInBits(Ty);
3758 }
3759 
3760 /// Return a type with the same bitwidth as the given type and which represents
3761 /// how SCEV will treat the given type, for which isSCEVable must return
3762 /// true. For pointer types, this is the pointer index sized integer type.
3763 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3764   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3765 
3766   if (Ty->isIntegerTy())
3767     return Ty;
3768 
3769   // The only other support type is pointer.
3770   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3771   return getDataLayout().getIndexType(Ty);
3772 }
3773 
3774 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3775   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3776 }
3777 
3778 const SCEV *ScalarEvolution::getCouldNotCompute() {
3779   return CouldNotCompute.get();
3780 }
3781 
3782 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3783   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3784     auto *SU = dyn_cast<SCEVUnknown>(S);
3785     return SU && SU->getValue() == nullptr;
3786   });
3787 
3788   return !ContainsNulls;
3789 }
3790 
3791 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3792   HasRecMapType::iterator I = HasRecMap.find(S);
3793   if (I != HasRecMap.end())
3794     return I->second;
3795 
3796   bool FoundAddRec =
3797       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3798   HasRecMap.insert({S, FoundAddRec});
3799   return FoundAddRec;
3800 }
3801 
3802 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3803 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3804 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3805 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3806   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3807   if (!Add)
3808     return {S, nullptr};
3809 
3810   if (Add->getNumOperands() != 2)
3811     return {S, nullptr};
3812 
3813   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3814   if (!ConstOp)
3815     return {S, nullptr};
3816 
3817   return {Add->getOperand(1), ConstOp->getValue()};
3818 }
3819 
3820 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3821 /// by the value and offset from any ValueOffsetPair in the set.
3822 SetVector<ScalarEvolution::ValueOffsetPair> *
3823 ScalarEvolution::getSCEVValues(const SCEV *S) {
3824   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3825   if (SI == ExprValueMap.end())
3826     return nullptr;
3827 #ifndef NDEBUG
3828   if (VerifySCEVMap) {
3829     // Check there is no dangling Value in the set returned.
3830     for (const auto &VE : SI->second)
3831       assert(ValueExprMap.count(VE.first));
3832   }
3833 #endif
3834   return &SI->second;
3835 }
3836 
3837 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3838 /// cannot be used separately. eraseValueFromMap should be used to remove
3839 /// V from ValueExprMap and ExprValueMap at the same time.
3840 void ScalarEvolution::eraseValueFromMap(Value *V) {
3841   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3842   if (I != ValueExprMap.end()) {
3843     const SCEV *S = I->second;
3844     // Remove {V, 0} from the set of ExprValueMap[S]
3845     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3846       SV->remove({V, nullptr});
3847 
3848     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3849     const SCEV *Stripped;
3850     ConstantInt *Offset;
3851     std::tie(Stripped, Offset) = splitAddExpr(S);
3852     if (Offset != nullptr) {
3853       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3854         SV->remove({V, Offset});
3855     }
3856     ValueExprMap.erase(V);
3857   }
3858 }
3859 
3860 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3861 /// TODO: In reality it is better to check the poison recursively
3862 /// but this is better than nothing.
3863 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3864   if (auto *I = dyn_cast<Instruction>(V)) {
3865     if (isa<OverflowingBinaryOperator>(I)) {
3866       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3867         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3868           return true;
3869         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3870           return true;
3871       }
3872     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3873       return true;
3874   }
3875   return false;
3876 }
3877 
3878 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3879 /// create a new one.
3880 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3881   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3882 
3883   const SCEV *S = getExistingSCEV(V);
3884   if (S == nullptr) {
3885     S = createSCEV(V);
3886     // During PHI resolution, it is possible to create two SCEVs for the same
3887     // V, so it is needed to double check whether V->S is inserted into
3888     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3889     std::pair<ValueExprMapType::iterator, bool> Pair =
3890         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3891     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3892       ExprValueMap[S].insert({V, nullptr});
3893 
3894       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3895       // ExprValueMap.
3896       const SCEV *Stripped = S;
3897       ConstantInt *Offset = nullptr;
3898       std::tie(Stripped, Offset) = splitAddExpr(S);
3899       // If stripped is SCEVUnknown, don't bother to save
3900       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3901       // increase the complexity of the expansion code.
3902       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3903       // because it may generate add/sub instead of GEP in SCEV expansion.
3904       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3905           !isa<GetElementPtrInst>(V))
3906         ExprValueMap[Stripped].insert({V, Offset});
3907     }
3908   }
3909   return S;
3910 }
3911 
3912 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3913   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3914 
3915   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3916   if (I != ValueExprMap.end()) {
3917     const SCEV *S = I->second;
3918     if (checkValidity(S))
3919       return S;
3920     eraseValueFromMap(V);
3921     forgetMemoizedResults(S);
3922   }
3923   return nullptr;
3924 }
3925 
3926 /// Return a SCEV corresponding to -V = -1*V
3927 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3928                                              SCEV::NoWrapFlags Flags) {
3929   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3930     return getConstant(
3931                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3932 
3933   Type *Ty = V->getType();
3934   Ty = getEffectiveSCEVType(Ty);
3935   return getMulExpr(V, getMinusOne(Ty), Flags);
3936 }
3937 
3938 /// If Expr computes ~A, return A else return nullptr
3939 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3940   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3941   if (!Add || Add->getNumOperands() != 2 ||
3942       !Add->getOperand(0)->isAllOnesValue())
3943     return nullptr;
3944 
3945   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3946   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3947       !AddRHS->getOperand(0)->isAllOnesValue())
3948     return nullptr;
3949 
3950   return AddRHS->getOperand(1);
3951 }
3952 
3953 /// Return a SCEV corresponding to ~V = -1-V
3954 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3955   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3956     return getConstant(
3957                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3958 
3959   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3960   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3961     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3962       SmallVector<const SCEV *, 2> MatchedOperands;
3963       for (const SCEV *Operand : MME->operands()) {
3964         const SCEV *Matched = MatchNotExpr(Operand);
3965         if (!Matched)
3966           return (const SCEV *)nullptr;
3967         MatchedOperands.push_back(Matched);
3968       }
3969       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3970                            MatchedOperands);
3971     };
3972     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3973       return Replaced;
3974   }
3975 
3976   Type *Ty = V->getType();
3977   Ty = getEffectiveSCEVType(Ty);
3978   return getMinusSCEV(getMinusOne(Ty), V);
3979 }
3980 
3981 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3982                                           SCEV::NoWrapFlags Flags,
3983                                           unsigned Depth) {
3984   // Fast path: X - X --> 0.
3985   if (LHS == RHS)
3986     return getZero(LHS->getType());
3987 
3988   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3989   // makes it so that we cannot make much use of NUW.
3990   auto AddFlags = SCEV::FlagAnyWrap;
3991   const bool RHSIsNotMinSigned =
3992       !getSignedRangeMin(RHS).isMinSignedValue();
3993   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3994     // Let M be the minimum representable signed value. Then (-1)*RHS
3995     // signed-wraps if and only if RHS is M. That can happen even for
3996     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3997     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3998     // (-1)*RHS, we need to prove that RHS != M.
3999     //
4000     // If LHS is non-negative and we know that LHS - RHS does not
4001     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4002     // either by proving that RHS > M or that LHS >= 0.
4003     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4004       AddFlags = SCEV::FlagNSW;
4005     }
4006   }
4007 
4008   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4009   // RHS is NSW and LHS >= 0.
4010   //
4011   // The difficulty here is that the NSW flag may have been proven
4012   // relative to a loop that is to be found in a recurrence in LHS and
4013   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4014   // larger scope than intended.
4015   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4016 
4017   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4018 }
4019 
4020 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4021                                                      unsigned Depth) {
4022   Type *SrcTy = V->getType();
4023   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4024          "Cannot truncate or zero extend with non-integer arguments!");
4025   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4026     return V;  // No conversion
4027   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4028     return getTruncateExpr(V, Ty, Depth);
4029   return getZeroExtendExpr(V, Ty, Depth);
4030 }
4031 
4032 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4033                                                      unsigned Depth) {
4034   Type *SrcTy = V->getType();
4035   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4036          "Cannot truncate or zero extend with non-integer arguments!");
4037   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4038     return V;  // No conversion
4039   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4040     return getTruncateExpr(V, Ty, Depth);
4041   return getSignExtendExpr(V, Ty, Depth);
4042 }
4043 
4044 const SCEV *
4045 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4046   Type *SrcTy = V->getType();
4047   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4048          "Cannot noop or zero extend with non-integer arguments!");
4049   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4050          "getNoopOrZeroExtend cannot truncate!");
4051   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4052     return V;  // No conversion
4053   return getZeroExtendExpr(V, Ty);
4054 }
4055 
4056 const SCEV *
4057 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4058   Type *SrcTy = V->getType();
4059   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4060          "Cannot noop or sign extend with non-integer arguments!");
4061   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4062          "getNoopOrSignExtend cannot truncate!");
4063   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4064     return V;  // No conversion
4065   return getSignExtendExpr(V, Ty);
4066 }
4067 
4068 const SCEV *
4069 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4070   Type *SrcTy = V->getType();
4071   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4072          "Cannot noop or any extend with non-integer arguments!");
4073   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4074          "getNoopOrAnyExtend cannot truncate!");
4075   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4076     return V;  // No conversion
4077   return getAnyExtendExpr(V, Ty);
4078 }
4079 
4080 const SCEV *
4081 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4082   Type *SrcTy = V->getType();
4083   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4084          "Cannot truncate or noop with non-integer arguments!");
4085   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4086          "getTruncateOrNoop cannot extend!");
4087   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4088     return V;  // No conversion
4089   return getTruncateExpr(V, Ty);
4090 }
4091 
4092 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4093                                                         const SCEV *RHS) {
4094   const SCEV *PromotedLHS = LHS;
4095   const SCEV *PromotedRHS = RHS;
4096 
4097   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4098     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4099   else
4100     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4101 
4102   return getUMaxExpr(PromotedLHS, PromotedRHS);
4103 }
4104 
4105 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4106                                                         const SCEV *RHS) {
4107   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4108   return getUMinFromMismatchedTypes(Ops);
4109 }
4110 
4111 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4112     SmallVectorImpl<const SCEV *> &Ops) {
4113   assert(!Ops.empty() && "At least one operand must be!");
4114   // Trivial case.
4115   if (Ops.size() == 1)
4116     return Ops[0];
4117 
4118   // Find the max type first.
4119   Type *MaxType = nullptr;
4120   for (auto *S : Ops)
4121     if (MaxType)
4122       MaxType = getWiderType(MaxType, S->getType());
4123     else
4124       MaxType = S->getType();
4125   assert(MaxType && "Failed to find maximum type!");
4126 
4127   // Extend all ops to max type.
4128   SmallVector<const SCEV *, 2> PromotedOps;
4129   for (auto *S : Ops)
4130     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4131 
4132   // Generate umin.
4133   return getUMinExpr(PromotedOps);
4134 }
4135 
4136 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4137   // A pointer operand may evaluate to a nonpointer expression, such as null.
4138   if (!V->getType()->isPointerTy())
4139     return V;
4140 
4141   while (true) {
4142     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4143       V = Cast->getOperand();
4144     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4145       const SCEV *PtrOp = nullptr;
4146       for (const SCEV *NAryOp : NAry->operands()) {
4147         if (NAryOp->getType()->isPointerTy()) {
4148           // Cannot find the base of an expression with multiple pointer ops.
4149           if (PtrOp)
4150             return V;
4151           PtrOp = NAryOp;
4152         }
4153       }
4154       if (!PtrOp) // All operands were non-pointer.
4155         return V;
4156       V = PtrOp;
4157     } else // Not something we can look further into.
4158       return V;
4159   }
4160 }
4161 
4162 /// Push users of the given Instruction onto the given Worklist.
4163 static void
4164 PushDefUseChildren(Instruction *I,
4165                    SmallVectorImpl<Instruction *> &Worklist) {
4166   // Push the def-use children onto the Worklist stack.
4167   for (User *U : I->users())
4168     Worklist.push_back(cast<Instruction>(U));
4169 }
4170 
4171 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4172   SmallVector<Instruction *, 16> Worklist;
4173   PushDefUseChildren(PN, Worklist);
4174 
4175   SmallPtrSet<Instruction *, 8> Visited;
4176   Visited.insert(PN);
4177   while (!Worklist.empty()) {
4178     Instruction *I = Worklist.pop_back_val();
4179     if (!Visited.insert(I).second)
4180       continue;
4181 
4182     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4183     if (It != ValueExprMap.end()) {
4184       const SCEV *Old = It->second;
4185 
4186       // Short-circuit the def-use traversal if the symbolic name
4187       // ceases to appear in expressions.
4188       if (Old != SymName && !hasOperand(Old, SymName))
4189         continue;
4190 
4191       // SCEVUnknown for a PHI either means that it has an unrecognized
4192       // structure, it's a PHI that's in the progress of being computed
4193       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4194       // additional loop trip count information isn't going to change anything.
4195       // In the second case, createNodeForPHI will perform the necessary
4196       // updates on its own when it gets to that point. In the third, we do
4197       // want to forget the SCEVUnknown.
4198       if (!isa<PHINode>(I) ||
4199           !isa<SCEVUnknown>(Old) ||
4200           (I != PN && Old == SymName)) {
4201         eraseValueFromMap(It->first);
4202         forgetMemoizedResults(Old);
4203       }
4204     }
4205 
4206     PushDefUseChildren(I, Worklist);
4207   }
4208 }
4209 
4210 namespace {
4211 
4212 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4213 /// expression in case its Loop is L. If it is not L then
4214 /// if IgnoreOtherLoops is true then use AddRec itself
4215 /// otherwise rewrite cannot be done.
4216 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4217 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4218 public:
4219   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4220                              bool IgnoreOtherLoops = true) {
4221     SCEVInitRewriter Rewriter(L, SE);
4222     const SCEV *Result = Rewriter.visit(S);
4223     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4224       return SE.getCouldNotCompute();
4225     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4226                ? SE.getCouldNotCompute()
4227                : Result;
4228   }
4229 
4230   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4231     if (!SE.isLoopInvariant(Expr, L))
4232       SeenLoopVariantSCEVUnknown = true;
4233     return Expr;
4234   }
4235 
4236   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4237     // Only re-write AddRecExprs for this loop.
4238     if (Expr->getLoop() == L)
4239       return Expr->getStart();
4240     SeenOtherLoops = true;
4241     return Expr;
4242   }
4243 
4244   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4245 
4246   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4247 
4248 private:
4249   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4250       : SCEVRewriteVisitor(SE), L(L) {}
4251 
4252   const Loop *L;
4253   bool SeenLoopVariantSCEVUnknown = false;
4254   bool SeenOtherLoops = false;
4255 };
4256 
4257 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4258 /// increment expression in case its Loop is L. If it is not L then
4259 /// use AddRec itself.
4260 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4261 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4262 public:
4263   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4264     SCEVPostIncRewriter Rewriter(L, SE);
4265     const SCEV *Result = Rewriter.visit(S);
4266     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4267         ? SE.getCouldNotCompute()
4268         : Result;
4269   }
4270 
4271   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4272     if (!SE.isLoopInvariant(Expr, L))
4273       SeenLoopVariantSCEVUnknown = true;
4274     return Expr;
4275   }
4276 
4277   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4278     // Only re-write AddRecExprs for this loop.
4279     if (Expr->getLoop() == L)
4280       return Expr->getPostIncExpr(SE);
4281     SeenOtherLoops = true;
4282     return Expr;
4283   }
4284 
4285   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4286 
4287   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4288 
4289 private:
4290   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4291       : SCEVRewriteVisitor(SE), L(L) {}
4292 
4293   const Loop *L;
4294   bool SeenLoopVariantSCEVUnknown = false;
4295   bool SeenOtherLoops = false;
4296 };
4297 
4298 /// This class evaluates the compare condition by matching it against the
4299 /// condition of loop latch. If there is a match we assume a true value
4300 /// for the condition while building SCEV nodes.
4301 class SCEVBackedgeConditionFolder
4302     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4303 public:
4304   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4305                              ScalarEvolution &SE) {
4306     bool IsPosBECond = false;
4307     Value *BECond = nullptr;
4308     if (BasicBlock *Latch = L->getLoopLatch()) {
4309       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4310       if (BI && BI->isConditional()) {
4311         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4312                "Both outgoing branches should not target same header!");
4313         BECond = BI->getCondition();
4314         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4315       } else {
4316         return S;
4317       }
4318     }
4319     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4320     return Rewriter.visit(S);
4321   }
4322 
4323   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4324     const SCEV *Result = Expr;
4325     bool InvariantF = SE.isLoopInvariant(Expr, L);
4326 
4327     if (!InvariantF) {
4328       Instruction *I = cast<Instruction>(Expr->getValue());
4329       switch (I->getOpcode()) {
4330       case Instruction::Select: {
4331         SelectInst *SI = cast<SelectInst>(I);
4332         Optional<const SCEV *> Res =
4333             compareWithBackedgeCondition(SI->getCondition());
4334         if (Res.hasValue()) {
4335           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4336           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4337         }
4338         break;
4339       }
4340       default: {
4341         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4342         if (Res.hasValue())
4343           Result = Res.getValue();
4344         break;
4345       }
4346       }
4347     }
4348     return Result;
4349   }
4350 
4351 private:
4352   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4353                                        bool IsPosBECond, ScalarEvolution &SE)
4354       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4355         IsPositiveBECond(IsPosBECond) {}
4356 
4357   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4358 
4359   const Loop *L;
4360   /// Loop back condition.
4361   Value *BackedgeCond = nullptr;
4362   /// Set to true if loop back is on positive branch condition.
4363   bool IsPositiveBECond;
4364 };
4365 
4366 Optional<const SCEV *>
4367 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4368 
4369   // If value matches the backedge condition for loop latch,
4370   // then return a constant evolution node based on loopback
4371   // branch taken.
4372   if (BackedgeCond == IC)
4373     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4374                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4375   return None;
4376 }
4377 
4378 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4379 public:
4380   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4381                              ScalarEvolution &SE) {
4382     SCEVShiftRewriter Rewriter(L, SE);
4383     const SCEV *Result = Rewriter.visit(S);
4384     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4385   }
4386 
4387   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4388     // Only allow AddRecExprs for this loop.
4389     if (!SE.isLoopInvariant(Expr, L))
4390       Valid = false;
4391     return Expr;
4392   }
4393 
4394   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4395     if (Expr->getLoop() == L && Expr->isAffine())
4396       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4397     Valid = false;
4398     return Expr;
4399   }
4400 
4401   bool isValid() { return Valid; }
4402 
4403 private:
4404   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4405       : SCEVRewriteVisitor(SE), L(L) {}
4406 
4407   const Loop *L;
4408   bool Valid = true;
4409 };
4410 
4411 } // end anonymous namespace
4412 
4413 SCEV::NoWrapFlags
4414 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4415   if (!AR->isAffine())
4416     return SCEV::FlagAnyWrap;
4417 
4418   using OBO = OverflowingBinaryOperator;
4419 
4420   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4421 
4422   if (!AR->hasNoSignedWrap()) {
4423     ConstantRange AddRecRange = getSignedRange(AR);
4424     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4425 
4426     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4427         Instruction::Add, IncRange, OBO::NoSignedWrap);
4428     if (NSWRegion.contains(AddRecRange))
4429       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4430   }
4431 
4432   if (!AR->hasNoUnsignedWrap()) {
4433     ConstantRange AddRecRange = getUnsignedRange(AR);
4434     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4435 
4436     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4437         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4438     if (NUWRegion.contains(AddRecRange))
4439       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4440   }
4441 
4442   return Result;
4443 }
4444 
4445 SCEV::NoWrapFlags
4446 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4447   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4448 
4449   if (AR->hasNoSignedWrap())
4450     return Result;
4451 
4452   if (!AR->isAffine())
4453     return Result;
4454 
4455   const SCEV *Step = AR->getStepRecurrence(*this);
4456   const Loop *L = AR->getLoop();
4457 
4458   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4459   // Note that this serves two purposes: It filters out loops that are
4460   // simply not analyzable, and it covers the case where this code is
4461   // being called from within backedge-taken count analysis, such that
4462   // attempting to ask for the backedge-taken count would likely result
4463   // in infinite recursion. In the later case, the analysis code will
4464   // cope with a conservative value, and it will take care to purge
4465   // that value once it has finished.
4466   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4467 
4468   // Normally, in the cases we can prove no-overflow via a
4469   // backedge guarding condition, we can also compute a backedge
4470   // taken count for the loop.  The exceptions are assumptions and
4471   // guards present in the loop -- SCEV is not great at exploiting
4472   // these to compute max backedge taken counts, but can still use
4473   // these to prove lack of overflow.  Use this fact to avoid
4474   // doing extra work that may not pay off.
4475 
4476   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4477       AC.assumptions().empty())
4478     return Result;
4479 
4480   // If the backedge is guarded by a comparison with the pre-inc  value the
4481   // addrec is safe. Also, if the entry is guarded by a comparison with the
4482   // start value and the backedge is guarded by a comparison with the post-inc
4483   // value, the addrec is safe.
4484   ICmpInst::Predicate Pred;
4485   const SCEV *OverflowLimit =
4486     getSignedOverflowLimitForStep(Step, &Pred, this);
4487   if (OverflowLimit &&
4488       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4489        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4490     Result = setFlags(Result, SCEV::FlagNSW);
4491   }
4492   return Result;
4493 }
4494 SCEV::NoWrapFlags
4495 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4496   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4497 
4498   if (AR->hasNoUnsignedWrap())
4499     return Result;
4500 
4501   if (!AR->isAffine())
4502     return Result;
4503 
4504   const SCEV *Step = AR->getStepRecurrence(*this);
4505   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4506   const Loop *L = AR->getLoop();
4507 
4508   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4509   // Note that this serves two purposes: It filters out loops that are
4510   // simply not analyzable, and it covers the case where this code is
4511   // being called from within backedge-taken count analysis, such that
4512   // attempting to ask for the backedge-taken count would likely result
4513   // in infinite recursion. In the later case, the analysis code will
4514   // cope with a conservative value, and it will take care to purge
4515   // that value once it has finished.
4516   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4517 
4518   // Normally, in the cases we can prove no-overflow via a
4519   // backedge guarding condition, we can also compute a backedge
4520   // taken count for the loop.  The exceptions are assumptions and
4521   // guards present in the loop -- SCEV is not great at exploiting
4522   // these to compute max backedge taken counts, but can still use
4523   // these to prove lack of overflow.  Use this fact to avoid
4524   // doing extra work that may not pay off.
4525 
4526   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4527       AC.assumptions().empty())
4528     return Result;
4529 
4530   // If the backedge is guarded by a comparison with the pre-inc  value the
4531   // addrec is safe. Also, if the entry is guarded by a comparison with the
4532   // start value and the backedge is guarded by a comparison with the post-inc
4533   // value, the addrec is safe.
4534   if (isKnownPositive(Step)) {
4535     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4536                                 getUnsignedRangeMax(Step));
4537     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4538         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4539       Result = setFlags(Result, SCEV::FlagNUW);
4540     }
4541   }
4542 
4543   return Result;
4544 }
4545 
4546 namespace {
4547 
4548 /// Represents an abstract binary operation.  This may exist as a
4549 /// normal instruction or constant expression, or may have been
4550 /// derived from an expression tree.
4551 struct BinaryOp {
4552   unsigned Opcode;
4553   Value *LHS;
4554   Value *RHS;
4555   bool IsNSW = false;
4556   bool IsNUW = false;
4557   bool IsExact = false;
4558 
4559   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4560   /// constant expression.
4561   Operator *Op = nullptr;
4562 
4563   explicit BinaryOp(Operator *Op)
4564       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4565         Op(Op) {
4566     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4567       IsNSW = OBO->hasNoSignedWrap();
4568       IsNUW = OBO->hasNoUnsignedWrap();
4569     }
4570     if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op))
4571       IsExact = PEO->isExact();
4572   }
4573 
4574   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4575                     bool IsNUW = false, bool IsExact = false)
4576       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4577         IsExact(IsExact) {}
4578 };
4579 
4580 } // end anonymous namespace
4581 
4582 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4583 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4584   auto *Op = dyn_cast<Operator>(V);
4585   if (!Op)
4586     return None;
4587 
4588   // Implementation detail: all the cleverness here should happen without
4589   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4590   // SCEV expressions when possible, and we should not break that.
4591 
4592   switch (Op->getOpcode()) {
4593   case Instruction::Add:
4594   case Instruction::Sub:
4595   case Instruction::Mul:
4596   case Instruction::UDiv:
4597   case Instruction::URem:
4598   case Instruction::And:
4599   case Instruction::Or:
4600   case Instruction::AShr:
4601   case Instruction::Shl:
4602     return BinaryOp(Op);
4603 
4604   case Instruction::Xor:
4605     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4606       // If the RHS of the xor is a signmask, then this is just an add.
4607       // Instcombine turns add of signmask into xor as a strength reduction step.
4608       if (RHSC->getValue().isSignMask())
4609         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4610     return BinaryOp(Op);
4611 
4612   case Instruction::LShr:
4613     // Turn logical shift right of a constant into a unsigned divide.
4614     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4615       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4616 
4617       // If the shift count is not less than the bitwidth, the result of
4618       // the shift is undefined. Don't try to analyze it, because the
4619       // resolution chosen here may differ from the resolution chosen in
4620       // other parts of the compiler.
4621       if (SA->getValue().ult(BitWidth)) {
4622         Constant *X =
4623             ConstantInt::get(SA->getContext(),
4624                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4625         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4626       }
4627     }
4628     return BinaryOp(Op);
4629 
4630   case Instruction::ExtractValue: {
4631     auto *EVI = cast<ExtractValueInst>(Op);
4632     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4633       break;
4634 
4635     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4636     if (!WO)
4637       break;
4638 
4639     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4640     bool Signed = WO->isSigned();
4641     // TODO: Should add nuw/nsw flags for mul as well.
4642     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4643       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4644 
4645     // Now that we know that all uses of the arithmetic-result component of
4646     // CI are guarded by the overflow check, we can go ahead and pretend
4647     // that the arithmetic is non-overflowing.
4648     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4649                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4650   }
4651 
4652   default:
4653     break;
4654   }
4655 
4656   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4657   // semantics as a Sub, return a binary sub expression.
4658   if (auto *II = dyn_cast<IntrinsicInst>(V))
4659     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4660       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4661 
4662   return None;
4663 }
4664 
4665 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4666 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4667 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4668 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4669 /// follows one of the following patterns:
4670 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4671 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4672 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4673 /// we return the type of the truncation operation, and indicate whether the
4674 /// truncated type should be treated as signed/unsigned by setting
4675 /// \p Signed to true/false, respectively.
4676 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4677                                bool &Signed, ScalarEvolution &SE) {
4678   // The case where Op == SymbolicPHI (that is, with no type conversions on
4679   // the way) is handled by the regular add recurrence creating logic and
4680   // would have already been triggered in createAddRecForPHI. Reaching it here
4681   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4682   // because one of the other operands of the SCEVAddExpr updating this PHI is
4683   // not invariant).
4684   //
4685   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4686   // this case predicates that allow us to prove that Op == SymbolicPHI will
4687   // be added.
4688   if (Op == SymbolicPHI)
4689     return nullptr;
4690 
4691   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4692   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4693   if (SourceBits != NewBits)
4694     return nullptr;
4695 
4696   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4697   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4698   if (!SExt && !ZExt)
4699     return nullptr;
4700   const SCEVTruncateExpr *Trunc =
4701       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4702            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4703   if (!Trunc)
4704     return nullptr;
4705   const SCEV *X = Trunc->getOperand();
4706   if (X != SymbolicPHI)
4707     return nullptr;
4708   Signed = SExt != nullptr;
4709   return Trunc->getType();
4710 }
4711 
4712 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4713   if (!PN->getType()->isIntegerTy())
4714     return nullptr;
4715   const Loop *L = LI.getLoopFor(PN->getParent());
4716   if (!L || L->getHeader() != PN->getParent())
4717     return nullptr;
4718   return L;
4719 }
4720 
4721 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4722 // computation that updates the phi follows the following pattern:
4723 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4724 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4725 // If so, try to see if it can be rewritten as an AddRecExpr under some
4726 // Predicates. If successful, return them as a pair. Also cache the results
4727 // of the analysis.
4728 //
4729 // Example usage scenario:
4730 //    Say the Rewriter is called for the following SCEV:
4731 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4732 //    where:
4733 //         %X = phi i64 (%Start, %BEValue)
4734 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4735 //    and call this function with %SymbolicPHI = %X.
4736 //
4737 //    The analysis will find that the value coming around the backedge has
4738 //    the following SCEV:
4739 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4740 //    Upon concluding that this matches the desired pattern, the function
4741 //    will return the pair {NewAddRec, SmallPredsVec} where:
4742 //         NewAddRec = {%Start,+,%Step}
4743 //         SmallPredsVec = {P1, P2, P3} as follows:
4744 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4745 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4746 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4747 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4748 //    under the predicates {P1,P2,P3}.
4749 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4750 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4751 //
4752 // TODO's:
4753 //
4754 // 1) Extend the Induction descriptor to also support inductions that involve
4755 //    casts: When needed (namely, when we are called in the context of the
4756 //    vectorizer induction analysis), a Set of cast instructions will be
4757 //    populated by this method, and provided back to isInductionPHI. This is
4758 //    needed to allow the vectorizer to properly record them to be ignored by
4759 //    the cost model and to avoid vectorizing them (otherwise these casts,
4760 //    which are redundant under the runtime overflow checks, will be
4761 //    vectorized, which can be costly).
4762 //
4763 // 2) Support additional induction/PHISCEV patterns: We also want to support
4764 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4765 //    after the induction update operation (the induction increment):
4766 //
4767 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4768 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4769 //
4770 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4771 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4772 //
4773 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4774 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4775 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4776   SmallVector<const SCEVPredicate *, 3> Predicates;
4777 
4778   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4779   // return an AddRec expression under some predicate.
4780 
4781   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4782   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4783   assert(L && "Expecting an integer loop header phi");
4784 
4785   // The loop may have multiple entrances or multiple exits; we can analyze
4786   // this phi as an addrec if it has a unique entry value and a unique
4787   // backedge value.
4788   Value *BEValueV = nullptr, *StartValueV = nullptr;
4789   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4790     Value *V = PN->getIncomingValue(i);
4791     if (L->contains(PN->getIncomingBlock(i))) {
4792       if (!BEValueV) {
4793         BEValueV = V;
4794       } else if (BEValueV != V) {
4795         BEValueV = nullptr;
4796         break;
4797       }
4798     } else if (!StartValueV) {
4799       StartValueV = V;
4800     } else if (StartValueV != V) {
4801       StartValueV = nullptr;
4802       break;
4803     }
4804   }
4805   if (!BEValueV || !StartValueV)
4806     return None;
4807 
4808   const SCEV *BEValue = getSCEV(BEValueV);
4809 
4810   // If the value coming around the backedge is an add with the symbolic
4811   // value we just inserted, possibly with casts that we can ignore under
4812   // an appropriate runtime guard, then we found a simple induction variable!
4813   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4814   if (!Add)
4815     return None;
4816 
4817   // If there is a single occurrence of the symbolic value, possibly
4818   // casted, replace it with a recurrence.
4819   unsigned FoundIndex = Add->getNumOperands();
4820   Type *TruncTy = nullptr;
4821   bool Signed;
4822   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4823     if ((TruncTy =
4824              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4825       if (FoundIndex == e) {
4826         FoundIndex = i;
4827         break;
4828       }
4829 
4830   if (FoundIndex == Add->getNumOperands())
4831     return None;
4832 
4833   // Create an add with everything but the specified operand.
4834   SmallVector<const SCEV *, 8> Ops;
4835   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4836     if (i != FoundIndex)
4837       Ops.push_back(Add->getOperand(i));
4838   const SCEV *Accum = getAddExpr(Ops);
4839 
4840   // The runtime checks will not be valid if the step amount is
4841   // varying inside the loop.
4842   if (!isLoopInvariant(Accum, L))
4843     return None;
4844 
4845   // *** Part2: Create the predicates
4846 
4847   // Analysis was successful: we have a phi-with-cast pattern for which we
4848   // can return an AddRec expression under the following predicates:
4849   //
4850   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4851   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4852   // P2: An Equal predicate that guarantees that
4853   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4854   // P3: An Equal predicate that guarantees that
4855   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4856   //
4857   // As we next prove, the above predicates guarantee that:
4858   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4859   //
4860   //
4861   // More formally, we want to prove that:
4862   //     Expr(i+1) = Start + (i+1) * Accum
4863   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4864   //
4865   // Given that:
4866   // 1) Expr(0) = Start
4867   // 2) Expr(1) = Start + Accum
4868   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4869   // 3) Induction hypothesis (step i):
4870   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4871   //
4872   // Proof:
4873   //  Expr(i+1) =
4874   //   = Start + (i+1)*Accum
4875   //   = (Start + i*Accum) + Accum
4876   //   = Expr(i) + Accum
4877   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4878   //                                                             :: from step i
4879   //
4880   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4881   //
4882   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4883   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4884   //     + Accum                                                     :: from P3
4885   //
4886   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4887   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4888   //
4889   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4890   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4891   //
4892   // By induction, the same applies to all iterations 1<=i<n:
4893   //
4894 
4895   // Create a truncated addrec for which we will add a no overflow check (P1).
4896   const SCEV *StartVal = getSCEV(StartValueV);
4897   const SCEV *PHISCEV =
4898       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4899                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4900 
4901   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4902   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4903   // will be constant.
4904   //
4905   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4906   // add P1.
4907   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4908     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4909         Signed ? SCEVWrapPredicate::IncrementNSSW
4910                : SCEVWrapPredicate::IncrementNUSW;
4911     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4912     Predicates.push_back(AddRecPred);
4913   }
4914 
4915   // Create the Equal Predicates P2,P3:
4916 
4917   // It is possible that the predicates P2 and/or P3 are computable at
4918   // compile time due to StartVal and/or Accum being constants.
4919   // If either one is, then we can check that now and escape if either P2
4920   // or P3 is false.
4921 
4922   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4923   // for each of StartVal and Accum
4924   auto getExtendedExpr = [&](const SCEV *Expr,
4925                              bool CreateSignExtend) -> const SCEV * {
4926     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4927     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4928     const SCEV *ExtendedExpr =
4929         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4930                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4931     return ExtendedExpr;
4932   };
4933 
4934   // Given:
4935   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4936   //               = getExtendedExpr(Expr)
4937   // Determine whether the predicate P: Expr == ExtendedExpr
4938   // is known to be false at compile time
4939   auto PredIsKnownFalse = [&](const SCEV *Expr,
4940                               const SCEV *ExtendedExpr) -> bool {
4941     return Expr != ExtendedExpr &&
4942            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4943   };
4944 
4945   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4946   if (PredIsKnownFalse(StartVal, StartExtended)) {
4947     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4948     return None;
4949   }
4950 
4951   // The Step is always Signed (because the overflow checks are either
4952   // NSSW or NUSW)
4953   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4954   if (PredIsKnownFalse(Accum, AccumExtended)) {
4955     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4956     return None;
4957   }
4958 
4959   auto AppendPredicate = [&](const SCEV *Expr,
4960                              const SCEV *ExtendedExpr) -> void {
4961     if (Expr != ExtendedExpr &&
4962         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4963       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4964       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4965       Predicates.push_back(Pred);
4966     }
4967   };
4968 
4969   AppendPredicate(StartVal, StartExtended);
4970   AppendPredicate(Accum, AccumExtended);
4971 
4972   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4973   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4974   // into NewAR if it will also add the runtime overflow checks specified in
4975   // Predicates.
4976   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4977 
4978   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4979       std::make_pair(NewAR, Predicates);
4980   // Remember the result of the analysis for this SCEV at this locayyytion.
4981   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4982   return PredRewrite;
4983 }
4984 
4985 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4986 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4987   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4988   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4989   if (!L)
4990     return None;
4991 
4992   // Check to see if we already analyzed this PHI.
4993   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4994   if (I != PredicatedSCEVRewrites.end()) {
4995     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4996         I->second;
4997     // Analysis was done before and failed to create an AddRec:
4998     if (Rewrite.first == SymbolicPHI)
4999       return None;
5000     // Analysis was done before and succeeded to create an AddRec under
5001     // a predicate:
5002     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5003     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5004     return Rewrite;
5005   }
5006 
5007   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5008     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5009 
5010   // Record in the cache that the analysis failed
5011   if (!Rewrite) {
5012     SmallVector<const SCEVPredicate *, 3> Predicates;
5013     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5014     return None;
5015   }
5016 
5017   return Rewrite;
5018 }
5019 
5020 // FIXME: This utility is currently required because the Rewriter currently
5021 // does not rewrite this expression:
5022 // {0, +, (sext ix (trunc iy to ix) to iy)}
5023 // into {0, +, %step},
5024 // even when the following Equal predicate exists:
5025 // "%step == (sext ix (trunc iy to ix) to iy)".
5026 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5027     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5028   if (AR1 == AR2)
5029     return true;
5030 
5031   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5032     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5033         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5034       return false;
5035     return true;
5036   };
5037 
5038   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5039       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5040     return false;
5041   return true;
5042 }
5043 
5044 /// A helper function for createAddRecFromPHI to handle simple cases.
5045 ///
5046 /// This function tries to find an AddRec expression for the simplest (yet most
5047 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5048 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5049 /// technique for finding the AddRec expression.
5050 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5051                                                       Value *BEValueV,
5052                                                       Value *StartValueV) {
5053   const Loop *L = LI.getLoopFor(PN->getParent());
5054   assert(L && L->getHeader() == PN->getParent());
5055   assert(BEValueV && StartValueV);
5056 
5057   auto BO = MatchBinaryOp(BEValueV, DT);
5058   if (!BO)
5059     return nullptr;
5060 
5061   if (BO->Opcode != Instruction::Add)
5062     return nullptr;
5063 
5064   const SCEV *Accum = nullptr;
5065   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5066     Accum = getSCEV(BO->RHS);
5067   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5068     Accum = getSCEV(BO->LHS);
5069 
5070   if (!Accum)
5071     return nullptr;
5072 
5073   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5074   if (BO->IsNUW)
5075     Flags = setFlags(Flags, SCEV::FlagNUW);
5076   if (BO->IsNSW)
5077     Flags = setFlags(Flags, SCEV::FlagNSW);
5078 
5079   const SCEV *StartVal = getSCEV(StartValueV);
5080   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5081 
5082   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5083 
5084   // We can add Flags to the post-inc expression only if we
5085   // know that it is *undefined behavior* for BEValueV to
5086   // overflow.
5087   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5088     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5089       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5090 
5091   return PHISCEV;
5092 }
5093 
5094 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5095   const Loop *L = LI.getLoopFor(PN->getParent());
5096   if (!L || L->getHeader() != PN->getParent())
5097     return nullptr;
5098 
5099   // The loop may have multiple entrances or multiple exits; we can analyze
5100   // this phi as an addrec if it has a unique entry value and a unique
5101   // backedge value.
5102   Value *BEValueV = nullptr, *StartValueV = nullptr;
5103   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5104     Value *V = PN->getIncomingValue(i);
5105     if (L->contains(PN->getIncomingBlock(i))) {
5106       if (!BEValueV) {
5107         BEValueV = V;
5108       } else if (BEValueV != V) {
5109         BEValueV = nullptr;
5110         break;
5111       }
5112     } else if (!StartValueV) {
5113       StartValueV = V;
5114     } else if (StartValueV != V) {
5115       StartValueV = nullptr;
5116       break;
5117     }
5118   }
5119   if (!BEValueV || !StartValueV)
5120     return nullptr;
5121 
5122   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5123          "PHI node already processed?");
5124 
5125   // First, try to find AddRec expression without creating a fictituos symbolic
5126   // value for PN.
5127   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5128     return S;
5129 
5130   // Handle PHI node value symbolically.
5131   const SCEV *SymbolicName = getUnknown(PN);
5132   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5133 
5134   // Using this symbolic name for the PHI, analyze the value coming around
5135   // the back-edge.
5136   const SCEV *BEValue = getSCEV(BEValueV);
5137 
5138   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5139   // has a special value for the first iteration of the loop.
5140 
5141   // If the value coming around the backedge is an add with the symbolic
5142   // value we just inserted, then we found a simple induction variable!
5143   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5144     // If there is a single occurrence of the symbolic value, replace it
5145     // with a recurrence.
5146     unsigned FoundIndex = Add->getNumOperands();
5147     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5148       if (Add->getOperand(i) == SymbolicName)
5149         if (FoundIndex == e) {
5150           FoundIndex = i;
5151           break;
5152         }
5153 
5154     if (FoundIndex != Add->getNumOperands()) {
5155       // Create an add with everything but the specified operand.
5156       SmallVector<const SCEV *, 8> Ops;
5157       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5158         if (i != FoundIndex)
5159           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5160                                                              L, *this));
5161       const SCEV *Accum = getAddExpr(Ops);
5162 
5163       // This is not a valid addrec if the step amount is varying each
5164       // loop iteration, but is not itself an addrec in this loop.
5165       if (isLoopInvariant(Accum, L) ||
5166           (isa<SCEVAddRecExpr>(Accum) &&
5167            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5168         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5169 
5170         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5171           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5172             if (BO->IsNUW)
5173               Flags = setFlags(Flags, SCEV::FlagNUW);
5174             if (BO->IsNSW)
5175               Flags = setFlags(Flags, SCEV::FlagNSW);
5176           }
5177         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5178           // If the increment is an inbounds GEP, then we know the address
5179           // space cannot be wrapped around. We cannot make any guarantee
5180           // about signed or unsigned overflow because pointers are
5181           // unsigned but we may have a negative index from the base
5182           // pointer. We can guarantee that no unsigned wrap occurs if the
5183           // indices form a positive value.
5184           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5185             Flags = setFlags(Flags, SCEV::FlagNW);
5186 
5187             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5188             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5189               Flags = setFlags(Flags, SCEV::FlagNUW);
5190           }
5191 
5192           // We cannot transfer nuw and nsw flags from subtraction
5193           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5194           // for instance.
5195         }
5196 
5197         const SCEV *StartVal = getSCEV(StartValueV);
5198         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5199 
5200         // Okay, for the entire analysis of this edge we assumed the PHI
5201         // to be symbolic.  We now need to go back and purge all of the
5202         // entries for the scalars that use the symbolic expression.
5203         forgetSymbolicName(PN, SymbolicName);
5204         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5205 
5206         // We can add Flags to the post-inc expression only if we
5207         // know that it is *undefined behavior* for BEValueV to
5208         // overflow.
5209         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5210           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5211             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5212 
5213         return PHISCEV;
5214       }
5215     }
5216   } else {
5217     // Otherwise, this could be a loop like this:
5218     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5219     // In this case, j = {1,+,1}  and BEValue is j.
5220     // Because the other in-value of i (0) fits the evolution of BEValue
5221     // i really is an addrec evolution.
5222     //
5223     // We can generalize this saying that i is the shifted value of BEValue
5224     // by one iteration:
5225     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5226     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5227     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5228     if (Shifted != getCouldNotCompute() &&
5229         Start != getCouldNotCompute()) {
5230       const SCEV *StartVal = getSCEV(StartValueV);
5231       if (Start == StartVal) {
5232         // Okay, for the entire analysis of this edge we assumed the PHI
5233         // to be symbolic.  We now need to go back and purge all of the
5234         // entries for the scalars that use the symbolic expression.
5235         forgetSymbolicName(PN, SymbolicName);
5236         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5237         return Shifted;
5238       }
5239     }
5240   }
5241 
5242   // Remove the temporary PHI node SCEV that has been inserted while intending
5243   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5244   // as it will prevent later (possibly simpler) SCEV expressions to be added
5245   // to the ValueExprMap.
5246   eraseValueFromMap(PN);
5247 
5248   return nullptr;
5249 }
5250 
5251 // Checks if the SCEV S is available at BB.  S is considered available at BB
5252 // if S can be materialized at BB without introducing a fault.
5253 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5254                                BasicBlock *BB) {
5255   struct CheckAvailable {
5256     bool TraversalDone = false;
5257     bool Available = true;
5258 
5259     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5260     BasicBlock *BB = nullptr;
5261     DominatorTree &DT;
5262 
5263     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5264       : L(L), BB(BB), DT(DT) {}
5265 
5266     bool setUnavailable() {
5267       TraversalDone = true;
5268       Available = false;
5269       return false;
5270     }
5271 
5272     bool follow(const SCEV *S) {
5273       switch (S->getSCEVType()) {
5274       case scConstant:
5275       case scPtrToInt:
5276       case scTruncate:
5277       case scZeroExtend:
5278       case scSignExtend:
5279       case scAddExpr:
5280       case scMulExpr:
5281       case scUMaxExpr:
5282       case scSMaxExpr:
5283       case scUMinExpr:
5284       case scSMinExpr:
5285         // These expressions are available if their operand(s) is/are.
5286         return true;
5287 
5288       case scAddRecExpr: {
5289         // We allow add recurrences that are on the loop BB is in, or some
5290         // outer loop.  This guarantees availability because the value of the
5291         // add recurrence at BB is simply the "current" value of the induction
5292         // variable.  We can relax this in the future; for instance an add
5293         // recurrence on a sibling dominating loop is also available at BB.
5294         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5295         if (L && (ARLoop == L || ARLoop->contains(L)))
5296           return true;
5297 
5298         return setUnavailable();
5299       }
5300 
5301       case scUnknown: {
5302         // For SCEVUnknown, we check for simple dominance.
5303         const auto *SU = cast<SCEVUnknown>(S);
5304         Value *V = SU->getValue();
5305 
5306         if (isa<Argument>(V))
5307           return false;
5308 
5309         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5310           return false;
5311 
5312         return setUnavailable();
5313       }
5314 
5315       case scUDivExpr:
5316       case scCouldNotCompute:
5317         // We do not try to smart about these at all.
5318         return setUnavailable();
5319       }
5320       llvm_unreachable("Unknown SCEV kind!");
5321     }
5322 
5323     bool isDone() { return TraversalDone; }
5324   };
5325 
5326   CheckAvailable CA(L, BB, DT);
5327   SCEVTraversal<CheckAvailable> ST(CA);
5328 
5329   ST.visitAll(S);
5330   return CA.Available;
5331 }
5332 
5333 // Try to match a control flow sequence that branches out at BI and merges back
5334 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5335 // match.
5336 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5337                           Value *&C, Value *&LHS, Value *&RHS) {
5338   C = BI->getCondition();
5339 
5340   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5341   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5342 
5343   if (!LeftEdge.isSingleEdge())
5344     return false;
5345 
5346   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5347 
5348   Use &LeftUse = Merge->getOperandUse(0);
5349   Use &RightUse = Merge->getOperandUse(1);
5350 
5351   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5352     LHS = LeftUse;
5353     RHS = RightUse;
5354     return true;
5355   }
5356 
5357   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5358     LHS = RightUse;
5359     RHS = LeftUse;
5360     return true;
5361   }
5362 
5363   return false;
5364 }
5365 
5366 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5367   auto IsReachable =
5368       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5369   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5370     const Loop *L = LI.getLoopFor(PN->getParent());
5371 
5372     // We don't want to break LCSSA, even in a SCEV expression tree.
5373     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5374       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5375         return nullptr;
5376 
5377     // Try to match
5378     //
5379     //  br %cond, label %left, label %right
5380     // left:
5381     //  br label %merge
5382     // right:
5383     //  br label %merge
5384     // merge:
5385     //  V = phi [ %x, %left ], [ %y, %right ]
5386     //
5387     // as "select %cond, %x, %y"
5388 
5389     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5390     assert(IDom && "At least the entry block should dominate PN");
5391 
5392     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5393     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5394 
5395     if (BI && BI->isConditional() &&
5396         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5397         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5398         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5399       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5400   }
5401 
5402   return nullptr;
5403 }
5404 
5405 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5406   if (const SCEV *S = createAddRecFromPHI(PN))
5407     return S;
5408 
5409   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5410     return S;
5411 
5412   // If the PHI has a single incoming value, follow that value, unless the
5413   // PHI's incoming blocks are in a different loop, in which case doing so
5414   // risks breaking LCSSA form. Instcombine would normally zap these, but
5415   // it doesn't have DominatorTree information, so it may miss cases.
5416   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5417     if (LI.replacementPreservesLCSSAForm(PN, V))
5418       return getSCEV(V);
5419 
5420   // If it's not a loop phi, we can't handle it yet.
5421   return getUnknown(PN);
5422 }
5423 
5424 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5425                                                       Value *Cond,
5426                                                       Value *TrueVal,
5427                                                       Value *FalseVal) {
5428   // Handle "constant" branch or select. This can occur for instance when a
5429   // loop pass transforms an inner loop and moves on to process the outer loop.
5430   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5431     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5432 
5433   // Try to match some simple smax or umax patterns.
5434   auto *ICI = dyn_cast<ICmpInst>(Cond);
5435   if (!ICI)
5436     return getUnknown(I);
5437 
5438   Value *LHS = ICI->getOperand(0);
5439   Value *RHS = ICI->getOperand(1);
5440 
5441   switch (ICI->getPredicate()) {
5442   case ICmpInst::ICMP_SLT:
5443   case ICmpInst::ICMP_SLE:
5444     std::swap(LHS, RHS);
5445     LLVM_FALLTHROUGH;
5446   case ICmpInst::ICMP_SGT:
5447   case ICmpInst::ICMP_SGE:
5448     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5449     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5450     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5451       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5452       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5453       const SCEV *LA = getSCEV(TrueVal);
5454       const SCEV *RA = getSCEV(FalseVal);
5455       const SCEV *LDiff = getMinusSCEV(LA, LS);
5456       const SCEV *RDiff = getMinusSCEV(RA, RS);
5457       if (LDiff == RDiff)
5458         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5459       LDiff = getMinusSCEV(LA, RS);
5460       RDiff = getMinusSCEV(RA, LS);
5461       if (LDiff == RDiff)
5462         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5463     }
5464     break;
5465   case ICmpInst::ICMP_ULT:
5466   case ICmpInst::ICMP_ULE:
5467     std::swap(LHS, RHS);
5468     LLVM_FALLTHROUGH;
5469   case ICmpInst::ICMP_UGT:
5470   case ICmpInst::ICMP_UGE:
5471     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5472     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5473     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5474       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5475       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5476       const SCEV *LA = getSCEV(TrueVal);
5477       const SCEV *RA = getSCEV(FalseVal);
5478       const SCEV *LDiff = getMinusSCEV(LA, LS);
5479       const SCEV *RDiff = getMinusSCEV(RA, RS);
5480       if (LDiff == RDiff)
5481         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5482       LDiff = getMinusSCEV(LA, RS);
5483       RDiff = getMinusSCEV(RA, LS);
5484       if (LDiff == RDiff)
5485         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5486     }
5487     break;
5488   case ICmpInst::ICMP_NE:
5489     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5490     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5491         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5492       const SCEV *One = getOne(I->getType());
5493       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5494       const SCEV *LA = getSCEV(TrueVal);
5495       const SCEV *RA = getSCEV(FalseVal);
5496       const SCEV *LDiff = getMinusSCEV(LA, LS);
5497       const SCEV *RDiff = getMinusSCEV(RA, One);
5498       if (LDiff == RDiff)
5499         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5500     }
5501     break;
5502   case ICmpInst::ICMP_EQ:
5503     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5504     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5505         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5506       const SCEV *One = getOne(I->getType());
5507       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5508       const SCEV *LA = getSCEV(TrueVal);
5509       const SCEV *RA = getSCEV(FalseVal);
5510       const SCEV *LDiff = getMinusSCEV(LA, One);
5511       const SCEV *RDiff = getMinusSCEV(RA, LS);
5512       if (LDiff == RDiff)
5513         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5514     }
5515     break;
5516   default:
5517     break;
5518   }
5519 
5520   return getUnknown(I);
5521 }
5522 
5523 /// Expand GEP instructions into add and multiply operations. This allows them
5524 /// to be analyzed by regular SCEV code.
5525 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5526   // Don't attempt to analyze GEPs over unsized objects.
5527   if (!GEP->getSourceElementType()->isSized())
5528     return getUnknown(GEP);
5529 
5530   SmallVector<const SCEV *, 4> IndexExprs;
5531   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5532     IndexExprs.push_back(getSCEV(*Index));
5533   return getGEPExpr(GEP, IndexExprs);
5534 }
5535 
5536 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5537   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5538     return C->getAPInt().countTrailingZeros();
5539 
5540   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5541     return GetMinTrailingZeros(I->getOperand());
5542 
5543   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5544     return std::min(GetMinTrailingZeros(T->getOperand()),
5545                     (uint32_t)getTypeSizeInBits(T->getType()));
5546 
5547   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5548     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5549     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5550                ? getTypeSizeInBits(E->getType())
5551                : OpRes;
5552   }
5553 
5554   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5555     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5556     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5557                ? getTypeSizeInBits(E->getType())
5558                : OpRes;
5559   }
5560 
5561   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5562     // The result is the min of all operands results.
5563     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5564     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5565       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5566     return MinOpRes;
5567   }
5568 
5569   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5570     // The result is the sum of all operands results.
5571     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5572     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5573     for (unsigned i = 1, e = M->getNumOperands();
5574          SumOpRes != BitWidth && i != e; ++i)
5575       SumOpRes =
5576           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5577     return SumOpRes;
5578   }
5579 
5580   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5581     // The result is the min of all operands results.
5582     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5583     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5584       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5585     return MinOpRes;
5586   }
5587 
5588   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5589     // The result is the min of all operands results.
5590     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5591     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5592       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5593     return MinOpRes;
5594   }
5595 
5596   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5597     // The result is the min of all operands results.
5598     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5599     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5600       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5601     return MinOpRes;
5602   }
5603 
5604   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5605     // For a SCEVUnknown, ask ValueTracking.
5606     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5607     return Known.countMinTrailingZeros();
5608   }
5609 
5610   // SCEVUDivExpr
5611   return 0;
5612 }
5613 
5614 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5615   auto I = MinTrailingZerosCache.find(S);
5616   if (I != MinTrailingZerosCache.end())
5617     return I->second;
5618 
5619   uint32_t Result = GetMinTrailingZerosImpl(S);
5620   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5621   assert(InsertPair.second && "Should insert a new key");
5622   return InsertPair.first->second;
5623 }
5624 
5625 /// Helper method to assign a range to V from metadata present in the IR.
5626 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5627   if (Instruction *I = dyn_cast<Instruction>(V))
5628     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5629       return getConstantRangeFromMetadata(*MD);
5630 
5631   return None;
5632 }
5633 
5634 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5635                                      SCEV::NoWrapFlags Flags) {
5636   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5637     AddRec->setNoWrapFlags(Flags);
5638     UnsignedRanges.erase(AddRec);
5639     SignedRanges.erase(AddRec);
5640   }
5641 }
5642 
5643 /// Determine the range for a particular SCEV.  If SignHint is
5644 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5645 /// with a "cleaner" unsigned (resp. signed) representation.
5646 const ConstantRange &
5647 ScalarEvolution::getRangeRef(const SCEV *S,
5648                              ScalarEvolution::RangeSignHint SignHint) {
5649   DenseMap<const SCEV *, ConstantRange> &Cache =
5650       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5651                                                        : SignedRanges;
5652   ConstantRange::PreferredRangeType RangeType =
5653       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5654           ? ConstantRange::Unsigned : ConstantRange::Signed;
5655 
5656   // See if we've computed this range already.
5657   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5658   if (I != Cache.end())
5659     return I->second;
5660 
5661   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5662     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5663 
5664   unsigned BitWidth = getTypeSizeInBits(S->getType());
5665   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5666   using OBO = OverflowingBinaryOperator;
5667 
5668   // If the value has known zeros, the maximum value will have those known zeros
5669   // as well.
5670   uint32_t TZ = GetMinTrailingZeros(S);
5671   if (TZ != 0) {
5672     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5673       ConservativeResult =
5674           ConstantRange(APInt::getMinValue(BitWidth),
5675                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5676     else
5677       ConservativeResult = ConstantRange(
5678           APInt::getSignedMinValue(BitWidth),
5679           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5680   }
5681 
5682   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5683     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5684     unsigned WrapType = OBO::AnyWrap;
5685     if (Add->hasNoSignedWrap())
5686       WrapType |= OBO::NoSignedWrap;
5687     if (Add->hasNoUnsignedWrap())
5688       WrapType |= OBO::NoUnsignedWrap;
5689     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5690       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5691                           WrapType, RangeType);
5692     return setRange(Add, SignHint,
5693                     ConservativeResult.intersectWith(X, RangeType));
5694   }
5695 
5696   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5697     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5698     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5699       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5700     return setRange(Mul, SignHint,
5701                     ConservativeResult.intersectWith(X, RangeType));
5702   }
5703 
5704   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5705     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5706     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5707       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5708     return setRange(SMax, SignHint,
5709                     ConservativeResult.intersectWith(X, RangeType));
5710   }
5711 
5712   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5713     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5714     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5715       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5716     return setRange(UMax, SignHint,
5717                     ConservativeResult.intersectWith(X, RangeType));
5718   }
5719 
5720   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5721     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5722     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5723       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5724     return setRange(SMin, SignHint,
5725                     ConservativeResult.intersectWith(X, RangeType));
5726   }
5727 
5728   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5729     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5730     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5731       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5732     return setRange(UMin, SignHint,
5733                     ConservativeResult.intersectWith(X, RangeType));
5734   }
5735 
5736   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5737     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5738     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5739     return setRange(UDiv, SignHint,
5740                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5741   }
5742 
5743   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5744     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5745     return setRange(ZExt, SignHint,
5746                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5747                                                      RangeType));
5748   }
5749 
5750   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5751     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5752     return setRange(SExt, SignHint,
5753                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5754                                                      RangeType));
5755   }
5756 
5757   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5758     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5759     return setRange(PtrToInt, SignHint, X);
5760   }
5761 
5762   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5763     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5764     return setRange(Trunc, SignHint,
5765                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5766                                                      RangeType));
5767   }
5768 
5769   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5770     // If there's no unsigned wrap, the value will never be less than its
5771     // initial value.
5772     if (AddRec->hasNoUnsignedWrap()) {
5773       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5774       if (!UnsignedMinValue.isNullValue())
5775         ConservativeResult = ConservativeResult.intersectWith(
5776             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5777     }
5778 
5779     // If there's no signed wrap, and all the operands except initial value have
5780     // the same sign or zero, the value won't ever be:
5781     // 1: smaller than initial value if operands are non negative,
5782     // 2: bigger than initial value if operands are non positive.
5783     // For both cases, value can not cross signed min/max boundary.
5784     if (AddRec->hasNoSignedWrap()) {
5785       bool AllNonNeg = true;
5786       bool AllNonPos = true;
5787       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5788         if (!isKnownNonNegative(AddRec->getOperand(i)))
5789           AllNonNeg = false;
5790         if (!isKnownNonPositive(AddRec->getOperand(i)))
5791           AllNonPos = false;
5792       }
5793       if (AllNonNeg)
5794         ConservativeResult = ConservativeResult.intersectWith(
5795             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5796                                        APInt::getSignedMinValue(BitWidth)),
5797             RangeType);
5798       else if (AllNonPos)
5799         ConservativeResult = ConservativeResult.intersectWith(
5800             ConstantRange::getNonEmpty(
5801                 APInt::getSignedMinValue(BitWidth),
5802                 getSignedRangeMax(AddRec->getStart()) + 1),
5803             RangeType);
5804     }
5805 
5806     // TODO: non-affine addrec
5807     if (AddRec->isAffine()) {
5808       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5809       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5810           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5811         auto RangeFromAffine = getRangeForAffineAR(
5812             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5813             BitWidth);
5814         ConservativeResult =
5815             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5816 
5817         auto RangeFromFactoring = getRangeViaFactoring(
5818             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5819             BitWidth);
5820         ConservativeResult =
5821             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5822       }
5823 
5824       // Now try symbolic BE count and more powerful methods.
5825       if (UseExpensiveRangeSharpening) {
5826         const SCEV *SymbolicMaxBECount =
5827             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5828         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5829             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5830             AddRec->hasNoSelfWrap()) {
5831           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5832               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5833           ConservativeResult =
5834               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5835         }
5836       }
5837     }
5838 
5839     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5840   }
5841 
5842   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5843     // Check if the IR explicitly contains !range metadata.
5844     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5845     if (MDRange.hasValue())
5846       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5847                                                             RangeType);
5848 
5849     // Split here to avoid paying the compile-time cost of calling both
5850     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5851     // if needed.
5852     const DataLayout &DL = getDataLayout();
5853     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5854       // For a SCEVUnknown, ask ValueTracking.
5855       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5856       if (Known.getBitWidth() != BitWidth)
5857         Known = Known.zextOrTrunc(BitWidth);
5858       // If Known does not result in full-set, intersect with it.
5859       if (Known.getMinValue() != Known.getMaxValue() + 1)
5860         ConservativeResult = ConservativeResult.intersectWith(
5861             ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5862             RangeType);
5863     } else {
5864       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5865              "generalize as needed!");
5866       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5867       // If the pointer size is larger than the index size type, this can cause
5868       // NS to be larger than BitWidth. So compensate for this.
5869       if (U->getType()->isPointerTy()) {
5870         unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5871         int ptrIdxDiff = ptrSize - BitWidth;
5872         if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5873           NS -= ptrIdxDiff;
5874       }
5875 
5876       if (NS > 1)
5877         ConservativeResult = ConservativeResult.intersectWith(
5878             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5879                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5880             RangeType);
5881     }
5882 
5883     // A range of Phi is a subset of union of all ranges of its input.
5884     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5885       // Make sure that we do not run over cycled Phis.
5886       if (PendingPhiRanges.insert(Phi).second) {
5887         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5888         for (auto &Op : Phi->operands()) {
5889           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5890           RangeFromOps = RangeFromOps.unionWith(OpRange);
5891           // No point to continue if we already have a full set.
5892           if (RangeFromOps.isFullSet())
5893             break;
5894         }
5895         ConservativeResult =
5896             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5897         bool Erased = PendingPhiRanges.erase(Phi);
5898         assert(Erased && "Failed to erase Phi properly?");
5899         (void) Erased;
5900       }
5901     }
5902 
5903     return setRange(U, SignHint, std::move(ConservativeResult));
5904   }
5905 
5906   return setRange(S, SignHint, std::move(ConservativeResult));
5907 }
5908 
5909 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5910 // values that the expression can take. Initially, the expression has a value
5911 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5912 // argument defines if we treat Step as signed or unsigned.
5913 static ConstantRange getRangeForAffineARHelper(APInt Step,
5914                                                const ConstantRange &StartRange,
5915                                                const APInt &MaxBECount,
5916                                                unsigned BitWidth, bool Signed) {
5917   // If either Step or MaxBECount is 0, then the expression won't change, and we
5918   // just need to return the initial range.
5919   if (Step == 0 || MaxBECount == 0)
5920     return StartRange;
5921 
5922   // If we don't know anything about the initial value (i.e. StartRange is
5923   // FullRange), then we don't know anything about the final range either.
5924   // Return FullRange.
5925   if (StartRange.isFullSet())
5926     return ConstantRange::getFull(BitWidth);
5927 
5928   // If Step is signed and negative, then we use its absolute value, but we also
5929   // note that we're moving in the opposite direction.
5930   bool Descending = Signed && Step.isNegative();
5931 
5932   if (Signed)
5933     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5934     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5935     // This equations hold true due to the well-defined wrap-around behavior of
5936     // APInt.
5937     Step = Step.abs();
5938 
5939   // Check if Offset is more than full span of BitWidth. If it is, the
5940   // expression is guaranteed to overflow.
5941   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5942     return ConstantRange::getFull(BitWidth);
5943 
5944   // Offset is by how much the expression can change. Checks above guarantee no
5945   // overflow here.
5946   APInt Offset = Step * MaxBECount;
5947 
5948   // Minimum value of the final range will match the minimal value of StartRange
5949   // if the expression is increasing and will be decreased by Offset otherwise.
5950   // Maximum value of the final range will match the maximal value of StartRange
5951   // if the expression is decreasing and will be increased by Offset otherwise.
5952   APInt StartLower = StartRange.getLower();
5953   APInt StartUpper = StartRange.getUpper() - 1;
5954   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5955                                    : (StartUpper + std::move(Offset));
5956 
5957   // It's possible that the new minimum/maximum value will fall into the initial
5958   // range (due to wrap around). This means that the expression can take any
5959   // value in this bitwidth, and we have to return full range.
5960   if (StartRange.contains(MovedBoundary))
5961     return ConstantRange::getFull(BitWidth);
5962 
5963   APInt NewLower =
5964       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5965   APInt NewUpper =
5966       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5967   NewUpper += 1;
5968 
5969   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5970   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5971 }
5972 
5973 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5974                                                    const SCEV *Step,
5975                                                    const SCEV *MaxBECount,
5976                                                    unsigned BitWidth) {
5977   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5978          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5979          "Precondition!");
5980 
5981   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5982   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5983 
5984   // First, consider step signed.
5985   ConstantRange StartSRange = getSignedRange(Start);
5986   ConstantRange StepSRange = getSignedRange(Step);
5987 
5988   // If Step can be both positive and negative, we need to find ranges for the
5989   // maximum absolute step values in both directions and union them.
5990   ConstantRange SR =
5991       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5992                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5993   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5994                                               StartSRange, MaxBECountValue,
5995                                               BitWidth, /* Signed = */ true));
5996 
5997   // Next, consider step unsigned.
5998   ConstantRange UR = getRangeForAffineARHelper(
5999       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6000       MaxBECountValue, BitWidth, /* Signed = */ false);
6001 
6002   // Finally, intersect signed and unsigned ranges.
6003   return SR.intersectWith(UR, ConstantRange::Smallest);
6004 }
6005 
6006 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6007     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6008     ScalarEvolution::RangeSignHint SignHint) {
6009   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6010   assert(AddRec->hasNoSelfWrap() &&
6011          "This only works for non-self-wrapping AddRecs!");
6012   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6013   const SCEV *Step = AddRec->getStepRecurrence(*this);
6014   // Only deal with constant step to save compile time.
6015   if (!isa<SCEVConstant>(Step))
6016     return ConstantRange::getFull(BitWidth);
6017   // Let's make sure that we can prove that we do not self-wrap during
6018   // MaxBECount iterations. We need this because MaxBECount is a maximum
6019   // iteration count estimate, and we might infer nw from some exit for which we
6020   // do not know max exit count (or any other side reasoning).
6021   // TODO: Turn into assert at some point.
6022   if (getTypeSizeInBits(MaxBECount->getType()) >
6023       getTypeSizeInBits(AddRec->getType()))
6024     return ConstantRange::getFull(BitWidth);
6025   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6026   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6027   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6028   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6029   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6030                                          MaxItersWithoutWrap))
6031     return ConstantRange::getFull(BitWidth);
6032 
6033   ICmpInst::Predicate LEPred =
6034       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6035   ICmpInst::Predicate GEPred =
6036       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6037   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6038 
6039   // We know that there is no self-wrap. Let's take Start and End values and
6040   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6041   // the iteration. They either lie inside the range [Min(Start, End),
6042   // Max(Start, End)] or outside it:
6043   //
6044   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6045   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6046   //
6047   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6048   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6049   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6050   // Start <= End and step is positive, or Start >= End and step is negative.
6051   const SCEV *Start = AddRec->getStart();
6052   ConstantRange StartRange = getRangeRef(Start, SignHint);
6053   ConstantRange EndRange = getRangeRef(End, SignHint);
6054   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6055   // If they already cover full iteration space, we will know nothing useful
6056   // even if we prove what we want to prove.
6057   if (RangeBetween.isFullSet())
6058     return RangeBetween;
6059   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6060   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6061                                : RangeBetween.isWrappedSet();
6062   if (IsWrappedSet)
6063     return ConstantRange::getFull(BitWidth);
6064 
6065   if (isKnownPositive(Step) &&
6066       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6067     return RangeBetween;
6068   else if (isKnownNegative(Step) &&
6069            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6070     return RangeBetween;
6071   return ConstantRange::getFull(BitWidth);
6072 }
6073 
6074 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6075                                                     const SCEV *Step,
6076                                                     const SCEV *MaxBECount,
6077                                                     unsigned BitWidth) {
6078   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6079   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6080 
6081   struct SelectPattern {
6082     Value *Condition = nullptr;
6083     APInt TrueValue;
6084     APInt FalseValue;
6085 
6086     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6087                            const SCEV *S) {
6088       Optional<unsigned> CastOp;
6089       APInt Offset(BitWidth, 0);
6090 
6091       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6092              "Should be!");
6093 
6094       // Peel off a constant offset:
6095       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6096         // In the future we could consider being smarter here and handle
6097         // {Start+Step,+,Step} too.
6098         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6099           return;
6100 
6101         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6102         S = SA->getOperand(1);
6103       }
6104 
6105       // Peel off a cast operation
6106       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6107         CastOp = SCast->getSCEVType();
6108         S = SCast->getOperand();
6109       }
6110 
6111       using namespace llvm::PatternMatch;
6112 
6113       auto *SU = dyn_cast<SCEVUnknown>(S);
6114       const APInt *TrueVal, *FalseVal;
6115       if (!SU ||
6116           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6117                                           m_APInt(FalseVal)))) {
6118         Condition = nullptr;
6119         return;
6120       }
6121 
6122       TrueValue = *TrueVal;
6123       FalseValue = *FalseVal;
6124 
6125       // Re-apply the cast we peeled off earlier
6126       if (CastOp.hasValue())
6127         switch (*CastOp) {
6128         default:
6129           llvm_unreachable("Unknown SCEV cast type!");
6130 
6131         case scTruncate:
6132           TrueValue = TrueValue.trunc(BitWidth);
6133           FalseValue = FalseValue.trunc(BitWidth);
6134           break;
6135         case scZeroExtend:
6136           TrueValue = TrueValue.zext(BitWidth);
6137           FalseValue = FalseValue.zext(BitWidth);
6138           break;
6139         case scSignExtend:
6140           TrueValue = TrueValue.sext(BitWidth);
6141           FalseValue = FalseValue.sext(BitWidth);
6142           break;
6143         }
6144 
6145       // Re-apply the constant offset we peeled off earlier
6146       TrueValue += Offset;
6147       FalseValue += Offset;
6148     }
6149 
6150     bool isRecognized() { return Condition != nullptr; }
6151   };
6152 
6153   SelectPattern StartPattern(*this, BitWidth, Start);
6154   if (!StartPattern.isRecognized())
6155     return ConstantRange::getFull(BitWidth);
6156 
6157   SelectPattern StepPattern(*this, BitWidth, Step);
6158   if (!StepPattern.isRecognized())
6159     return ConstantRange::getFull(BitWidth);
6160 
6161   if (StartPattern.Condition != StepPattern.Condition) {
6162     // We don't handle this case today; but we could, by considering four
6163     // possibilities below instead of two. I'm not sure if there are cases where
6164     // that will help over what getRange already does, though.
6165     return ConstantRange::getFull(BitWidth);
6166   }
6167 
6168   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6169   // construct arbitrary general SCEV expressions here.  This function is called
6170   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6171   // say) can end up caching a suboptimal value.
6172 
6173   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6174   // C2352 and C2512 (otherwise it isn't needed).
6175 
6176   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6177   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6178   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6179   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6180 
6181   ConstantRange TrueRange =
6182       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6183   ConstantRange FalseRange =
6184       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6185 
6186   return TrueRange.unionWith(FalseRange);
6187 }
6188 
6189 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6190   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6191   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6192 
6193   // Return early if there are no flags to propagate to the SCEV.
6194   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6195   if (BinOp->hasNoUnsignedWrap())
6196     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6197   if (BinOp->hasNoSignedWrap())
6198     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6199   if (Flags == SCEV::FlagAnyWrap)
6200     return SCEV::FlagAnyWrap;
6201 
6202   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6203 }
6204 
6205 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6206   // Here we check that I is in the header of the innermost loop containing I,
6207   // since we only deal with instructions in the loop header. The actual loop we
6208   // need to check later will come from an add recurrence, but getting that
6209   // requires computing the SCEV of the operands, which can be expensive. This
6210   // check we can do cheaply to rule out some cases early.
6211   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6212   if (InnermostContainingLoop == nullptr ||
6213       InnermostContainingLoop->getHeader() != I->getParent())
6214     return false;
6215 
6216   // Only proceed if we can prove that I does not yield poison.
6217   if (!programUndefinedIfPoison(I))
6218     return false;
6219 
6220   // At this point we know that if I is executed, then it does not wrap
6221   // according to at least one of NSW or NUW. If I is not executed, then we do
6222   // not know if the calculation that I represents would wrap. Multiple
6223   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6224   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6225   // derived from other instructions that map to the same SCEV. We cannot make
6226   // that guarantee for cases where I is not executed. So we need to find the
6227   // loop that I is considered in relation to and prove that I is executed for
6228   // every iteration of that loop. That implies that the value that I
6229   // calculates does not wrap anywhere in the loop, so then we can apply the
6230   // flags to the SCEV.
6231   //
6232   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6233   // from different loops, so that we know which loop to prove that I is
6234   // executed in.
6235   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6236     // I could be an extractvalue from a call to an overflow intrinsic.
6237     // TODO: We can do better here in some cases.
6238     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6239       return false;
6240     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6241     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6242       bool AllOtherOpsLoopInvariant = true;
6243       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6244            ++OtherOpIndex) {
6245         if (OtherOpIndex != OpIndex) {
6246           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6247           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6248             AllOtherOpsLoopInvariant = false;
6249             break;
6250           }
6251         }
6252       }
6253       if (AllOtherOpsLoopInvariant &&
6254           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6255         return true;
6256     }
6257   }
6258   return false;
6259 }
6260 
6261 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6262   // If we know that \c I can never be poison period, then that's enough.
6263   if (isSCEVExprNeverPoison(I))
6264     return true;
6265 
6266   // For an add recurrence specifically, we assume that infinite loops without
6267   // side effects are undefined behavior, and then reason as follows:
6268   //
6269   // If the add recurrence is poison in any iteration, it is poison on all
6270   // future iterations (since incrementing poison yields poison). If the result
6271   // of the add recurrence is fed into the loop latch condition and the loop
6272   // does not contain any throws or exiting blocks other than the latch, we now
6273   // have the ability to "choose" whether the backedge is taken or not (by
6274   // choosing a sufficiently evil value for the poison feeding into the branch)
6275   // for every iteration including and after the one in which \p I first became
6276   // poison.  There are two possibilities (let's call the iteration in which \p
6277   // I first became poison as K):
6278   //
6279   //  1. In the set of iterations including and after K, the loop body executes
6280   //     no side effects.  In this case executing the backege an infinte number
6281   //     of times will yield undefined behavior.
6282   //
6283   //  2. In the set of iterations including and after K, the loop body executes
6284   //     at least one side effect.  In this case, that specific instance of side
6285   //     effect is control dependent on poison, which also yields undefined
6286   //     behavior.
6287 
6288   auto *ExitingBB = L->getExitingBlock();
6289   auto *LatchBB = L->getLoopLatch();
6290   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6291     return false;
6292 
6293   SmallPtrSet<const Instruction *, 16> Pushed;
6294   SmallVector<const Instruction *, 8> PoisonStack;
6295 
6296   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6297   // things that are known to be poison under that assumption go on the
6298   // PoisonStack.
6299   Pushed.insert(I);
6300   PoisonStack.push_back(I);
6301 
6302   bool LatchControlDependentOnPoison = false;
6303   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6304     const Instruction *Poison = PoisonStack.pop_back_val();
6305 
6306     for (auto *PoisonUser : Poison->users()) {
6307       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6308         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6309           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6310       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6311         assert(BI->isConditional() && "Only possibility!");
6312         if (BI->getParent() == LatchBB) {
6313           LatchControlDependentOnPoison = true;
6314           break;
6315         }
6316       }
6317     }
6318   }
6319 
6320   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6321 }
6322 
6323 ScalarEvolution::LoopProperties
6324 ScalarEvolution::getLoopProperties(const Loop *L) {
6325   using LoopProperties = ScalarEvolution::LoopProperties;
6326 
6327   auto Itr = LoopPropertiesCache.find(L);
6328   if (Itr == LoopPropertiesCache.end()) {
6329     auto HasSideEffects = [](Instruction *I) {
6330       if (auto *SI = dyn_cast<StoreInst>(I))
6331         return !SI->isSimple();
6332 
6333       return I->mayHaveSideEffects();
6334     };
6335 
6336     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6337                          /*HasNoSideEffects*/ true};
6338 
6339     for (auto *BB : L->getBlocks())
6340       for (auto &I : *BB) {
6341         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6342           LP.HasNoAbnormalExits = false;
6343         if (HasSideEffects(&I))
6344           LP.HasNoSideEffects = false;
6345         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6346           break; // We're already as pessimistic as we can get.
6347       }
6348 
6349     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6350     assert(InsertPair.second && "We just checked!");
6351     Itr = InsertPair.first;
6352   }
6353 
6354   return Itr->second;
6355 }
6356 
6357 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6358   if (!isSCEVable(V->getType()))
6359     return getUnknown(V);
6360 
6361   if (Instruction *I = dyn_cast<Instruction>(V)) {
6362     // Don't attempt to analyze instructions in blocks that aren't
6363     // reachable. Such instructions don't matter, and they aren't required
6364     // to obey basic rules for definitions dominating uses which this
6365     // analysis depends on.
6366     if (!DT.isReachableFromEntry(I->getParent()))
6367       return getUnknown(UndefValue::get(V->getType()));
6368   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6369     return getConstant(CI);
6370   else if (isa<ConstantPointerNull>(V))
6371     // FIXME: we shouldn't special-case null pointer constant.
6372     return getZero(V->getType());
6373   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6374     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6375   else if (!isa<ConstantExpr>(V))
6376     return getUnknown(V);
6377 
6378   Operator *U = cast<Operator>(V);
6379   if (auto BO = MatchBinaryOp(U, DT)) {
6380     switch (BO->Opcode) {
6381     case Instruction::Add: {
6382       // The simple thing to do would be to just call getSCEV on both operands
6383       // and call getAddExpr with the result. However if we're looking at a
6384       // bunch of things all added together, this can be quite inefficient,
6385       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6386       // Instead, gather up all the operands and make a single getAddExpr call.
6387       // LLVM IR canonical form means we need only traverse the left operands.
6388       SmallVector<const SCEV *, 4> AddOps;
6389       do {
6390         if (BO->Op) {
6391           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6392             AddOps.push_back(OpSCEV);
6393             break;
6394           }
6395 
6396           // If a NUW or NSW flag can be applied to the SCEV for this
6397           // addition, then compute the SCEV for this addition by itself
6398           // with a separate call to getAddExpr. We need to do that
6399           // instead of pushing the operands of the addition onto AddOps,
6400           // since the flags are only known to apply to this particular
6401           // addition - they may not apply to other additions that can be
6402           // formed with operands from AddOps.
6403           const SCEV *RHS = getSCEV(BO->RHS);
6404           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6405           if (Flags != SCEV::FlagAnyWrap) {
6406             const SCEV *LHS = getSCEV(BO->LHS);
6407             if (BO->Opcode == Instruction::Sub)
6408               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6409             else
6410               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6411             break;
6412           }
6413         }
6414 
6415         if (BO->Opcode == Instruction::Sub)
6416           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6417         else
6418           AddOps.push_back(getSCEV(BO->RHS));
6419 
6420         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6421         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6422                        NewBO->Opcode != Instruction::Sub)) {
6423           AddOps.push_back(getSCEV(BO->LHS));
6424           break;
6425         }
6426         BO = NewBO;
6427       } while (true);
6428 
6429       return getAddExpr(AddOps);
6430     }
6431 
6432     case Instruction::Mul: {
6433       SmallVector<const SCEV *, 4> MulOps;
6434       do {
6435         if (BO->Op) {
6436           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6437             MulOps.push_back(OpSCEV);
6438             break;
6439           }
6440 
6441           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6442           if (Flags != SCEV::FlagAnyWrap) {
6443             MulOps.push_back(
6444                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6445             break;
6446           }
6447         }
6448 
6449         MulOps.push_back(getSCEV(BO->RHS));
6450         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6451         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6452           MulOps.push_back(getSCEV(BO->LHS));
6453           break;
6454         }
6455         BO = NewBO;
6456       } while (true);
6457 
6458       return getMulExpr(MulOps);
6459     }
6460     case Instruction::UDiv:
6461       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6462     case Instruction::URem:
6463       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6464     case Instruction::Sub: {
6465       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6466       if (BO->Op)
6467         Flags = getNoWrapFlagsFromUB(BO->Op);
6468       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6469     }
6470     case Instruction::And:
6471       // For an expression like x&255 that merely masks off the high bits,
6472       // use zext(trunc(x)) as the SCEV expression.
6473       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6474         if (CI->isZero())
6475           return getSCEV(BO->RHS);
6476         if (CI->isMinusOne())
6477           return getSCEV(BO->LHS);
6478         const APInt &A = CI->getValue();
6479 
6480         // Instcombine's ShrinkDemandedConstant may strip bits out of
6481         // constants, obscuring what would otherwise be a low-bits mask.
6482         // Use computeKnownBits to compute what ShrinkDemandedConstant
6483         // knew about to reconstruct a low-bits mask value.
6484         unsigned LZ = A.countLeadingZeros();
6485         unsigned TZ = A.countTrailingZeros();
6486         unsigned BitWidth = A.getBitWidth();
6487         KnownBits Known(BitWidth);
6488         computeKnownBits(BO->LHS, Known, getDataLayout(),
6489                          0, &AC, nullptr, &DT);
6490 
6491         APInt EffectiveMask =
6492             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6493         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6494           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6495           const SCEV *LHS = getSCEV(BO->LHS);
6496           const SCEV *ShiftedLHS = nullptr;
6497           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6498             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6499               // For an expression like (x * 8) & 8, simplify the multiply.
6500               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6501               unsigned GCD = std::min(MulZeros, TZ);
6502               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6503               SmallVector<const SCEV*, 4> MulOps;
6504               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6505               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6506               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6507               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6508             }
6509           }
6510           if (!ShiftedLHS)
6511             ShiftedLHS = getUDivExpr(LHS, MulCount);
6512           return getMulExpr(
6513               getZeroExtendExpr(
6514                   getTruncateExpr(ShiftedLHS,
6515                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6516                   BO->LHS->getType()),
6517               MulCount);
6518         }
6519       }
6520       break;
6521 
6522     case Instruction::Or:
6523       // If the RHS of the Or is a constant, we may have something like:
6524       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6525       // optimizations will transparently handle this case.
6526       //
6527       // In order for this transformation to be safe, the LHS must be of the
6528       // form X*(2^n) and the Or constant must be less than 2^n.
6529       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6530         const SCEV *LHS = getSCEV(BO->LHS);
6531         const APInt &CIVal = CI->getValue();
6532         if (GetMinTrailingZeros(LHS) >=
6533             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6534           // Build a plain add SCEV.
6535           return getAddExpr(LHS, getSCEV(CI),
6536                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6537         }
6538       }
6539       break;
6540 
6541     case Instruction::Xor:
6542       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6543         // If the RHS of xor is -1, then this is a not operation.
6544         if (CI->isMinusOne())
6545           return getNotSCEV(getSCEV(BO->LHS));
6546 
6547         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6548         // This is a variant of the check for xor with -1, and it handles
6549         // the case where instcombine has trimmed non-demanded bits out
6550         // of an xor with -1.
6551         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6552           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6553             if (LBO->getOpcode() == Instruction::And &&
6554                 LCI->getValue() == CI->getValue())
6555               if (const SCEVZeroExtendExpr *Z =
6556                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6557                 Type *UTy = BO->LHS->getType();
6558                 const SCEV *Z0 = Z->getOperand();
6559                 Type *Z0Ty = Z0->getType();
6560                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6561 
6562                 // If C is a low-bits mask, the zero extend is serving to
6563                 // mask off the high bits. Complement the operand and
6564                 // re-apply the zext.
6565                 if (CI->getValue().isMask(Z0TySize))
6566                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6567 
6568                 // If C is a single bit, it may be in the sign-bit position
6569                 // before the zero-extend. In this case, represent the xor
6570                 // using an add, which is equivalent, and re-apply the zext.
6571                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6572                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6573                     Trunc.isSignMask())
6574                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6575                                            UTy);
6576               }
6577       }
6578       break;
6579 
6580     case Instruction::Shl:
6581       // Turn shift left of a constant amount into a multiply.
6582       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6583         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6584 
6585         // If the shift count is not less than the bitwidth, the result of
6586         // the shift is undefined. Don't try to analyze it, because the
6587         // resolution chosen here may differ from the resolution chosen in
6588         // other parts of the compiler.
6589         if (SA->getValue().uge(BitWidth))
6590           break;
6591 
6592         // We can safely preserve the nuw flag in all cases. It's also safe to
6593         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6594         // requires special handling. It can be preserved as long as we're not
6595         // left shifting by bitwidth - 1.
6596         auto Flags = SCEV::FlagAnyWrap;
6597         if (BO->Op) {
6598           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6599           if ((MulFlags & SCEV::FlagNSW) &&
6600               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6601             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6602           if (MulFlags & SCEV::FlagNUW)
6603             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6604         }
6605 
6606         Constant *X = ConstantInt::get(
6607             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6608         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6609       }
6610       break;
6611 
6612     case Instruction::AShr: {
6613       // AShr X, C, where C is a constant.
6614       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6615       if (!CI)
6616         break;
6617 
6618       Type *OuterTy = BO->LHS->getType();
6619       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6620       // If the shift count is not less than the bitwidth, the result of
6621       // the shift is undefined. Don't try to analyze it, because the
6622       // resolution chosen here may differ from the resolution chosen in
6623       // other parts of the compiler.
6624       if (CI->getValue().uge(BitWidth))
6625         break;
6626 
6627       if (CI->isZero())
6628         return getSCEV(BO->LHS); // shift by zero --> noop
6629 
6630       uint64_t AShrAmt = CI->getZExtValue();
6631       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6632 
6633       Operator *L = dyn_cast<Operator>(BO->LHS);
6634       if (L && L->getOpcode() == Instruction::Shl) {
6635         // X = Shl A, n
6636         // Y = AShr X, m
6637         // Both n and m are constant.
6638 
6639         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6640         if (L->getOperand(1) == BO->RHS)
6641           // For a two-shift sext-inreg, i.e. n = m,
6642           // use sext(trunc(x)) as the SCEV expression.
6643           return getSignExtendExpr(
6644               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6645 
6646         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6647         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6648           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6649           if (ShlAmt > AShrAmt) {
6650             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6651             // expression. We already checked that ShlAmt < BitWidth, so
6652             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6653             // ShlAmt - AShrAmt < Amt.
6654             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6655                                             ShlAmt - AShrAmt);
6656             return getSignExtendExpr(
6657                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6658                 getConstant(Mul)), OuterTy);
6659           }
6660         }
6661       }
6662       if (BO->IsExact) {
6663         // Given exact arithmetic in-bounds right-shift by a constant,
6664         // we can lower it into:  (abs(x) EXACT/u (1<<C)) * signum(x)
6665         const SCEV *X = getSCEV(BO->LHS);
6666         const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false);
6667         APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt);
6668         const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult));
6669         return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW);
6670       }
6671       break;
6672     }
6673     }
6674   }
6675 
6676   switch (U->getOpcode()) {
6677   case Instruction::Trunc:
6678     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6679 
6680   case Instruction::ZExt:
6681     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6682 
6683   case Instruction::SExt:
6684     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6685       // The NSW flag of a subtract does not always survive the conversion to
6686       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6687       // more likely to preserve NSW and allow later AddRec optimisations.
6688       //
6689       // NOTE: This is effectively duplicating this logic from getSignExtend:
6690       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6691       // but by that point the NSW information has potentially been lost.
6692       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6693         Type *Ty = U->getType();
6694         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6695         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6696         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6697       }
6698     }
6699     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6700 
6701   case Instruction::BitCast:
6702     // BitCasts are no-op casts so we just eliminate the cast.
6703     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6704       return getSCEV(U->getOperand(0));
6705     break;
6706 
6707   case Instruction::PtrToInt: {
6708     // Pointer to integer cast is straight-forward, so do model it.
6709     Value *Ptr = U->getOperand(0);
6710     const SCEV *Op = getSCEV(Ptr);
6711     Type *DstIntTy = U->getType();
6712     // SCEV doesn't have constant pointer expression type, but it supports
6713     // nullptr constant (and only that one), which is modelled in SCEV as a
6714     // zero integer constant. So just skip the ptrtoint cast for constants.
6715     if (isa<SCEVConstant>(Op))
6716       return getTruncateOrZeroExtend(Op, DstIntTy);
6717     Type *PtrTy = Ptr->getType();
6718     Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy);
6719     // But only if effective SCEV (integer) type is wide enough to represent
6720     // all possible pointer values.
6721     if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) !=
6722         getDataLayout().getTypeSizeInBits(IntPtrTy))
6723       return getUnknown(V);
6724     return getPtrToIntExpr(Op, DstIntTy);
6725   }
6726   case Instruction::IntToPtr:
6727     // Just don't deal with inttoptr casts.
6728     return getUnknown(V);
6729 
6730   case Instruction::SDiv:
6731     // If both operands are non-negative, this is just an udiv.
6732     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6733         isKnownNonNegative(getSCEV(U->getOperand(1))))
6734       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6735     break;
6736 
6737   case Instruction::SRem:
6738     // If both operands are non-negative, this is just an urem.
6739     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6740         isKnownNonNegative(getSCEV(U->getOperand(1))))
6741       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6742     break;
6743 
6744   case Instruction::GetElementPtr:
6745     return createNodeForGEP(cast<GEPOperator>(U));
6746 
6747   case Instruction::PHI:
6748     return createNodeForPHI(cast<PHINode>(U));
6749 
6750   case Instruction::Select:
6751     // U can also be a select constant expr, which let fall through.  Since
6752     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6753     // constant expressions cannot have instructions as operands, we'd have
6754     // returned getUnknown for a select constant expressions anyway.
6755     if (isa<Instruction>(U))
6756       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6757                                       U->getOperand(1), U->getOperand(2));
6758     break;
6759 
6760   case Instruction::Call:
6761   case Instruction::Invoke:
6762     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6763       return getSCEV(RV);
6764 
6765     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6766       switch (II->getIntrinsicID()) {
6767       case Intrinsic::abs:
6768         return getAbsExpr(
6769             getSCEV(II->getArgOperand(0)),
6770             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6771       case Intrinsic::umax:
6772         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6773                            getSCEV(II->getArgOperand(1)));
6774       case Intrinsic::umin:
6775         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6776                            getSCEV(II->getArgOperand(1)));
6777       case Intrinsic::smax:
6778         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6779                            getSCEV(II->getArgOperand(1)));
6780       case Intrinsic::smin:
6781         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6782                            getSCEV(II->getArgOperand(1)));
6783       case Intrinsic::usub_sat: {
6784         const SCEV *X = getSCEV(II->getArgOperand(0));
6785         const SCEV *Y = getSCEV(II->getArgOperand(1));
6786         const SCEV *ClampedY = getUMinExpr(X, Y);
6787         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6788       }
6789       case Intrinsic::uadd_sat: {
6790         const SCEV *X = getSCEV(II->getArgOperand(0));
6791         const SCEV *Y = getSCEV(II->getArgOperand(1));
6792         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6793         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6794       }
6795       case Intrinsic::start_loop_iterations:
6796         // A start_loop_iterations is just equivalent to the first operand for
6797         // SCEV purposes.
6798         return getSCEV(II->getArgOperand(0));
6799       default:
6800         break;
6801       }
6802     }
6803     break;
6804   }
6805 
6806   return getUnknown(V);
6807 }
6808 
6809 //===----------------------------------------------------------------------===//
6810 //                   Iteration Count Computation Code
6811 //
6812 
6813 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6814   if (!ExitCount)
6815     return 0;
6816 
6817   ConstantInt *ExitConst = ExitCount->getValue();
6818 
6819   // Guard against huge trip counts.
6820   if (ExitConst->getValue().getActiveBits() > 32)
6821     return 0;
6822 
6823   // In case of integer overflow, this returns 0, which is correct.
6824   return ((unsigned)ExitConst->getZExtValue()) + 1;
6825 }
6826 
6827 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6828   if (BasicBlock *ExitingBB = L->getExitingBlock())
6829     return getSmallConstantTripCount(L, ExitingBB);
6830 
6831   // No trip count information for multiple exits.
6832   return 0;
6833 }
6834 
6835 unsigned
6836 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6837                                            const BasicBlock *ExitingBlock) {
6838   assert(ExitingBlock && "Must pass a non-null exiting block!");
6839   assert(L->isLoopExiting(ExitingBlock) &&
6840          "Exiting block must actually branch out of the loop!");
6841   const SCEVConstant *ExitCount =
6842       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6843   return getConstantTripCount(ExitCount);
6844 }
6845 
6846 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6847   const auto *MaxExitCount =
6848       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6849   return getConstantTripCount(MaxExitCount);
6850 }
6851 
6852 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6853   if (BasicBlock *ExitingBB = L->getExitingBlock())
6854     return getSmallConstantTripMultiple(L, ExitingBB);
6855 
6856   // No trip multiple information for multiple exits.
6857   return 0;
6858 }
6859 
6860 /// Returns the largest constant divisor of the trip count of this loop as a
6861 /// normal unsigned value, if possible. This means that the actual trip count is
6862 /// always a multiple of the returned value (don't forget the trip count could
6863 /// very well be zero as well!).
6864 ///
6865 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6866 /// multiple of a constant (which is also the case if the trip count is simply
6867 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6868 /// if the trip count is very large (>= 2^32).
6869 ///
6870 /// As explained in the comments for getSmallConstantTripCount, this assumes
6871 /// that control exits the loop via ExitingBlock.
6872 unsigned
6873 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6874                                               const BasicBlock *ExitingBlock) {
6875   assert(ExitingBlock && "Must pass a non-null exiting block!");
6876   assert(L->isLoopExiting(ExitingBlock) &&
6877          "Exiting block must actually branch out of the loop!");
6878   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6879   if (ExitCount == getCouldNotCompute())
6880     return 1;
6881 
6882   // Get the trip count from the BE count by adding 1.
6883   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6884 
6885   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6886   if (!TC)
6887     // Attempt to factor more general cases. Returns the greatest power of
6888     // two divisor. If overflow happens, the trip count expression is still
6889     // divisible by the greatest power of 2 divisor returned.
6890     return 1U << std::min((uint32_t)31,
6891                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
6892 
6893   ConstantInt *Result = TC->getValue();
6894 
6895   // Guard against huge trip counts (this requires checking
6896   // for zero to handle the case where the trip count == -1 and the
6897   // addition wraps).
6898   if (!Result || Result->getValue().getActiveBits() > 32 ||
6899       Result->getValue().getActiveBits() == 0)
6900     return 1;
6901 
6902   return (unsigned)Result->getZExtValue();
6903 }
6904 
6905 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6906                                           const BasicBlock *ExitingBlock,
6907                                           ExitCountKind Kind) {
6908   switch (Kind) {
6909   case Exact:
6910   case SymbolicMaximum:
6911     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6912   case ConstantMaximum:
6913     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
6914   };
6915   llvm_unreachable("Invalid ExitCountKind!");
6916 }
6917 
6918 const SCEV *
6919 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6920                                                  SCEVUnionPredicate &Preds) {
6921   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6922 }
6923 
6924 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6925                                                    ExitCountKind Kind) {
6926   switch (Kind) {
6927   case Exact:
6928     return getBackedgeTakenInfo(L).getExact(L, this);
6929   case ConstantMaximum:
6930     return getBackedgeTakenInfo(L).getConstantMax(this);
6931   case SymbolicMaximum:
6932     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
6933   };
6934   llvm_unreachable("Invalid ExitCountKind!");
6935 }
6936 
6937 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6938   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
6939 }
6940 
6941 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6942 static void
6943 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6944   BasicBlock *Header = L->getHeader();
6945 
6946   // Push all Loop-header PHIs onto the Worklist stack.
6947   for (PHINode &PN : Header->phis())
6948     Worklist.push_back(&PN);
6949 }
6950 
6951 const ScalarEvolution::BackedgeTakenInfo &
6952 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6953   auto &BTI = getBackedgeTakenInfo(L);
6954   if (BTI.hasFullInfo())
6955     return BTI;
6956 
6957   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6958 
6959   if (!Pair.second)
6960     return Pair.first->second;
6961 
6962   BackedgeTakenInfo Result =
6963       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6964 
6965   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6966 }
6967 
6968 ScalarEvolution::BackedgeTakenInfo &
6969 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6970   // Initially insert an invalid entry for this loop. If the insertion
6971   // succeeds, proceed to actually compute a backedge-taken count and
6972   // update the value. The temporary CouldNotCompute value tells SCEV
6973   // code elsewhere that it shouldn't attempt to request a new
6974   // backedge-taken count, which could result in infinite recursion.
6975   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6976       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6977   if (!Pair.second)
6978     return Pair.first->second;
6979 
6980   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6981   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6982   // must be cleared in this scope.
6983   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6984 
6985   // In product build, there are no usage of statistic.
6986   (void)NumTripCountsComputed;
6987   (void)NumTripCountsNotComputed;
6988 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6989   const SCEV *BEExact = Result.getExact(L, this);
6990   if (BEExact != getCouldNotCompute()) {
6991     assert(isLoopInvariant(BEExact, L) &&
6992            isLoopInvariant(Result.getConstantMax(this), L) &&
6993            "Computed backedge-taken count isn't loop invariant for loop!");
6994     ++NumTripCountsComputed;
6995   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
6996              isa<PHINode>(L->getHeader()->begin())) {
6997     // Only count loops that have phi nodes as not being computable.
6998     ++NumTripCountsNotComputed;
6999   }
7000 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7001 
7002   // Now that we know more about the trip count for this loop, forget any
7003   // existing SCEV values for PHI nodes in this loop since they are only
7004   // conservative estimates made without the benefit of trip count
7005   // information. This is similar to the code in forgetLoop, except that
7006   // it handles SCEVUnknown PHI nodes specially.
7007   if (Result.hasAnyInfo()) {
7008     SmallVector<Instruction *, 16> Worklist;
7009     PushLoopPHIs(L, Worklist);
7010 
7011     SmallPtrSet<Instruction *, 8> Discovered;
7012     while (!Worklist.empty()) {
7013       Instruction *I = Worklist.pop_back_val();
7014 
7015       ValueExprMapType::iterator It =
7016         ValueExprMap.find_as(static_cast<Value *>(I));
7017       if (It != ValueExprMap.end()) {
7018         const SCEV *Old = It->second;
7019 
7020         // SCEVUnknown for a PHI either means that it has an unrecognized
7021         // structure, or it's a PHI that's in the progress of being computed
7022         // by createNodeForPHI.  In the former case, additional loop trip
7023         // count information isn't going to change anything. In the later
7024         // case, createNodeForPHI will perform the necessary updates on its
7025         // own when it gets to that point.
7026         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7027           eraseValueFromMap(It->first);
7028           forgetMemoizedResults(Old);
7029         }
7030         if (PHINode *PN = dyn_cast<PHINode>(I))
7031           ConstantEvolutionLoopExitValue.erase(PN);
7032       }
7033 
7034       // Since we don't need to invalidate anything for correctness and we're
7035       // only invalidating to make SCEV's results more precise, we get to stop
7036       // early to avoid invalidating too much.  This is especially important in
7037       // cases like:
7038       //
7039       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7040       // loop0:
7041       //   %pn0 = phi
7042       //   ...
7043       // loop1:
7044       //   %pn1 = phi
7045       //   ...
7046       //
7047       // where both loop0 and loop1's backedge taken count uses the SCEV
7048       // expression for %v.  If we don't have the early stop below then in cases
7049       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7050       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7051       // count for loop1, effectively nullifying SCEV's trip count cache.
7052       for (auto *U : I->users())
7053         if (auto *I = dyn_cast<Instruction>(U)) {
7054           auto *LoopForUser = LI.getLoopFor(I->getParent());
7055           if (LoopForUser && L->contains(LoopForUser) &&
7056               Discovered.insert(I).second)
7057             Worklist.push_back(I);
7058         }
7059     }
7060   }
7061 
7062   // Re-lookup the insert position, since the call to
7063   // computeBackedgeTakenCount above could result in a
7064   // recusive call to getBackedgeTakenInfo (on a different
7065   // loop), which would invalidate the iterator computed
7066   // earlier.
7067   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7068 }
7069 
7070 void ScalarEvolution::forgetAllLoops() {
7071   // This method is intended to forget all info about loops. It should
7072   // invalidate caches as if the following happened:
7073   // - The trip counts of all loops have changed arbitrarily
7074   // - Every llvm::Value has been updated in place to produce a different
7075   // result.
7076   BackedgeTakenCounts.clear();
7077   PredicatedBackedgeTakenCounts.clear();
7078   LoopPropertiesCache.clear();
7079   ConstantEvolutionLoopExitValue.clear();
7080   ValueExprMap.clear();
7081   ValuesAtScopes.clear();
7082   LoopDispositions.clear();
7083   BlockDispositions.clear();
7084   UnsignedRanges.clear();
7085   SignedRanges.clear();
7086   ExprValueMap.clear();
7087   HasRecMap.clear();
7088   MinTrailingZerosCache.clear();
7089   PredicatedSCEVRewrites.clear();
7090 }
7091 
7092 void ScalarEvolution::forgetLoop(const Loop *L) {
7093   // Drop any stored trip count value.
7094   auto RemoveLoopFromBackedgeMap =
7095       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
7096         auto BTCPos = Map.find(L);
7097         if (BTCPos != Map.end()) {
7098           BTCPos->second.clear();
7099           Map.erase(BTCPos);
7100         }
7101       };
7102 
7103   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7104   SmallVector<Instruction *, 32> Worklist;
7105   SmallPtrSet<Instruction *, 16> Visited;
7106 
7107   // Iterate over all the loops and sub-loops to drop SCEV information.
7108   while (!LoopWorklist.empty()) {
7109     auto *CurrL = LoopWorklist.pop_back_val();
7110 
7111     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
7112     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
7113 
7114     // Drop information about predicated SCEV rewrites for this loop.
7115     for (auto I = PredicatedSCEVRewrites.begin();
7116          I != PredicatedSCEVRewrites.end();) {
7117       std::pair<const SCEV *, const Loop *> Entry = I->first;
7118       if (Entry.second == CurrL)
7119         PredicatedSCEVRewrites.erase(I++);
7120       else
7121         ++I;
7122     }
7123 
7124     auto LoopUsersItr = LoopUsers.find(CurrL);
7125     if (LoopUsersItr != LoopUsers.end()) {
7126       for (auto *S : LoopUsersItr->second)
7127         forgetMemoizedResults(S);
7128       LoopUsers.erase(LoopUsersItr);
7129     }
7130 
7131     // Drop information about expressions based on loop-header PHIs.
7132     PushLoopPHIs(CurrL, Worklist);
7133 
7134     while (!Worklist.empty()) {
7135       Instruction *I = Worklist.pop_back_val();
7136       if (!Visited.insert(I).second)
7137         continue;
7138 
7139       ValueExprMapType::iterator It =
7140           ValueExprMap.find_as(static_cast<Value *>(I));
7141       if (It != ValueExprMap.end()) {
7142         eraseValueFromMap(It->first);
7143         forgetMemoizedResults(It->second);
7144         if (PHINode *PN = dyn_cast<PHINode>(I))
7145           ConstantEvolutionLoopExitValue.erase(PN);
7146       }
7147 
7148       PushDefUseChildren(I, Worklist);
7149     }
7150 
7151     LoopPropertiesCache.erase(CurrL);
7152     // Forget all contained loops too, to avoid dangling entries in the
7153     // ValuesAtScopes map.
7154     LoopWorklist.append(CurrL->begin(), CurrL->end());
7155   }
7156 }
7157 
7158 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7159   while (Loop *Parent = L->getParentLoop())
7160     L = Parent;
7161   forgetLoop(L);
7162 }
7163 
7164 void ScalarEvolution::forgetValue(Value *V) {
7165   Instruction *I = dyn_cast<Instruction>(V);
7166   if (!I) return;
7167 
7168   // Drop information about expressions based on loop-header PHIs.
7169   SmallVector<Instruction *, 16> Worklist;
7170   Worklist.push_back(I);
7171 
7172   SmallPtrSet<Instruction *, 8> Visited;
7173   while (!Worklist.empty()) {
7174     I = Worklist.pop_back_val();
7175     if (!Visited.insert(I).second)
7176       continue;
7177 
7178     ValueExprMapType::iterator It =
7179       ValueExprMap.find_as(static_cast<Value *>(I));
7180     if (It != ValueExprMap.end()) {
7181       eraseValueFromMap(It->first);
7182       forgetMemoizedResults(It->second);
7183       if (PHINode *PN = dyn_cast<PHINode>(I))
7184         ConstantEvolutionLoopExitValue.erase(PN);
7185     }
7186 
7187     PushDefUseChildren(I, Worklist);
7188   }
7189 }
7190 
7191 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7192   LoopDispositions.clear();
7193 }
7194 
7195 /// Get the exact loop backedge taken count considering all loop exits. A
7196 /// computable result can only be returned for loops with all exiting blocks
7197 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7198 /// is never skipped. This is a valid assumption as long as the loop exits via
7199 /// that test. For precise results, it is the caller's responsibility to specify
7200 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7201 const SCEV *
7202 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7203                                              SCEVUnionPredicate *Preds) const {
7204   // If any exits were not computable, the loop is not computable.
7205   if (!isComplete() || ExitNotTaken.empty())
7206     return SE->getCouldNotCompute();
7207 
7208   const BasicBlock *Latch = L->getLoopLatch();
7209   // All exiting blocks we have collected must dominate the only backedge.
7210   if (!Latch)
7211     return SE->getCouldNotCompute();
7212 
7213   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7214   // count is simply a minimum out of all these calculated exit counts.
7215   SmallVector<const SCEV *, 2> Ops;
7216   for (auto &ENT : ExitNotTaken) {
7217     const SCEV *BECount = ENT.ExactNotTaken;
7218     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7219     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7220            "We should only have known counts for exiting blocks that dominate "
7221            "latch!");
7222 
7223     Ops.push_back(BECount);
7224 
7225     if (Preds && !ENT.hasAlwaysTruePredicate())
7226       Preds->add(ENT.Predicate.get());
7227 
7228     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7229            "Predicate should be always true!");
7230   }
7231 
7232   return SE->getUMinFromMismatchedTypes(Ops);
7233 }
7234 
7235 /// Get the exact not taken count for this loop exit.
7236 const SCEV *
7237 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7238                                              ScalarEvolution *SE) const {
7239   for (auto &ENT : ExitNotTaken)
7240     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7241       return ENT.ExactNotTaken;
7242 
7243   return SE->getCouldNotCompute();
7244 }
7245 
7246 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7247     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7248   for (auto &ENT : ExitNotTaken)
7249     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7250       return ENT.MaxNotTaken;
7251 
7252   return SE->getCouldNotCompute();
7253 }
7254 
7255 /// getConstantMax - Get the constant max backedge taken count for the loop.
7256 const SCEV *
7257 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7258   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7259     return !ENT.hasAlwaysTruePredicate();
7260   };
7261 
7262   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7263     return SE->getCouldNotCompute();
7264 
7265   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7266           isa<SCEVConstant>(getConstantMax())) &&
7267          "No point in having a non-constant max backedge taken count!");
7268   return getConstantMax();
7269 }
7270 
7271 const SCEV *
7272 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7273                                                    ScalarEvolution *SE) {
7274   if (!SymbolicMax)
7275     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7276   return SymbolicMax;
7277 }
7278 
7279 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7280     ScalarEvolution *SE) const {
7281   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7282     return !ENT.hasAlwaysTruePredicate();
7283   };
7284   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7285 }
7286 
7287 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7288                                                     ScalarEvolution *SE) const {
7289   if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7290       SE->hasOperand(getConstantMax(), S))
7291     return true;
7292 
7293   for (auto &ENT : ExitNotTaken)
7294     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7295         SE->hasOperand(ENT.ExactNotTaken, S))
7296       return true;
7297 
7298   return false;
7299 }
7300 
7301 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7302     : ExactNotTaken(E), MaxNotTaken(E) {
7303   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7304           isa<SCEVConstant>(MaxNotTaken)) &&
7305          "No point in having a non-constant max backedge taken count!");
7306 }
7307 
7308 ScalarEvolution::ExitLimit::ExitLimit(
7309     const SCEV *E, const SCEV *M, bool MaxOrZero,
7310     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7311     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7312   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7313           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7314          "Exact is not allowed to be less precise than Max");
7315   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7316           isa<SCEVConstant>(MaxNotTaken)) &&
7317          "No point in having a non-constant max backedge taken count!");
7318   for (auto *PredSet : PredSetList)
7319     for (auto *P : *PredSet)
7320       addPredicate(P);
7321 }
7322 
7323 ScalarEvolution::ExitLimit::ExitLimit(
7324     const SCEV *E, const SCEV *M, bool MaxOrZero,
7325     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7326     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7327   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7328           isa<SCEVConstant>(MaxNotTaken)) &&
7329          "No point in having a non-constant max backedge taken count!");
7330 }
7331 
7332 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7333                                       bool MaxOrZero)
7334     : ExitLimit(E, M, MaxOrZero, None) {
7335   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7336           isa<SCEVConstant>(MaxNotTaken)) &&
7337          "No point in having a non-constant max backedge taken count!");
7338 }
7339 
7340 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7341 /// computable exit into a persistent ExitNotTakenInfo array.
7342 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7343     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7344     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7345     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7346   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7347 
7348   ExitNotTaken.reserve(ExitCounts.size());
7349   std::transform(
7350       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7351       [&](const EdgeExitInfo &EEI) {
7352         BasicBlock *ExitBB = EEI.first;
7353         const ExitLimit &EL = EEI.second;
7354         if (EL.Predicates.empty())
7355           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7356                                   nullptr);
7357 
7358         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7359         for (auto *Pred : EL.Predicates)
7360           Predicate->add(Pred);
7361 
7362         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7363                                 std::move(Predicate));
7364       });
7365   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7366           isa<SCEVConstant>(ConstantMax)) &&
7367          "No point in having a non-constant max backedge taken count!");
7368 }
7369 
7370 /// Invalidate this result and free the ExitNotTakenInfo array.
7371 void ScalarEvolution::BackedgeTakenInfo::clear() {
7372   ExitNotTaken.clear();
7373 }
7374 
7375 /// Compute the number of times the backedge of the specified loop will execute.
7376 ScalarEvolution::BackedgeTakenInfo
7377 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7378                                            bool AllowPredicates) {
7379   SmallVector<BasicBlock *, 8> ExitingBlocks;
7380   L->getExitingBlocks(ExitingBlocks);
7381 
7382   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7383 
7384   SmallVector<EdgeExitInfo, 4> ExitCounts;
7385   bool CouldComputeBECount = true;
7386   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7387   const SCEV *MustExitMaxBECount = nullptr;
7388   const SCEV *MayExitMaxBECount = nullptr;
7389   bool MustExitMaxOrZero = false;
7390 
7391   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7392   // and compute maxBECount.
7393   // Do a union of all the predicates here.
7394   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7395     BasicBlock *ExitBB = ExitingBlocks[i];
7396 
7397     // We canonicalize untaken exits to br (constant), ignore them so that
7398     // proving an exit untaken doesn't negatively impact our ability to reason
7399     // about the loop as whole.
7400     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7401       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7402         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7403         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7404           continue;
7405       }
7406 
7407     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7408 
7409     assert((AllowPredicates || EL.Predicates.empty()) &&
7410            "Predicated exit limit when predicates are not allowed!");
7411 
7412     // 1. For each exit that can be computed, add an entry to ExitCounts.
7413     // CouldComputeBECount is true only if all exits can be computed.
7414     if (EL.ExactNotTaken == getCouldNotCompute())
7415       // We couldn't compute an exact value for this exit, so
7416       // we won't be able to compute an exact value for the loop.
7417       CouldComputeBECount = false;
7418     else
7419       ExitCounts.emplace_back(ExitBB, EL);
7420 
7421     // 2. Derive the loop's MaxBECount from each exit's max number of
7422     // non-exiting iterations. Partition the loop exits into two kinds:
7423     // LoopMustExits and LoopMayExits.
7424     //
7425     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7426     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7427     // MaxBECount is the minimum EL.MaxNotTaken of computable
7428     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7429     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7430     // computable EL.MaxNotTaken.
7431     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7432         DT.dominates(ExitBB, Latch)) {
7433       if (!MustExitMaxBECount) {
7434         MustExitMaxBECount = EL.MaxNotTaken;
7435         MustExitMaxOrZero = EL.MaxOrZero;
7436       } else {
7437         MustExitMaxBECount =
7438             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7439       }
7440     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7441       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7442         MayExitMaxBECount = EL.MaxNotTaken;
7443       else {
7444         MayExitMaxBECount =
7445             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7446       }
7447     }
7448   }
7449   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7450     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7451   // The loop backedge will be taken the maximum or zero times if there's
7452   // a single exit that must be taken the maximum or zero times.
7453   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7454   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7455                            MaxBECount, MaxOrZero);
7456 }
7457 
7458 ScalarEvolution::ExitLimit
7459 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7460                                       bool AllowPredicates) {
7461   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7462   // If our exiting block does not dominate the latch, then its connection with
7463   // loop's exit limit may be far from trivial.
7464   const BasicBlock *Latch = L->getLoopLatch();
7465   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7466     return getCouldNotCompute();
7467 
7468   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7469   Instruction *Term = ExitingBlock->getTerminator();
7470   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7471     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7472     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7473     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7474            "It should have one successor in loop and one exit block!");
7475     // Proceed to the next level to examine the exit condition expression.
7476     return computeExitLimitFromCond(
7477         L, BI->getCondition(), ExitIfTrue,
7478         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7479   }
7480 
7481   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7482     // For switch, make sure that there is a single exit from the loop.
7483     BasicBlock *Exit = nullptr;
7484     for (auto *SBB : successors(ExitingBlock))
7485       if (!L->contains(SBB)) {
7486         if (Exit) // Multiple exit successors.
7487           return getCouldNotCompute();
7488         Exit = SBB;
7489       }
7490     assert(Exit && "Exiting block must have at least one exit");
7491     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7492                                                 /*ControlsExit=*/IsOnlyExit);
7493   }
7494 
7495   return getCouldNotCompute();
7496 }
7497 
7498 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7499     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7500     bool ControlsExit, bool AllowPredicates) {
7501   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7502   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7503                                         ControlsExit, AllowPredicates);
7504 }
7505 
7506 Optional<ScalarEvolution::ExitLimit>
7507 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7508                                       bool ExitIfTrue, bool ControlsExit,
7509                                       bool AllowPredicates) {
7510   (void)this->L;
7511   (void)this->ExitIfTrue;
7512   (void)this->AllowPredicates;
7513 
7514   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7515          this->AllowPredicates == AllowPredicates &&
7516          "Variance in assumed invariant key components!");
7517   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7518   if (Itr == TripCountMap.end())
7519     return None;
7520   return Itr->second;
7521 }
7522 
7523 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7524                                              bool ExitIfTrue,
7525                                              bool ControlsExit,
7526                                              bool AllowPredicates,
7527                                              const ExitLimit &EL) {
7528   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7529          this->AllowPredicates == AllowPredicates &&
7530          "Variance in assumed invariant key components!");
7531 
7532   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7533   assert(InsertResult.second && "Expected successful insertion!");
7534   (void)InsertResult;
7535   (void)ExitIfTrue;
7536 }
7537 
7538 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7539     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7540     bool ControlsExit, bool AllowPredicates) {
7541 
7542   if (auto MaybeEL =
7543           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7544     return *MaybeEL;
7545 
7546   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7547                                               ControlsExit, AllowPredicates);
7548   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7549   return EL;
7550 }
7551 
7552 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7553     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7554     bool ControlsExit, bool AllowPredicates) {
7555   // Handle BinOp conditions (And, Or).
7556   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7557           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7558     return *LimitFromBinOp;
7559 
7560   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7561   // Proceed to the next level to examine the icmp.
7562   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7563     ExitLimit EL =
7564         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7565     if (EL.hasFullInfo() || !AllowPredicates)
7566       return EL;
7567 
7568     // Try again, but use SCEV predicates this time.
7569     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7570                                     /*AllowPredicates=*/true);
7571   }
7572 
7573   // Check for a constant condition. These are normally stripped out by
7574   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7575   // preserve the CFG and is temporarily leaving constant conditions
7576   // in place.
7577   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7578     if (ExitIfTrue == !CI->getZExtValue())
7579       // The backedge is always taken.
7580       return getCouldNotCompute();
7581     else
7582       // The backedge is never taken.
7583       return getZero(CI->getType());
7584   }
7585 
7586   // If it's not an integer or pointer comparison then compute it the hard way.
7587   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7588 }
7589 
7590 Optional<ScalarEvolution::ExitLimit>
7591 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7592     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7593     bool ControlsExit, bool AllowPredicates) {
7594   // Check if the controlling expression for this loop is an And or Or.
7595   Value *Op0, *Op1;
7596   bool IsAnd = false;
7597   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7598     IsAnd = true;
7599   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7600     IsAnd = false;
7601   else
7602     return None;
7603 
7604   // EitherMayExit is true in these two cases:
7605   //   br (and Op0 Op1), loop, exit
7606   //   br (or  Op0 Op1), exit, loop
7607   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7608   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7609                                                  ControlsExit && !EitherMayExit,
7610                                                  AllowPredicates);
7611   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7612                                                  ControlsExit && !EitherMayExit,
7613                                                  AllowPredicates);
7614 
7615   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7616   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7617   if (isa<ConstantInt>(Op1))
7618     return Op1 == NeutralElement ? EL0 : EL1;
7619   if (isa<ConstantInt>(Op0))
7620     return Op0 == NeutralElement ? EL1 : EL0;
7621 
7622   const SCEV *BECount = getCouldNotCompute();
7623   const SCEV *MaxBECount = getCouldNotCompute();
7624   if (EitherMayExit) {
7625     // Both conditions must be same for the loop to continue executing.
7626     // Choose the less conservative count.
7627     // If ExitCond is a short-circuit form (select), using
7628     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7629     // To see the detailed examples, please see
7630     // test/Analysis/ScalarEvolution/exit-count-select.ll
7631     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7632     if (!PoisonSafe)
7633       // Even if ExitCond is select, we can safely derive BECount using both
7634       // EL0 and EL1 in these cases:
7635       // (1) EL0.ExactNotTaken is non-zero
7636       // (2) EL1.ExactNotTaken is non-poison
7637       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7638       //     it cannot be umin(0, ..))
7639       // The PoisonSafe assignment below is simplified and the assertion after
7640       // BECount calculation fully guarantees the condition (3).
7641       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7642                    isa<SCEVConstant>(EL1.ExactNotTaken);
7643     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7644         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7645       BECount =
7646           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7647 
7648       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7649       // it should have been simplified to zero (see the condition (3) above)
7650       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7651              BECount->isZero());
7652     }
7653     if (EL0.MaxNotTaken == getCouldNotCompute())
7654       MaxBECount = EL1.MaxNotTaken;
7655     else if (EL1.MaxNotTaken == getCouldNotCompute())
7656       MaxBECount = EL0.MaxNotTaken;
7657     else
7658       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7659   } else {
7660     // Both conditions must be same at the same time for the loop to exit.
7661     // For now, be conservative.
7662     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7663       BECount = EL0.ExactNotTaken;
7664   }
7665 
7666   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7667   // to be more aggressive when computing BECount than when computing
7668   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7669   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7670   // to not.
7671   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7672       !isa<SCEVCouldNotCompute>(BECount))
7673     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7674 
7675   return ExitLimit(BECount, MaxBECount, false,
7676                    { &EL0.Predicates, &EL1.Predicates });
7677 }
7678 
7679 ScalarEvolution::ExitLimit
7680 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7681                                           ICmpInst *ExitCond,
7682                                           bool ExitIfTrue,
7683                                           bool ControlsExit,
7684                                           bool AllowPredicates) {
7685   // If the condition was exit on true, convert the condition to exit on false
7686   ICmpInst::Predicate Pred;
7687   if (!ExitIfTrue)
7688     Pred = ExitCond->getPredicate();
7689   else
7690     Pred = ExitCond->getInversePredicate();
7691   const ICmpInst::Predicate OriginalPred = Pred;
7692 
7693   // Handle common loops like: for (X = "string"; *X; ++X)
7694   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7695     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7696       ExitLimit ItCnt =
7697         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7698       if (ItCnt.hasAnyInfo())
7699         return ItCnt;
7700     }
7701 
7702   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7703   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7704 
7705   // Try to evaluate any dependencies out of the loop.
7706   LHS = getSCEVAtScope(LHS, L);
7707   RHS = getSCEVAtScope(RHS, L);
7708 
7709   // At this point, we would like to compute how many iterations of the
7710   // loop the predicate will return true for these inputs.
7711   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7712     // If there is a loop-invariant, force it into the RHS.
7713     std::swap(LHS, RHS);
7714     Pred = ICmpInst::getSwappedPredicate(Pred);
7715   }
7716 
7717   // Simplify the operands before analyzing them.
7718   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7719 
7720   // If we have a comparison of a chrec against a constant, try to use value
7721   // ranges to answer this query.
7722   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7723     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7724       if (AddRec->getLoop() == L) {
7725         // Form the constant range.
7726         ConstantRange CompRange =
7727             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7728 
7729         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7730         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7731       }
7732 
7733   switch (Pred) {
7734   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7735     // Convert to: while (X-Y != 0)
7736     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7737                                 AllowPredicates);
7738     if (EL.hasAnyInfo()) return EL;
7739     break;
7740   }
7741   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7742     // Convert to: while (X-Y == 0)
7743     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7744     if (EL.hasAnyInfo()) return EL;
7745     break;
7746   }
7747   case ICmpInst::ICMP_SLT:
7748   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7749     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7750     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7751                                     AllowPredicates);
7752     if (EL.hasAnyInfo()) return EL;
7753     break;
7754   }
7755   case ICmpInst::ICMP_SGT:
7756   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7757     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7758     ExitLimit EL =
7759         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7760                             AllowPredicates);
7761     if (EL.hasAnyInfo()) return EL;
7762     break;
7763   }
7764   default:
7765     break;
7766   }
7767 
7768   auto *ExhaustiveCount =
7769       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7770 
7771   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7772     return ExhaustiveCount;
7773 
7774   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7775                                       ExitCond->getOperand(1), L, OriginalPred);
7776 }
7777 
7778 ScalarEvolution::ExitLimit
7779 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7780                                                       SwitchInst *Switch,
7781                                                       BasicBlock *ExitingBlock,
7782                                                       bool ControlsExit) {
7783   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7784 
7785   // Give up if the exit is the default dest of a switch.
7786   if (Switch->getDefaultDest() == ExitingBlock)
7787     return getCouldNotCompute();
7788 
7789   assert(L->contains(Switch->getDefaultDest()) &&
7790          "Default case must not exit the loop!");
7791   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7792   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7793 
7794   // while (X != Y) --> while (X-Y != 0)
7795   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7796   if (EL.hasAnyInfo())
7797     return EL;
7798 
7799   return getCouldNotCompute();
7800 }
7801 
7802 static ConstantInt *
7803 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7804                                 ScalarEvolution &SE) {
7805   const SCEV *InVal = SE.getConstant(C);
7806   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7807   assert(isa<SCEVConstant>(Val) &&
7808          "Evaluation of SCEV at constant didn't fold correctly?");
7809   return cast<SCEVConstant>(Val)->getValue();
7810 }
7811 
7812 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7813 /// compute the backedge execution count.
7814 ScalarEvolution::ExitLimit
7815 ScalarEvolution::computeLoadConstantCompareExitLimit(
7816   LoadInst *LI,
7817   Constant *RHS,
7818   const Loop *L,
7819   ICmpInst::Predicate predicate) {
7820   if (LI->isVolatile()) return getCouldNotCompute();
7821 
7822   // Check to see if the loaded pointer is a getelementptr of a global.
7823   // TODO: Use SCEV instead of manually grubbing with GEPs.
7824   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7825   if (!GEP) return getCouldNotCompute();
7826 
7827   // Make sure that it is really a constant global we are gepping, with an
7828   // initializer, and make sure the first IDX is really 0.
7829   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7830   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7831       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7832       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7833     return getCouldNotCompute();
7834 
7835   // Okay, we allow one non-constant index into the GEP instruction.
7836   Value *VarIdx = nullptr;
7837   std::vector<Constant*> Indexes;
7838   unsigned VarIdxNum = 0;
7839   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7840     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7841       Indexes.push_back(CI);
7842     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7843       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7844       VarIdx = GEP->getOperand(i);
7845       VarIdxNum = i-2;
7846       Indexes.push_back(nullptr);
7847     }
7848 
7849   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7850   if (!VarIdx)
7851     return getCouldNotCompute();
7852 
7853   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7854   // Check to see if X is a loop variant variable value now.
7855   const SCEV *Idx = getSCEV(VarIdx);
7856   Idx = getSCEVAtScope(Idx, L);
7857 
7858   // We can only recognize very limited forms of loop index expressions, in
7859   // particular, only affine AddRec's like {C1,+,C2}<L>.
7860   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7861   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
7862       isLoopInvariant(IdxExpr, L) ||
7863       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7864       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7865     return getCouldNotCompute();
7866 
7867   unsigned MaxSteps = MaxBruteForceIterations;
7868   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7869     ConstantInt *ItCst = ConstantInt::get(
7870                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7871     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7872 
7873     // Form the GEP offset.
7874     Indexes[VarIdxNum] = Val;
7875 
7876     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7877                                                          Indexes);
7878     if (!Result) break;  // Cannot compute!
7879 
7880     // Evaluate the condition for this iteration.
7881     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7882     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7883     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7884       ++NumArrayLenItCounts;
7885       return getConstant(ItCst);   // Found terminating iteration!
7886     }
7887   }
7888   return getCouldNotCompute();
7889 }
7890 
7891 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7892     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7893   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7894   if (!RHS)
7895     return getCouldNotCompute();
7896 
7897   const BasicBlock *Latch = L->getLoopLatch();
7898   if (!Latch)
7899     return getCouldNotCompute();
7900 
7901   const BasicBlock *Predecessor = L->getLoopPredecessor();
7902   if (!Predecessor)
7903     return getCouldNotCompute();
7904 
7905   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7906   // Return LHS in OutLHS and shift_opt in OutOpCode.
7907   auto MatchPositiveShift =
7908       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7909 
7910     using namespace PatternMatch;
7911 
7912     ConstantInt *ShiftAmt;
7913     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7914       OutOpCode = Instruction::LShr;
7915     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7916       OutOpCode = Instruction::AShr;
7917     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7918       OutOpCode = Instruction::Shl;
7919     else
7920       return false;
7921 
7922     return ShiftAmt->getValue().isStrictlyPositive();
7923   };
7924 
7925   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7926   //
7927   // loop:
7928   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7929   //   %iv.shifted = lshr i32 %iv, <positive constant>
7930   //
7931   // Return true on a successful match.  Return the corresponding PHI node (%iv
7932   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7933   auto MatchShiftRecurrence =
7934       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7935     Optional<Instruction::BinaryOps> PostShiftOpCode;
7936 
7937     {
7938       Instruction::BinaryOps OpC;
7939       Value *V;
7940 
7941       // If we encounter a shift instruction, "peel off" the shift operation,
7942       // and remember that we did so.  Later when we inspect %iv's backedge
7943       // value, we will make sure that the backedge value uses the same
7944       // operation.
7945       //
7946       // Note: the peeled shift operation does not have to be the same
7947       // instruction as the one feeding into the PHI's backedge value.  We only
7948       // really care about it being the same *kind* of shift instruction --
7949       // that's all that is required for our later inferences to hold.
7950       if (MatchPositiveShift(LHS, V, OpC)) {
7951         PostShiftOpCode = OpC;
7952         LHS = V;
7953       }
7954     }
7955 
7956     PNOut = dyn_cast<PHINode>(LHS);
7957     if (!PNOut || PNOut->getParent() != L->getHeader())
7958       return false;
7959 
7960     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7961     Value *OpLHS;
7962 
7963     return
7964         // The backedge value for the PHI node must be a shift by a positive
7965         // amount
7966         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7967 
7968         // of the PHI node itself
7969         OpLHS == PNOut &&
7970 
7971         // and the kind of shift should be match the kind of shift we peeled
7972         // off, if any.
7973         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7974   };
7975 
7976   PHINode *PN;
7977   Instruction::BinaryOps OpCode;
7978   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7979     return getCouldNotCompute();
7980 
7981   const DataLayout &DL = getDataLayout();
7982 
7983   // The key rationale for this optimization is that for some kinds of shift
7984   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7985   // within a finite number of iterations.  If the condition guarding the
7986   // backedge (in the sense that the backedge is taken if the condition is true)
7987   // is false for the value the shift recurrence stabilizes to, then we know
7988   // that the backedge is taken only a finite number of times.
7989 
7990   ConstantInt *StableValue = nullptr;
7991   switch (OpCode) {
7992   default:
7993     llvm_unreachable("Impossible case!");
7994 
7995   case Instruction::AShr: {
7996     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7997     // bitwidth(K) iterations.
7998     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7999     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
8000                                        Predecessor->getTerminator(), &DT);
8001     auto *Ty = cast<IntegerType>(RHS->getType());
8002     if (Known.isNonNegative())
8003       StableValue = ConstantInt::get(Ty, 0);
8004     else if (Known.isNegative())
8005       StableValue = ConstantInt::get(Ty, -1, true);
8006     else
8007       return getCouldNotCompute();
8008 
8009     break;
8010   }
8011   case Instruction::LShr:
8012   case Instruction::Shl:
8013     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8014     // stabilize to 0 in at most bitwidth(K) iterations.
8015     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8016     break;
8017   }
8018 
8019   auto *Result =
8020       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8021   assert(Result->getType()->isIntegerTy(1) &&
8022          "Otherwise cannot be an operand to a branch instruction");
8023 
8024   if (Result->isZeroValue()) {
8025     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8026     const SCEV *UpperBound =
8027         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8028     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8029   }
8030 
8031   return getCouldNotCompute();
8032 }
8033 
8034 /// Return true if we can constant fold an instruction of the specified type,
8035 /// assuming that all operands were constants.
8036 static bool CanConstantFold(const Instruction *I) {
8037   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8038       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8039       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8040     return true;
8041 
8042   if (const CallInst *CI = dyn_cast<CallInst>(I))
8043     if (const Function *F = CI->getCalledFunction())
8044       return canConstantFoldCallTo(CI, F);
8045   return false;
8046 }
8047 
8048 /// Determine whether this instruction can constant evolve within this loop
8049 /// assuming its operands can all constant evolve.
8050 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8051   // An instruction outside of the loop can't be derived from a loop PHI.
8052   if (!L->contains(I)) return false;
8053 
8054   if (isa<PHINode>(I)) {
8055     // We don't currently keep track of the control flow needed to evaluate
8056     // PHIs, so we cannot handle PHIs inside of loops.
8057     return L->getHeader() == I->getParent();
8058   }
8059 
8060   // If we won't be able to constant fold this expression even if the operands
8061   // are constants, bail early.
8062   return CanConstantFold(I);
8063 }
8064 
8065 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8066 /// recursing through each instruction operand until reaching a loop header phi.
8067 static PHINode *
8068 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8069                                DenseMap<Instruction *, PHINode *> &PHIMap,
8070                                unsigned Depth) {
8071   if (Depth > MaxConstantEvolvingDepth)
8072     return nullptr;
8073 
8074   // Otherwise, we can evaluate this instruction if all of its operands are
8075   // constant or derived from a PHI node themselves.
8076   PHINode *PHI = nullptr;
8077   for (Value *Op : UseInst->operands()) {
8078     if (isa<Constant>(Op)) continue;
8079 
8080     Instruction *OpInst = dyn_cast<Instruction>(Op);
8081     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8082 
8083     PHINode *P = dyn_cast<PHINode>(OpInst);
8084     if (!P)
8085       // If this operand is already visited, reuse the prior result.
8086       // We may have P != PHI if this is the deepest point at which the
8087       // inconsistent paths meet.
8088       P = PHIMap.lookup(OpInst);
8089     if (!P) {
8090       // Recurse and memoize the results, whether a phi is found or not.
8091       // This recursive call invalidates pointers into PHIMap.
8092       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8093       PHIMap[OpInst] = P;
8094     }
8095     if (!P)
8096       return nullptr;  // Not evolving from PHI
8097     if (PHI && PHI != P)
8098       return nullptr;  // Evolving from multiple different PHIs.
8099     PHI = P;
8100   }
8101   // This is a expression evolving from a constant PHI!
8102   return PHI;
8103 }
8104 
8105 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8106 /// in the loop that V is derived from.  We allow arbitrary operations along the
8107 /// way, but the operands of an operation must either be constants or a value
8108 /// derived from a constant PHI.  If this expression does not fit with these
8109 /// constraints, return null.
8110 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8111   Instruction *I = dyn_cast<Instruction>(V);
8112   if (!I || !canConstantEvolve(I, L)) return nullptr;
8113 
8114   if (PHINode *PN = dyn_cast<PHINode>(I))
8115     return PN;
8116 
8117   // Record non-constant instructions contained by the loop.
8118   DenseMap<Instruction *, PHINode *> PHIMap;
8119   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8120 }
8121 
8122 /// EvaluateExpression - Given an expression that passes the
8123 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8124 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8125 /// reason, return null.
8126 static Constant *EvaluateExpression(Value *V, const Loop *L,
8127                                     DenseMap<Instruction *, Constant *> &Vals,
8128                                     const DataLayout &DL,
8129                                     const TargetLibraryInfo *TLI) {
8130   // Convenient constant check, but redundant for recursive calls.
8131   if (Constant *C = dyn_cast<Constant>(V)) return C;
8132   Instruction *I = dyn_cast<Instruction>(V);
8133   if (!I) return nullptr;
8134 
8135   if (Constant *C = Vals.lookup(I)) return C;
8136 
8137   // An instruction inside the loop depends on a value outside the loop that we
8138   // weren't given a mapping for, or a value such as a call inside the loop.
8139   if (!canConstantEvolve(I, L)) return nullptr;
8140 
8141   // An unmapped PHI can be due to a branch or another loop inside this loop,
8142   // or due to this not being the initial iteration through a loop where we
8143   // couldn't compute the evolution of this particular PHI last time.
8144   if (isa<PHINode>(I)) return nullptr;
8145 
8146   std::vector<Constant*> Operands(I->getNumOperands());
8147 
8148   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8149     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8150     if (!Operand) {
8151       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8152       if (!Operands[i]) return nullptr;
8153       continue;
8154     }
8155     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8156     Vals[Operand] = C;
8157     if (!C) return nullptr;
8158     Operands[i] = C;
8159   }
8160 
8161   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8162     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8163                                            Operands[1], DL, TLI);
8164   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8165     if (!LI->isVolatile())
8166       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8167   }
8168   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8169 }
8170 
8171 
8172 // If every incoming value to PN except the one for BB is a specific Constant,
8173 // return that, else return nullptr.
8174 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8175   Constant *IncomingVal = nullptr;
8176 
8177   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8178     if (PN->getIncomingBlock(i) == BB)
8179       continue;
8180 
8181     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8182     if (!CurrentVal)
8183       return nullptr;
8184 
8185     if (IncomingVal != CurrentVal) {
8186       if (IncomingVal)
8187         return nullptr;
8188       IncomingVal = CurrentVal;
8189     }
8190   }
8191 
8192   return IncomingVal;
8193 }
8194 
8195 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8196 /// in the header of its containing loop, we know the loop executes a
8197 /// constant number of times, and the PHI node is just a recurrence
8198 /// involving constants, fold it.
8199 Constant *
8200 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8201                                                    const APInt &BEs,
8202                                                    const Loop *L) {
8203   auto I = ConstantEvolutionLoopExitValue.find(PN);
8204   if (I != ConstantEvolutionLoopExitValue.end())
8205     return I->second;
8206 
8207   if (BEs.ugt(MaxBruteForceIterations))
8208     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8209 
8210   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8211 
8212   DenseMap<Instruction *, Constant *> CurrentIterVals;
8213   BasicBlock *Header = L->getHeader();
8214   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8215 
8216   BasicBlock *Latch = L->getLoopLatch();
8217   if (!Latch)
8218     return nullptr;
8219 
8220   for (PHINode &PHI : Header->phis()) {
8221     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8222       CurrentIterVals[&PHI] = StartCST;
8223   }
8224   if (!CurrentIterVals.count(PN))
8225     return RetVal = nullptr;
8226 
8227   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8228 
8229   // Execute the loop symbolically to determine the exit value.
8230   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8231          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8232 
8233   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8234   unsigned IterationNum = 0;
8235   const DataLayout &DL = getDataLayout();
8236   for (; ; ++IterationNum) {
8237     if (IterationNum == NumIterations)
8238       return RetVal = CurrentIterVals[PN];  // Got exit value!
8239 
8240     // Compute the value of the PHIs for the next iteration.
8241     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8242     DenseMap<Instruction *, Constant *> NextIterVals;
8243     Constant *NextPHI =
8244         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8245     if (!NextPHI)
8246       return nullptr;        // Couldn't evaluate!
8247     NextIterVals[PN] = NextPHI;
8248 
8249     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8250 
8251     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8252     // cease to be able to evaluate one of them or if they stop evolving,
8253     // because that doesn't necessarily prevent us from computing PN.
8254     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8255     for (const auto &I : CurrentIterVals) {
8256       PHINode *PHI = dyn_cast<PHINode>(I.first);
8257       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8258       PHIsToCompute.emplace_back(PHI, I.second);
8259     }
8260     // We use two distinct loops because EvaluateExpression may invalidate any
8261     // iterators into CurrentIterVals.
8262     for (const auto &I : PHIsToCompute) {
8263       PHINode *PHI = I.first;
8264       Constant *&NextPHI = NextIterVals[PHI];
8265       if (!NextPHI) {   // Not already computed.
8266         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8267         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8268       }
8269       if (NextPHI != I.second)
8270         StoppedEvolving = false;
8271     }
8272 
8273     // If all entries in CurrentIterVals == NextIterVals then we can stop
8274     // iterating, the loop can't continue to change.
8275     if (StoppedEvolving)
8276       return RetVal = CurrentIterVals[PN];
8277 
8278     CurrentIterVals.swap(NextIterVals);
8279   }
8280 }
8281 
8282 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8283                                                           Value *Cond,
8284                                                           bool ExitWhen) {
8285   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8286   if (!PN) return getCouldNotCompute();
8287 
8288   // If the loop is canonicalized, the PHI will have exactly two entries.
8289   // That's the only form we support here.
8290   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8291 
8292   DenseMap<Instruction *, Constant *> CurrentIterVals;
8293   BasicBlock *Header = L->getHeader();
8294   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8295 
8296   BasicBlock *Latch = L->getLoopLatch();
8297   assert(Latch && "Should follow from NumIncomingValues == 2!");
8298 
8299   for (PHINode &PHI : Header->phis()) {
8300     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8301       CurrentIterVals[&PHI] = StartCST;
8302   }
8303   if (!CurrentIterVals.count(PN))
8304     return getCouldNotCompute();
8305 
8306   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8307   // the loop symbolically to determine when the condition gets a value of
8308   // "ExitWhen".
8309   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8310   const DataLayout &DL = getDataLayout();
8311   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8312     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8313         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8314 
8315     // Couldn't symbolically evaluate.
8316     if (!CondVal) return getCouldNotCompute();
8317 
8318     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8319       ++NumBruteForceTripCountsComputed;
8320       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8321     }
8322 
8323     // Update all the PHI nodes for the next iteration.
8324     DenseMap<Instruction *, Constant *> NextIterVals;
8325 
8326     // Create a list of which PHIs we need to compute. We want to do this before
8327     // calling EvaluateExpression on them because that may invalidate iterators
8328     // into CurrentIterVals.
8329     SmallVector<PHINode *, 8> PHIsToCompute;
8330     for (const auto &I : CurrentIterVals) {
8331       PHINode *PHI = dyn_cast<PHINode>(I.first);
8332       if (!PHI || PHI->getParent() != Header) continue;
8333       PHIsToCompute.push_back(PHI);
8334     }
8335     for (PHINode *PHI : PHIsToCompute) {
8336       Constant *&NextPHI = NextIterVals[PHI];
8337       if (NextPHI) continue;    // Already computed!
8338 
8339       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8340       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8341     }
8342     CurrentIterVals.swap(NextIterVals);
8343   }
8344 
8345   // Too many iterations were needed to evaluate.
8346   return getCouldNotCompute();
8347 }
8348 
8349 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8350   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8351       ValuesAtScopes[V];
8352   // Check to see if we've folded this expression at this loop before.
8353   for (auto &LS : Values)
8354     if (LS.first == L)
8355       return LS.second ? LS.second : V;
8356 
8357   Values.emplace_back(L, nullptr);
8358 
8359   // Otherwise compute it.
8360   const SCEV *C = computeSCEVAtScope(V, L);
8361   for (auto &LS : reverse(ValuesAtScopes[V]))
8362     if (LS.first == L) {
8363       LS.second = C;
8364       break;
8365     }
8366   return C;
8367 }
8368 
8369 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8370 /// will return Constants for objects which aren't represented by a
8371 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8372 /// Returns NULL if the SCEV isn't representable as a Constant.
8373 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8374   switch (V->getSCEVType()) {
8375   case scCouldNotCompute:
8376   case scAddRecExpr:
8377     return nullptr;
8378   case scConstant:
8379     return cast<SCEVConstant>(V)->getValue();
8380   case scUnknown:
8381     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8382   case scSignExtend: {
8383     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8384     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8385       return ConstantExpr::getSExt(CastOp, SS->getType());
8386     return nullptr;
8387   }
8388   case scZeroExtend: {
8389     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8390     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8391       return ConstantExpr::getZExt(CastOp, SZ->getType());
8392     return nullptr;
8393   }
8394   case scPtrToInt: {
8395     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8396     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8397       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8398 
8399     return nullptr;
8400   }
8401   case scTruncate: {
8402     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8403     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8404       return ConstantExpr::getTrunc(CastOp, ST->getType());
8405     return nullptr;
8406   }
8407   case scAddExpr: {
8408     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8409     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8410       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8411         unsigned AS = PTy->getAddressSpace();
8412         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8413         C = ConstantExpr::getBitCast(C, DestPtrTy);
8414       }
8415       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8416         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8417         if (!C2)
8418           return nullptr;
8419 
8420         // First pointer!
8421         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8422           unsigned AS = C2->getType()->getPointerAddressSpace();
8423           std::swap(C, C2);
8424           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8425           // The offsets have been converted to bytes.  We can add bytes to an
8426           // i8* by GEP with the byte count in the first index.
8427           C = ConstantExpr::getBitCast(C, DestPtrTy);
8428         }
8429 
8430         // Don't bother trying to sum two pointers. We probably can't
8431         // statically compute a load that results from it anyway.
8432         if (C2->getType()->isPointerTy())
8433           return nullptr;
8434 
8435         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8436           if (PTy->getElementType()->isStructTy())
8437             C2 = ConstantExpr::getIntegerCast(
8438                 C2, Type::getInt32Ty(C->getContext()), true);
8439           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8440         } else
8441           C = ConstantExpr::getAdd(C, C2);
8442       }
8443       return C;
8444     }
8445     return nullptr;
8446   }
8447   case scMulExpr: {
8448     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8449     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8450       // Don't bother with pointers at all.
8451       if (C->getType()->isPointerTy())
8452         return nullptr;
8453       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8454         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8455         if (!C2 || C2->getType()->isPointerTy())
8456           return nullptr;
8457         C = ConstantExpr::getMul(C, C2);
8458       }
8459       return C;
8460     }
8461     return nullptr;
8462   }
8463   case scUDivExpr: {
8464     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8465     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8466       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8467         if (LHS->getType() == RHS->getType())
8468           return ConstantExpr::getUDiv(LHS, RHS);
8469     return nullptr;
8470   }
8471   case scSMaxExpr:
8472   case scUMaxExpr:
8473   case scSMinExpr:
8474   case scUMinExpr:
8475     return nullptr; // TODO: smax, umax, smin, umax.
8476   }
8477   llvm_unreachable("Unknown SCEV kind!");
8478 }
8479 
8480 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8481   if (isa<SCEVConstant>(V)) return V;
8482 
8483   // If this instruction is evolved from a constant-evolving PHI, compute the
8484   // exit value from the loop without using SCEVs.
8485   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8486     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8487       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8488         const Loop *CurrLoop = this->LI[I->getParent()];
8489         // Looking for loop exit value.
8490         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8491             PN->getParent() == CurrLoop->getHeader()) {
8492           // Okay, there is no closed form solution for the PHI node.  Check
8493           // to see if the loop that contains it has a known backedge-taken
8494           // count.  If so, we may be able to force computation of the exit
8495           // value.
8496           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8497           // This trivial case can show up in some degenerate cases where
8498           // the incoming IR has not yet been fully simplified.
8499           if (BackedgeTakenCount->isZero()) {
8500             Value *InitValue = nullptr;
8501             bool MultipleInitValues = false;
8502             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8503               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8504                 if (!InitValue)
8505                   InitValue = PN->getIncomingValue(i);
8506                 else if (InitValue != PN->getIncomingValue(i)) {
8507                   MultipleInitValues = true;
8508                   break;
8509                 }
8510               }
8511             }
8512             if (!MultipleInitValues && InitValue)
8513               return getSCEV(InitValue);
8514           }
8515           // Do we have a loop invariant value flowing around the backedge
8516           // for a loop which must execute the backedge?
8517           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8518               isKnownPositive(BackedgeTakenCount) &&
8519               PN->getNumIncomingValues() == 2) {
8520 
8521             unsigned InLoopPred =
8522                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8523             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8524             if (CurrLoop->isLoopInvariant(BackedgeVal))
8525               return getSCEV(BackedgeVal);
8526           }
8527           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8528             // Okay, we know how many times the containing loop executes.  If
8529             // this is a constant evolving PHI node, get the final value at
8530             // the specified iteration number.
8531             Constant *RV = getConstantEvolutionLoopExitValue(
8532                 PN, BTCC->getAPInt(), CurrLoop);
8533             if (RV) return getSCEV(RV);
8534           }
8535         }
8536 
8537         // If there is a single-input Phi, evaluate it at our scope. If we can
8538         // prove that this replacement does not break LCSSA form, use new value.
8539         if (PN->getNumOperands() == 1) {
8540           const SCEV *Input = getSCEV(PN->getOperand(0));
8541           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8542           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8543           // for the simplest case just support constants.
8544           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8545         }
8546       }
8547 
8548       // Okay, this is an expression that we cannot symbolically evaluate
8549       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8550       // the arguments into constants, and if so, try to constant propagate the
8551       // result.  This is particularly useful for computing loop exit values.
8552       if (CanConstantFold(I)) {
8553         SmallVector<Constant *, 4> Operands;
8554         bool MadeImprovement = false;
8555         for (Value *Op : I->operands()) {
8556           if (Constant *C = dyn_cast<Constant>(Op)) {
8557             Operands.push_back(C);
8558             continue;
8559           }
8560 
8561           // If any of the operands is non-constant and if they are
8562           // non-integer and non-pointer, don't even try to analyze them
8563           // with scev techniques.
8564           if (!isSCEVable(Op->getType()))
8565             return V;
8566 
8567           const SCEV *OrigV = getSCEV(Op);
8568           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8569           MadeImprovement |= OrigV != OpV;
8570 
8571           Constant *C = BuildConstantFromSCEV(OpV);
8572           if (!C) return V;
8573           if (C->getType() != Op->getType())
8574             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8575                                                               Op->getType(),
8576                                                               false),
8577                                       C, Op->getType());
8578           Operands.push_back(C);
8579         }
8580 
8581         // Check to see if getSCEVAtScope actually made an improvement.
8582         if (MadeImprovement) {
8583           Constant *C = nullptr;
8584           const DataLayout &DL = getDataLayout();
8585           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8586             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8587                                                 Operands[1], DL, &TLI);
8588           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8589             if (!Load->isVolatile())
8590               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8591                                                DL);
8592           } else
8593             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8594           if (!C) return V;
8595           return getSCEV(C);
8596         }
8597       }
8598     }
8599 
8600     // This is some other type of SCEVUnknown, just return it.
8601     return V;
8602   }
8603 
8604   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8605     // Avoid performing the look-up in the common case where the specified
8606     // expression has no loop-variant portions.
8607     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8608       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8609       if (OpAtScope != Comm->getOperand(i)) {
8610         // Okay, at least one of these operands is loop variant but might be
8611         // foldable.  Build a new instance of the folded commutative expression.
8612         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8613                                             Comm->op_begin()+i);
8614         NewOps.push_back(OpAtScope);
8615 
8616         for (++i; i != e; ++i) {
8617           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8618           NewOps.push_back(OpAtScope);
8619         }
8620         if (isa<SCEVAddExpr>(Comm))
8621           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8622         if (isa<SCEVMulExpr>(Comm))
8623           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8624         if (isa<SCEVMinMaxExpr>(Comm))
8625           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8626         llvm_unreachable("Unknown commutative SCEV type!");
8627       }
8628     }
8629     // If we got here, all operands are loop invariant.
8630     return Comm;
8631   }
8632 
8633   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8634     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8635     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8636     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8637       return Div;   // must be loop invariant
8638     return getUDivExpr(LHS, RHS);
8639   }
8640 
8641   // If this is a loop recurrence for a loop that does not contain L, then we
8642   // are dealing with the final value computed by the loop.
8643   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8644     // First, attempt to evaluate each operand.
8645     // Avoid performing the look-up in the common case where the specified
8646     // expression has no loop-variant portions.
8647     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8648       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8649       if (OpAtScope == AddRec->getOperand(i))
8650         continue;
8651 
8652       // Okay, at least one of these operands is loop variant but might be
8653       // foldable.  Build a new instance of the folded commutative expression.
8654       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8655                                           AddRec->op_begin()+i);
8656       NewOps.push_back(OpAtScope);
8657       for (++i; i != e; ++i)
8658         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8659 
8660       const SCEV *FoldedRec =
8661         getAddRecExpr(NewOps, AddRec->getLoop(),
8662                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8663       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8664       // The addrec may be folded to a nonrecurrence, for example, if the
8665       // induction variable is multiplied by zero after constant folding. Go
8666       // ahead and return the folded value.
8667       if (!AddRec)
8668         return FoldedRec;
8669       break;
8670     }
8671 
8672     // If the scope is outside the addrec's loop, evaluate it by using the
8673     // loop exit value of the addrec.
8674     if (!AddRec->getLoop()->contains(L)) {
8675       // To evaluate this recurrence, we need to know how many times the AddRec
8676       // loop iterates.  Compute this now.
8677       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8678       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8679 
8680       // Then, evaluate the AddRec.
8681       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8682     }
8683 
8684     return AddRec;
8685   }
8686 
8687   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8688     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8689     if (Op == Cast->getOperand())
8690       return Cast;  // must be loop invariant
8691     return getZeroExtendExpr(Op, Cast->getType());
8692   }
8693 
8694   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8695     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8696     if (Op == Cast->getOperand())
8697       return Cast;  // must be loop invariant
8698     return getSignExtendExpr(Op, Cast->getType());
8699   }
8700 
8701   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8702     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8703     if (Op == Cast->getOperand())
8704       return Cast;  // must be loop invariant
8705     return getTruncateExpr(Op, Cast->getType());
8706   }
8707 
8708   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8709     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8710     if (Op == Cast->getOperand())
8711       return Cast; // must be loop invariant
8712     return getPtrToIntExpr(Op, Cast->getType());
8713   }
8714 
8715   llvm_unreachable("Unknown SCEV type!");
8716 }
8717 
8718 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8719   return getSCEVAtScope(getSCEV(V), L);
8720 }
8721 
8722 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8723   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8724     return stripInjectiveFunctions(ZExt->getOperand());
8725   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8726     return stripInjectiveFunctions(SExt->getOperand());
8727   return S;
8728 }
8729 
8730 /// Finds the minimum unsigned root of the following equation:
8731 ///
8732 ///     A * X = B (mod N)
8733 ///
8734 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8735 /// A and B isn't important.
8736 ///
8737 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8738 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8739                                                ScalarEvolution &SE) {
8740   uint32_t BW = A.getBitWidth();
8741   assert(BW == SE.getTypeSizeInBits(B->getType()));
8742   assert(A != 0 && "A must be non-zero.");
8743 
8744   // 1. D = gcd(A, N)
8745   //
8746   // The gcd of A and N may have only one prime factor: 2. The number of
8747   // trailing zeros in A is its multiplicity
8748   uint32_t Mult2 = A.countTrailingZeros();
8749   // D = 2^Mult2
8750 
8751   // 2. Check if B is divisible by D.
8752   //
8753   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8754   // is not less than multiplicity of this prime factor for D.
8755   if (SE.GetMinTrailingZeros(B) < Mult2)
8756     return SE.getCouldNotCompute();
8757 
8758   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8759   // modulo (N / D).
8760   //
8761   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8762   // (N / D) in general. The inverse itself always fits into BW bits, though,
8763   // so we immediately truncate it.
8764   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8765   APInt Mod(BW + 1, 0);
8766   Mod.setBit(BW - Mult2);  // Mod = N / D
8767   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8768 
8769   // 4. Compute the minimum unsigned root of the equation:
8770   // I * (B / D) mod (N / D)
8771   // To simplify the computation, we factor out the divide by D:
8772   // (I * B mod N) / D
8773   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8774   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8775 }
8776 
8777 /// For a given quadratic addrec, generate coefficients of the corresponding
8778 /// quadratic equation, multiplied by a common value to ensure that they are
8779 /// integers.
8780 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8781 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8782 /// were multiplied by, and BitWidth is the bit width of the original addrec
8783 /// coefficients.
8784 /// This function returns None if the addrec coefficients are not compile-
8785 /// time constants.
8786 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8787 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8788   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8789   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8790   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8791   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8792   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8793                     << *AddRec << '\n');
8794 
8795   // We currently can only solve this if the coefficients are constants.
8796   if (!LC || !MC || !NC) {
8797     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8798     return None;
8799   }
8800 
8801   APInt L = LC->getAPInt();
8802   APInt M = MC->getAPInt();
8803   APInt N = NC->getAPInt();
8804   assert(!N.isNullValue() && "This is not a quadratic addrec");
8805 
8806   unsigned BitWidth = LC->getAPInt().getBitWidth();
8807   unsigned NewWidth = BitWidth + 1;
8808   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8809                     << BitWidth << '\n');
8810   // The sign-extension (as opposed to a zero-extension) here matches the
8811   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8812   N = N.sext(NewWidth);
8813   M = M.sext(NewWidth);
8814   L = L.sext(NewWidth);
8815 
8816   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8817   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8818   //   L+M, L+2M+N, L+3M+3N, ...
8819   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8820   //
8821   // The equation Acc = 0 is then
8822   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8823   // In a quadratic form it becomes:
8824   //   N n^2 + (2M-N) n + 2L = 0.
8825 
8826   APInt A = N;
8827   APInt B = 2 * M - A;
8828   APInt C = 2 * L;
8829   APInt T = APInt(NewWidth, 2);
8830   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8831                     << "x + " << C << ", coeff bw: " << NewWidth
8832                     << ", multiplied by " << T << '\n');
8833   return std::make_tuple(A, B, C, T, BitWidth);
8834 }
8835 
8836 /// Helper function to compare optional APInts:
8837 /// (a) if X and Y both exist, return min(X, Y),
8838 /// (b) if neither X nor Y exist, return None,
8839 /// (c) if exactly one of X and Y exists, return that value.
8840 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8841   if (X.hasValue() && Y.hasValue()) {
8842     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8843     APInt XW = X->sextOrSelf(W);
8844     APInt YW = Y->sextOrSelf(W);
8845     return XW.slt(YW) ? *X : *Y;
8846   }
8847   if (!X.hasValue() && !Y.hasValue())
8848     return None;
8849   return X.hasValue() ? *X : *Y;
8850 }
8851 
8852 /// Helper function to truncate an optional APInt to a given BitWidth.
8853 /// When solving addrec-related equations, it is preferable to return a value
8854 /// that has the same bit width as the original addrec's coefficients. If the
8855 /// solution fits in the original bit width, truncate it (except for i1).
8856 /// Returning a value of a different bit width may inhibit some optimizations.
8857 ///
8858 /// In general, a solution to a quadratic equation generated from an addrec
8859 /// may require BW+1 bits, where BW is the bit width of the addrec's
8860 /// coefficients. The reason is that the coefficients of the quadratic
8861 /// equation are BW+1 bits wide (to avoid truncation when converting from
8862 /// the addrec to the equation).
8863 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8864   if (!X.hasValue())
8865     return None;
8866   unsigned W = X->getBitWidth();
8867   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8868     return X->trunc(BitWidth);
8869   return X;
8870 }
8871 
8872 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8873 /// iterations. The values L, M, N are assumed to be signed, and they
8874 /// should all have the same bit widths.
8875 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8876 /// where BW is the bit width of the addrec's coefficients.
8877 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8878 /// returned as such, otherwise the bit width of the returned value may
8879 /// be greater than BW.
8880 ///
8881 /// This function returns None if
8882 /// (a) the addrec coefficients are not constant, or
8883 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8884 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8885 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8886 static Optional<APInt>
8887 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8888   APInt A, B, C, M;
8889   unsigned BitWidth;
8890   auto T = GetQuadraticEquation(AddRec);
8891   if (!T.hasValue())
8892     return None;
8893 
8894   std::tie(A, B, C, M, BitWidth) = *T;
8895   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8896   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8897   if (!X.hasValue())
8898     return None;
8899 
8900   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8901   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8902   if (!V->isZero())
8903     return None;
8904 
8905   return TruncIfPossible(X, BitWidth);
8906 }
8907 
8908 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8909 /// iterations. The values M, N are assumed to be signed, and they
8910 /// should all have the same bit widths.
8911 /// Find the least n such that c(n) does not belong to the given range,
8912 /// while c(n-1) does.
8913 ///
8914 /// This function returns None if
8915 /// (a) the addrec coefficients are not constant, or
8916 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8917 ///     bounds of the range.
8918 static Optional<APInt>
8919 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8920                           const ConstantRange &Range, ScalarEvolution &SE) {
8921   assert(AddRec->getOperand(0)->isZero() &&
8922          "Starting value of addrec should be 0");
8923   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8924                     << Range << ", addrec " << *AddRec << '\n');
8925   // This case is handled in getNumIterationsInRange. Here we can assume that
8926   // we start in the range.
8927   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8928          "Addrec's initial value should be in range");
8929 
8930   APInt A, B, C, M;
8931   unsigned BitWidth;
8932   auto T = GetQuadraticEquation(AddRec);
8933   if (!T.hasValue())
8934     return None;
8935 
8936   // Be careful about the return value: there can be two reasons for not
8937   // returning an actual number. First, if no solutions to the equations
8938   // were found, and second, if the solutions don't leave the given range.
8939   // The first case means that the actual solution is "unknown", the second
8940   // means that it's known, but not valid. If the solution is unknown, we
8941   // cannot make any conclusions.
8942   // Return a pair: the optional solution and a flag indicating if the
8943   // solution was found.
8944   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8945     // Solve for signed overflow and unsigned overflow, pick the lower
8946     // solution.
8947     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8948                       << Bound << " (before multiplying by " << M << ")\n");
8949     Bound *= M; // The quadratic equation multiplier.
8950 
8951     Optional<APInt> SO = None;
8952     if (BitWidth > 1) {
8953       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8954                            "signed overflow\n");
8955       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8956     }
8957     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8958                          "unsigned overflow\n");
8959     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8960                                                               BitWidth+1);
8961 
8962     auto LeavesRange = [&] (const APInt &X) {
8963       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8964       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8965       if (Range.contains(V0->getValue()))
8966         return false;
8967       // X should be at least 1, so X-1 is non-negative.
8968       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8969       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8970       if (Range.contains(V1->getValue()))
8971         return true;
8972       return false;
8973     };
8974 
8975     // If SolveQuadraticEquationWrap returns None, it means that there can
8976     // be a solution, but the function failed to find it. We cannot treat it
8977     // as "no solution".
8978     if (!SO.hasValue() || !UO.hasValue())
8979       return { None, false };
8980 
8981     // Check the smaller value first to see if it leaves the range.
8982     // At this point, both SO and UO must have values.
8983     Optional<APInt> Min = MinOptional(SO, UO);
8984     if (LeavesRange(*Min))
8985       return { Min, true };
8986     Optional<APInt> Max = Min == SO ? UO : SO;
8987     if (LeavesRange(*Max))
8988       return { Max, true };
8989 
8990     // Solutions were found, but were eliminated, hence the "true".
8991     return { None, true };
8992   };
8993 
8994   std::tie(A, B, C, M, BitWidth) = *T;
8995   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8996   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8997   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8998   auto SL = SolveForBoundary(Lower);
8999   auto SU = SolveForBoundary(Upper);
9000   // If any of the solutions was unknown, no meaninigful conclusions can
9001   // be made.
9002   if (!SL.second || !SU.second)
9003     return None;
9004 
9005   // Claim: The correct solution is not some value between Min and Max.
9006   //
9007   // Justification: Assuming that Min and Max are different values, one of
9008   // them is when the first signed overflow happens, the other is when the
9009   // first unsigned overflow happens. Crossing the range boundary is only
9010   // possible via an overflow (treating 0 as a special case of it, modeling
9011   // an overflow as crossing k*2^W for some k).
9012   //
9013   // The interesting case here is when Min was eliminated as an invalid
9014   // solution, but Max was not. The argument is that if there was another
9015   // overflow between Min and Max, it would also have been eliminated if
9016   // it was considered.
9017   //
9018   // For a given boundary, it is possible to have two overflows of the same
9019   // type (signed/unsigned) without having the other type in between: this
9020   // can happen when the vertex of the parabola is between the iterations
9021   // corresponding to the overflows. This is only possible when the two
9022   // overflows cross k*2^W for the same k. In such case, if the second one
9023   // left the range (and was the first one to do so), the first overflow
9024   // would have to enter the range, which would mean that either we had left
9025   // the range before or that we started outside of it. Both of these cases
9026   // are contradictions.
9027   //
9028   // Claim: In the case where SolveForBoundary returns None, the correct
9029   // solution is not some value between the Max for this boundary and the
9030   // Min of the other boundary.
9031   //
9032   // Justification: Assume that we had such Max_A and Min_B corresponding
9033   // to range boundaries A and B and such that Max_A < Min_B. If there was
9034   // a solution between Max_A and Min_B, it would have to be caused by an
9035   // overflow corresponding to either A or B. It cannot correspond to B,
9036   // since Min_B is the first occurrence of such an overflow. If it
9037   // corresponded to A, it would have to be either a signed or an unsigned
9038   // overflow that is larger than both eliminated overflows for A. But
9039   // between the eliminated overflows and this overflow, the values would
9040   // cover the entire value space, thus crossing the other boundary, which
9041   // is a contradiction.
9042 
9043   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9044 }
9045 
9046 ScalarEvolution::ExitLimit
9047 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9048                               bool AllowPredicates) {
9049 
9050   // This is only used for loops with a "x != y" exit test. The exit condition
9051   // is now expressed as a single expression, V = x-y. So the exit test is
9052   // effectively V != 0.  We know and take advantage of the fact that this
9053   // expression only being used in a comparison by zero context.
9054 
9055   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9056   // If the value is a constant
9057   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9058     // If the value is already zero, the branch will execute zero times.
9059     if (C->getValue()->isZero()) return C;
9060     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9061   }
9062 
9063   const SCEVAddRecExpr *AddRec =
9064       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9065 
9066   if (!AddRec && AllowPredicates)
9067     // Try to make this an AddRec using runtime tests, in the first X
9068     // iterations of this loop, where X is the SCEV expression found by the
9069     // algorithm below.
9070     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9071 
9072   if (!AddRec || AddRec->getLoop() != L)
9073     return getCouldNotCompute();
9074 
9075   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9076   // the quadratic equation to solve it.
9077   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9078     // We can only use this value if the chrec ends up with an exact zero
9079     // value at this index.  When solving for "X*X != 5", for example, we
9080     // should not accept a root of 2.
9081     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9082       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9083       return ExitLimit(R, R, false, Predicates);
9084     }
9085     return getCouldNotCompute();
9086   }
9087 
9088   // Otherwise we can only handle this if it is affine.
9089   if (!AddRec->isAffine())
9090     return getCouldNotCompute();
9091 
9092   // If this is an affine expression, the execution count of this branch is
9093   // the minimum unsigned root of the following equation:
9094   //
9095   //     Start + Step*N = 0 (mod 2^BW)
9096   //
9097   // equivalent to:
9098   //
9099   //             Step*N = -Start (mod 2^BW)
9100   //
9101   // where BW is the common bit width of Start and Step.
9102 
9103   // Get the initial value for the loop.
9104   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9105   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9106 
9107   // For now we handle only constant steps.
9108   //
9109   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9110   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9111   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9112   // We have not yet seen any such cases.
9113   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9114   if (!StepC || StepC->getValue()->isZero())
9115     return getCouldNotCompute();
9116 
9117   // For positive steps (counting up until unsigned overflow):
9118   //   N = -Start/Step (as unsigned)
9119   // For negative steps (counting down to zero):
9120   //   N = Start/-Step
9121   // First compute the unsigned distance from zero in the direction of Step.
9122   bool CountDown = StepC->getAPInt().isNegative();
9123   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9124 
9125   // Handle unitary steps, which cannot wraparound.
9126   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9127   //   N = Distance (as unsigned)
9128   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9129     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9130     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9131     if (MaxBECountBase.ult(MaxBECount))
9132       MaxBECount = MaxBECountBase;
9133 
9134     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9135     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9136     // case, and see if we can improve the bound.
9137     //
9138     // Explicitly handling this here is necessary because getUnsignedRange
9139     // isn't context-sensitive; it doesn't know that we only care about the
9140     // range inside the loop.
9141     const SCEV *Zero = getZero(Distance->getType());
9142     const SCEV *One = getOne(Distance->getType());
9143     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9144     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9145       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9146       // as "unsigned_max(Distance + 1) - 1".
9147       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9148       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9149     }
9150     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9151   }
9152 
9153   // If the condition controls loop exit (the loop exits only if the expression
9154   // is true) and the addition is no-wrap we can use unsigned divide to
9155   // compute the backedge count.  In this case, the step may not divide the
9156   // distance, but we don't care because if the condition is "missed" the loop
9157   // will have undefined behavior due to wrapping.
9158   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9159       loopHasNoAbnormalExits(AddRec->getLoop())) {
9160     const SCEV *Exact =
9161         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9162     const SCEV *Max =
9163         Exact == getCouldNotCompute()
9164             ? Exact
9165             : getConstant(getUnsignedRangeMax(Exact));
9166     return ExitLimit(Exact, Max, false, Predicates);
9167   }
9168 
9169   // Solve the general equation.
9170   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9171                                                getNegativeSCEV(Start), *this);
9172   const SCEV *M = E == getCouldNotCompute()
9173                       ? E
9174                       : getConstant(getUnsignedRangeMax(E));
9175   return ExitLimit(E, M, false, Predicates);
9176 }
9177 
9178 ScalarEvolution::ExitLimit
9179 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9180   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9181   // handle them yet except for the trivial case.  This could be expanded in the
9182   // future as needed.
9183 
9184   // If the value is a constant, check to see if it is known to be non-zero
9185   // already.  If so, the backedge will execute zero times.
9186   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9187     if (!C->getValue()->isZero())
9188       return getZero(C->getType());
9189     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9190   }
9191 
9192   // We could implement others, but I really doubt anyone writes loops like
9193   // this, and if they did, they would already be constant folded.
9194   return getCouldNotCompute();
9195 }
9196 
9197 std::pair<const BasicBlock *, const BasicBlock *>
9198 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9199     const {
9200   // If the block has a unique predecessor, then there is no path from the
9201   // predecessor to the block that does not go through the direct edge
9202   // from the predecessor to the block.
9203   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9204     return {Pred, BB};
9205 
9206   // A loop's header is defined to be a block that dominates the loop.
9207   // If the header has a unique predecessor outside the loop, it must be
9208   // a block that has exactly one successor that can reach the loop.
9209   if (const Loop *L = LI.getLoopFor(BB))
9210     return {L->getLoopPredecessor(), L->getHeader()};
9211 
9212   return {nullptr, nullptr};
9213 }
9214 
9215 /// SCEV structural equivalence is usually sufficient for testing whether two
9216 /// expressions are equal, however for the purposes of looking for a condition
9217 /// guarding a loop, it can be useful to be a little more general, since a
9218 /// front-end may have replicated the controlling expression.
9219 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9220   // Quick check to see if they are the same SCEV.
9221   if (A == B) return true;
9222 
9223   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9224     // Not all instructions that are "identical" compute the same value.  For
9225     // instance, two distinct alloca instructions allocating the same type are
9226     // identical and do not read memory; but compute distinct values.
9227     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9228   };
9229 
9230   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9231   // two different instructions with the same value. Check for this case.
9232   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9233     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9234       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9235         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9236           if (ComputesEqualValues(AI, BI))
9237             return true;
9238 
9239   // Otherwise assume they may have a different value.
9240   return false;
9241 }
9242 
9243 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9244                                            const SCEV *&LHS, const SCEV *&RHS,
9245                                            unsigned Depth) {
9246   bool Changed = false;
9247   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9248   // '0 != 0'.
9249   auto TrivialCase = [&](bool TriviallyTrue) {
9250     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9251     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9252     return true;
9253   };
9254   // If we hit the max recursion limit bail out.
9255   if (Depth >= 3)
9256     return false;
9257 
9258   // Canonicalize a constant to the right side.
9259   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9260     // Check for both operands constant.
9261     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9262       if (ConstantExpr::getICmp(Pred,
9263                                 LHSC->getValue(),
9264                                 RHSC->getValue())->isNullValue())
9265         return TrivialCase(false);
9266       else
9267         return TrivialCase(true);
9268     }
9269     // Otherwise swap the operands to put the constant on the right.
9270     std::swap(LHS, RHS);
9271     Pred = ICmpInst::getSwappedPredicate(Pred);
9272     Changed = true;
9273   }
9274 
9275   // If we're comparing an addrec with a value which is loop-invariant in the
9276   // addrec's loop, put the addrec on the left. Also make a dominance check,
9277   // as both operands could be addrecs loop-invariant in each other's loop.
9278   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9279     const Loop *L = AR->getLoop();
9280     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9281       std::swap(LHS, RHS);
9282       Pred = ICmpInst::getSwappedPredicate(Pred);
9283       Changed = true;
9284     }
9285   }
9286 
9287   // If there's a constant operand, canonicalize comparisons with boundary
9288   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9289   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9290     const APInt &RA = RC->getAPInt();
9291 
9292     bool SimplifiedByConstantRange = false;
9293 
9294     if (!ICmpInst::isEquality(Pred)) {
9295       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9296       if (ExactCR.isFullSet())
9297         return TrivialCase(true);
9298       else if (ExactCR.isEmptySet())
9299         return TrivialCase(false);
9300 
9301       APInt NewRHS;
9302       CmpInst::Predicate NewPred;
9303       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9304           ICmpInst::isEquality(NewPred)) {
9305         // We were able to convert an inequality to an equality.
9306         Pred = NewPred;
9307         RHS = getConstant(NewRHS);
9308         Changed = SimplifiedByConstantRange = true;
9309       }
9310     }
9311 
9312     if (!SimplifiedByConstantRange) {
9313       switch (Pred) {
9314       default:
9315         break;
9316       case ICmpInst::ICMP_EQ:
9317       case ICmpInst::ICMP_NE:
9318         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9319         if (!RA)
9320           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9321             if (const SCEVMulExpr *ME =
9322                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9323               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9324                   ME->getOperand(0)->isAllOnesValue()) {
9325                 RHS = AE->getOperand(1);
9326                 LHS = ME->getOperand(1);
9327                 Changed = true;
9328               }
9329         break;
9330 
9331 
9332         // The "Should have been caught earlier!" messages refer to the fact
9333         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9334         // should have fired on the corresponding cases, and canonicalized the
9335         // check to trivial case.
9336 
9337       case ICmpInst::ICMP_UGE:
9338         assert(!RA.isMinValue() && "Should have been caught earlier!");
9339         Pred = ICmpInst::ICMP_UGT;
9340         RHS = getConstant(RA - 1);
9341         Changed = true;
9342         break;
9343       case ICmpInst::ICMP_ULE:
9344         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9345         Pred = ICmpInst::ICMP_ULT;
9346         RHS = getConstant(RA + 1);
9347         Changed = true;
9348         break;
9349       case ICmpInst::ICMP_SGE:
9350         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9351         Pred = ICmpInst::ICMP_SGT;
9352         RHS = getConstant(RA - 1);
9353         Changed = true;
9354         break;
9355       case ICmpInst::ICMP_SLE:
9356         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9357         Pred = ICmpInst::ICMP_SLT;
9358         RHS = getConstant(RA + 1);
9359         Changed = true;
9360         break;
9361       }
9362     }
9363   }
9364 
9365   // Check for obvious equality.
9366   if (HasSameValue(LHS, RHS)) {
9367     if (ICmpInst::isTrueWhenEqual(Pred))
9368       return TrivialCase(true);
9369     if (ICmpInst::isFalseWhenEqual(Pred))
9370       return TrivialCase(false);
9371   }
9372 
9373   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9374   // adding or subtracting 1 from one of the operands.
9375   switch (Pred) {
9376   case ICmpInst::ICMP_SLE:
9377     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9378       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9379                        SCEV::FlagNSW);
9380       Pred = ICmpInst::ICMP_SLT;
9381       Changed = true;
9382     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9383       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9384                        SCEV::FlagNSW);
9385       Pred = ICmpInst::ICMP_SLT;
9386       Changed = true;
9387     }
9388     break;
9389   case ICmpInst::ICMP_SGE:
9390     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9391       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9392                        SCEV::FlagNSW);
9393       Pred = ICmpInst::ICMP_SGT;
9394       Changed = true;
9395     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9396       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9397                        SCEV::FlagNSW);
9398       Pred = ICmpInst::ICMP_SGT;
9399       Changed = true;
9400     }
9401     break;
9402   case ICmpInst::ICMP_ULE:
9403     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9404       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9405                        SCEV::FlagNUW);
9406       Pred = ICmpInst::ICMP_ULT;
9407       Changed = true;
9408     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9409       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9410       Pred = ICmpInst::ICMP_ULT;
9411       Changed = true;
9412     }
9413     break;
9414   case ICmpInst::ICMP_UGE:
9415     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9416       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9417       Pred = ICmpInst::ICMP_UGT;
9418       Changed = true;
9419     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9420       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9421                        SCEV::FlagNUW);
9422       Pred = ICmpInst::ICMP_UGT;
9423       Changed = true;
9424     }
9425     break;
9426   default:
9427     break;
9428   }
9429 
9430   // TODO: More simplifications are possible here.
9431 
9432   // Recursively simplify until we either hit a recursion limit or nothing
9433   // changes.
9434   if (Changed)
9435     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9436 
9437   return Changed;
9438 }
9439 
9440 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9441   return getSignedRangeMax(S).isNegative();
9442 }
9443 
9444 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9445   return getSignedRangeMin(S).isStrictlyPositive();
9446 }
9447 
9448 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9449   return !getSignedRangeMin(S).isNegative();
9450 }
9451 
9452 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9453   return !getSignedRangeMax(S).isStrictlyPositive();
9454 }
9455 
9456 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9457   return isKnownNegative(S) || isKnownPositive(S);
9458 }
9459 
9460 std::pair<const SCEV *, const SCEV *>
9461 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9462   // Compute SCEV on entry of loop L.
9463   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9464   if (Start == getCouldNotCompute())
9465     return { Start, Start };
9466   // Compute post increment SCEV for loop L.
9467   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9468   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9469   return { Start, PostInc };
9470 }
9471 
9472 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9473                                           const SCEV *LHS, const SCEV *RHS) {
9474   // First collect all loops.
9475   SmallPtrSet<const Loop *, 8> LoopsUsed;
9476   getUsedLoops(LHS, LoopsUsed);
9477   getUsedLoops(RHS, LoopsUsed);
9478 
9479   if (LoopsUsed.empty())
9480     return false;
9481 
9482   // Domination relationship must be a linear order on collected loops.
9483 #ifndef NDEBUG
9484   for (auto *L1 : LoopsUsed)
9485     for (auto *L2 : LoopsUsed)
9486       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9487               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9488              "Domination relationship is not a linear order");
9489 #endif
9490 
9491   const Loop *MDL =
9492       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9493                         [&](const Loop *L1, const Loop *L2) {
9494          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9495        });
9496 
9497   // Get init and post increment value for LHS.
9498   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9499   // if LHS contains unknown non-invariant SCEV then bail out.
9500   if (SplitLHS.first == getCouldNotCompute())
9501     return false;
9502   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9503   // Get init and post increment value for RHS.
9504   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9505   // if RHS contains unknown non-invariant SCEV then bail out.
9506   if (SplitRHS.first == getCouldNotCompute())
9507     return false;
9508   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9509   // It is possible that init SCEV contains an invariant load but it does
9510   // not dominate MDL and is not available at MDL loop entry, so we should
9511   // check it here.
9512   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9513       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9514     return false;
9515 
9516   // It seems backedge guard check is faster than entry one so in some cases
9517   // it can speed up whole estimation by short circuit
9518   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9519                                      SplitRHS.second) &&
9520          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9521 }
9522 
9523 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9524                                        const SCEV *LHS, const SCEV *RHS) {
9525   // Canonicalize the inputs first.
9526   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9527 
9528   if (isKnownViaInduction(Pred, LHS, RHS))
9529     return true;
9530 
9531   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9532     return true;
9533 
9534   // Otherwise see what can be done with some simple reasoning.
9535   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9536 }
9537 
9538 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9539                                          const SCEV *LHS, const SCEV *RHS,
9540                                          const Instruction *Context) {
9541   // TODO: Analyze guards and assumes from Context's block.
9542   return isKnownPredicate(Pred, LHS, RHS) ||
9543          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9544 }
9545 
9546 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9547                                               const SCEVAddRecExpr *LHS,
9548                                               const SCEV *RHS) {
9549   const Loop *L = LHS->getLoop();
9550   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9551          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9552 }
9553 
9554 Optional<ScalarEvolution::MonotonicPredicateType>
9555 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9556                                            ICmpInst::Predicate Pred) {
9557   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9558 
9559 #ifndef NDEBUG
9560   // Verify an invariant: inverting the predicate should turn a monotonically
9561   // increasing change to a monotonically decreasing one, and vice versa.
9562   if (Result) {
9563     auto ResultSwapped =
9564         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9565 
9566     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9567     assert(ResultSwapped.getValue() != Result.getValue() &&
9568            "monotonicity should flip as we flip the predicate");
9569   }
9570 #endif
9571 
9572   return Result;
9573 }
9574 
9575 Optional<ScalarEvolution::MonotonicPredicateType>
9576 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9577                                                ICmpInst::Predicate Pred) {
9578   // A zero step value for LHS means the induction variable is essentially a
9579   // loop invariant value. We don't really depend on the predicate actually
9580   // flipping from false to true (for increasing predicates, and the other way
9581   // around for decreasing predicates), all we care about is that *if* the
9582   // predicate changes then it only changes from false to true.
9583   //
9584   // A zero step value in itself is not very useful, but there may be places
9585   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9586   // as general as possible.
9587 
9588   // Only handle LE/LT/GE/GT predicates.
9589   if (!ICmpInst::isRelational(Pred))
9590     return None;
9591 
9592   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9593   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9594          "Should be greater or less!");
9595 
9596   // Check that AR does not wrap.
9597   if (ICmpInst::isUnsigned(Pred)) {
9598     if (!LHS->hasNoUnsignedWrap())
9599       return None;
9600     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9601   } else {
9602     assert(ICmpInst::isSigned(Pred) &&
9603            "Relational predicate is either signed or unsigned!");
9604     if (!LHS->hasNoSignedWrap())
9605       return None;
9606 
9607     const SCEV *Step = LHS->getStepRecurrence(*this);
9608 
9609     if (isKnownNonNegative(Step))
9610       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9611 
9612     if (isKnownNonPositive(Step))
9613       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9614 
9615     return None;
9616   }
9617 }
9618 
9619 Optional<ScalarEvolution::LoopInvariantPredicate>
9620 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9621                                            const SCEV *LHS, const SCEV *RHS,
9622                                            const Loop *L) {
9623 
9624   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9625   if (!isLoopInvariant(RHS, L)) {
9626     if (!isLoopInvariant(LHS, L))
9627       return None;
9628 
9629     std::swap(LHS, RHS);
9630     Pred = ICmpInst::getSwappedPredicate(Pred);
9631   }
9632 
9633   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9634   if (!ArLHS || ArLHS->getLoop() != L)
9635     return None;
9636 
9637   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9638   if (!MonotonicType)
9639     return None;
9640   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9641   // true as the loop iterates, and the backedge is control dependent on
9642   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9643   //
9644   //   * if the predicate was false in the first iteration then the predicate
9645   //     is never evaluated again, since the loop exits without taking the
9646   //     backedge.
9647   //   * if the predicate was true in the first iteration then it will
9648   //     continue to be true for all future iterations since it is
9649   //     monotonically increasing.
9650   //
9651   // For both the above possibilities, we can replace the loop varying
9652   // predicate with its value on the first iteration of the loop (which is
9653   // loop invariant).
9654   //
9655   // A similar reasoning applies for a monotonically decreasing predicate, by
9656   // replacing true with false and false with true in the above two bullets.
9657   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9658   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9659 
9660   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9661     return None;
9662 
9663   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9664 }
9665 
9666 Optional<ScalarEvolution::LoopInvariantPredicate>
9667 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9668     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9669     const Instruction *Context, const SCEV *MaxIter) {
9670   // Try to prove the following set of facts:
9671   // - The predicate is monotonic in the iteration space.
9672   // - If the check does not fail on the 1st iteration:
9673   //   - No overflow will happen during first MaxIter iterations;
9674   //   - It will not fail on the MaxIter'th iteration.
9675   // If the check does fail on the 1st iteration, we leave the loop and no
9676   // other checks matter.
9677 
9678   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9679   if (!isLoopInvariant(RHS, L)) {
9680     if (!isLoopInvariant(LHS, L))
9681       return None;
9682 
9683     std::swap(LHS, RHS);
9684     Pred = ICmpInst::getSwappedPredicate(Pred);
9685   }
9686 
9687   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9688   if (!AR || AR->getLoop() != L)
9689     return None;
9690 
9691   // The predicate must be relational (i.e. <, <=, >=, >).
9692   if (!ICmpInst::isRelational(Pred))
9693     return None;
9694 
9695   // TODO: Support steps other than +/- 1.
9696   const SCEV *Step = AR->getStepRecurrence(*this);
9697   auto *One = getOne(Step->getType());
9698   auto *MinusOne = getNegativeSCEV(One);
9699   if (Step != One && Step != MinusOne)
9700     return None;
9701 
9702   // Type mismatch here means that MaxIter is potentially larger than max
9703   // unsigned value in start type, which mean we cannot prove no wrap for the
9704   // indvar.
9705   if (AR->getType() != MaxIter->getType())
9706     return None;
9707 
9708   // Value of IV on suggested last iteration.
9709   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9710   // Does it still meet the requirement?
9711   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
9712     return None;
9713   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9714   // not exceed max unsigned value of this type), this effectively proves
9715   // that there is no wrap during the iteration. To prove that there is no
9716   // signed/unsigned wrap, we need to check that
9717   // Start <= Last for step = 1 or Start >= Last for step = -1.
9718   ICmpInst::Predicate NoOverflowPred =
9719       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9720   if (Step == MinusOne)
9721     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9722   const SCEV *Start = AR->getStart();
9723   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9724     return None;
9725 
9726   // Everything is fine.
9727   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
9728 }
9729 
9730 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9731     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9732   if (HasSameValue(LHS, RHS))
9733     return ICmpInst::isTrueWhenEqual(Pred);
9734 
9735   // This code is split out from isKnownPredicate because it is called from
9736   // within isLoopEntryGuardedByCond.
9737 
9738   auto CheckRanges =
9739       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9740     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9741         .contains(RangeLHS);
9742   };
9743 
9744   // The check at the top of the function catches the case where the values are
9745   // known to be equal.
9746   if (Pred == CmpInst::ICMP_EQ)
9747     return false;
9748 
9749   if (Pred == CmpInst::ICMP_NE)
9750     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9751            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9752            isKnownNonZero(getMinusSCEV(LHS, RHS));
9753 
9754   if (CmpInst::isSigned(Pred))
9755     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9756 
9757   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9758 }
9759 
9760 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9761                                                     const SCEV *LHS,
9762                                                     const SCEV *RHS) {
9763   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9764   // Return Y via OutY.
9765   auto MatchBinaryAddToConst =
9766       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9767              SCEV::NoWrapFlags ExpectedFlags) {
9768     const SCEV *NonConstOp, *ConstOp;
9769     SCEV::NoWrapFlags FlagsPresent;
9770 
9771     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9772         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9773       return false;
9774 
9775     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9776     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9777   };
9778 
9779   APInt C;
9780 
9781   switch (Pred) {
9782   default:
9783     break;
9784 
9785   case ICmpInst::ICMP_SGE:
9786     std::swap(LHS, RHS);
9787     LLVM_FALLTHROUGH;
9788   case ICmpInst::ICMP_SLE:
9789     // X s<= (X + C)<nsw> if C >= 0
9790     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9791       return true;
9792 
9793     // (X + C)<nsw> s<= X if C <= 0
9794     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9795         !C.isStrictlyPositive())
9796       return true;
9797     break;
9798 
9799   case ICmpInst::ICMP_SGT:
9800     std::swap(LHS, RHS);
9801     LLVM_FALLTHROUGH;
9802   case ICmpInst::ICMP_SLT:
9803     // X s< (X + C)<nsw> if C > 0
9804     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9805         C.isStrictlyPositive())
9806       return true;
9807 
9808     // (X + C)<nsw> s< X if C < 0
9809     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9810       return true;
9811     break;
9812 
9813   case ICmpInst::ICMP_UGE:
9814     std::swap(LHS, RHS);
9815     LLVM_FALLTHROUGH;
9816   case ICmpInst::ICMP_ULE:
9817     // X u<= (X + C)<nuw> for any C
9818     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9819       return true;
9820     break;
9821 
9822   case ICmpInst::ICMP_UGT:
9823     std::swap(LHS, RHS);
9824     LLVM_FALLTHROUGH;
9825   case ICmpInst::ICMP_ULT:
9826     // X u< (X + C)<nuw> if C != 0
9827     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9828       return true;
9829     break;
9830   }
9831 
9832   return false;
9833 }
9834 
9835 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9836                                                    const SCEV *LHS,
9837                                                    const SCEV *RHS) {
9838   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9839     return false;
9840 
9841   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9842   // the stack can result in exponential time complexity.
9843   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9844 
9845   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9846   //
9847   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9848   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9849   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9850   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9851   // use isKnownPredicate later if needed.
9852   return isKnownNonNegative(RHS) &&
9853          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9854          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9855 }
9856 
9857 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9858                                         ICmpInst::Predicate Pred,
9859                                         const SCEV *LHS, const SCEV *RHS) {
9860   // No need to even try if we know the module has no guards.
9861   if (!HasGuards)
9862     return false;
9863 
9864   return any_of(*BB, [&](const Instruction &I) {
9865     using namespace llvm::PatternMatch;
9866 
9867     Value *Condition;
9868     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9869                          m_Value(Condition))) &&
9870            isImpliedCond(Pred, LHS, RHS, Condition, false);
9871   });
9872 }
9873 
9874 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9875 /// protected by a conditional between LHS and RHS.  This is used to
9876 /// to eliminate casts.
9877 bool
9878 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9879                                              ICmpInst::Predicate Pred,
9880                                              const SCEV *LHS, const SCEV *RHS) {
9881   // Interpret a null as meaning no loop, where there is obviously no guard
9882   // (interprocedural conditions notwithstanding).
9883   if (!L) return true;
9884 
9885   if (VerifyIR)
9886     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9887            "This cannot be done on broken IR!");
9888 
9889 
9890   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9891     return true;
9892 
9893   BasicBlock *Latch = L->getLoopLatch();
9894   if (!Latch)
9895     return false;
9896 
9897   BranchInst *LoopContinuePredicate =
9898     dyn_cast<BranchInst>(Latch->getTerminator());
9899   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9900       isImpliedCond(Pred, LHS, RHS,
9901                     LoopContinuePredicate->getCondition(),
9902                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9903     return true;
9904 
9905   // We don't want more than one activation of the following loops on the stack
9906   // -- that can lead to O(n!) time complexity.
9907   if (WalkingBEDominatingConds)
9908     return false;
9909 
9910   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9911 
9912   // See if we can exploit a trip count to prove the predicate.
9913   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9914   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9915   if (LatchBECount != getCouldNotCompute()) {
9916     // We know that Latch branches back to the loop header exactly
9917     // LatchBECount times.  This means the backdege condition at Latch is
9918     // equivalent to  "{0,+,1} u< LatchBECount".
9919     Type *Ty = LatchBECount->getType();
9920     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9921     const SCEV *LoopCounter =
9922       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9923     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9924                       LatchBECount))
9925       return true;
9926   }
9927 
9928   // Check conditions due to any @llvm.assume intrinsics.
9929   for (auto &AssumeVH : AC.assumptions()) {
9930     if (!AssumeVH)
9931       continue;
9932     auto *CI = cast<CallInst>(AssumeVH);
9933     if (!DT.dominates(CI, Latch->getTerminator()))
9934       continue;
9935 
9936     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9937       return true;
9938   }
9939 
9940   // If the loop is not reachable from the entry block, we risk running into an
9941   // infinite loop as we walk up into the dom tree.  These loops do not matter
9942   // anyway, so we just return a conservative answer when we see them.
9943   if (!DT.isReachableFromEntry(L->getHeader()))
9944     return false;
9945 
9946   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9947     return true;
9948 
9949   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9950        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9951     assert(DTN && "should reach the loop header before reaching the root!");
9952 
9953     BasicBlock *BB = DTN->getBlock();
9954     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9955       return true;
9956 
9957     BasicBlock *PBB = BB->getSinglePredecessor();
9958     if (!PBB)
9959       continue;
9960 
9961     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9962     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9963       continue;
9964 
9965     Value *Condition = ContinuePredicate->getCondition();
9966 
9967     // If we have an edge `E` within the loop body that dominates the only
9968     // latch, the condition guarding `E` also guards the backedge.  This
9969     // reasoning works only for loops with a single latch.
9970 
9971     BasicBlockEdge DominatingEdge(PBB, BB);
9972     if (DominatingEdge.isSingleEdge()) {
9973       // We're constructively (and conservatively) enumerating edges within the
9974       // loop body that dominate the latch.  The dominator tree better agree
9975       // with us on this:
9976       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9977 
9978       if (isImpliedCond(Pred, LHS, RHS, Condition,
9979                         BB != ContinuePredicate->getSuccessor(0)))
9980         return true;
9981     }
9982   }
9983 
9984   return false;
9985 }
9986 
9987 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
9988                                                      ICmpInst::Predicate Pred,
9989                                                      const SCEV *LHS,
9990                                                      const SCEV *RHS) {
9991   if (VerifyIR)
9992     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
9993            "This cannot be done on broken IR!");
9994 
9995   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9996     return true;
9997 
9998   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9999   // the facts (a >= b && a != b) separately. A typical situation is when the
10000   // non-strict comparison is known from ranges and non-equality is known from
10001   // dominating predicates. If we are proving strict comparison, we always try
10002   // to prove non-equality and non-strict comparison separately.
10003   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10004   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10005   bool ProvedNonStrictComparison = false;
10006   bool ProvedNonEquality = false;
10007 
10008   if (ProvingStrictComparison) {
10009     ProvedNonStrictComparison =
10010         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
10011     ProvedNonEquality =
10012         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
10013     if (ProvedNonStrictComparison && ProvedNonEquality)
10014       return true;
10015   }
10016 
10017   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10018   auto ProveViaGuard = [&](const BasicBlock *Block) {
10019     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10020       return true;
10021     if (ProvingStrictComparison) {
10022       if (!ProvedNonStrictComparison)
10023         ProvedNonStrictComparison =
10024             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
10025       if (!ProvedNonEquality)
10026         ProvedNonEquality =
10027             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
10028       if (ProvedNonStrictComparison && ProvedNonEquality)
10029         return true;
10030     }
10031     return false;
10032   };
10033 
10034   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10035   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10036     const Instruction *Context = &BB->front();
10037     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10038       return true;
10039     if (ProvingStrictComparison) {
10040       if (!ProvedNonStrictComparison)
10041         ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS,
10042                                                   Condition, Inverse, Context);
10043       if (!ProvedNonEquality)
10044         ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS,
10045                                           Condition, Inverse, Context);
10046       if (ProvedNonStrictComparison && ProvedNonEquality)
10047         return true;
10048     }
10049     return false;
10050   };
10051 
10052   // Starting at the block's predecessor, climb up the predecessor chain, as long
10053   // as there are predecessors that can be found that have unique successors
10054   // leading to the original block.
10055   const Loop *ContainingLoop = LI.getLoopFor(BB);
10056   const BasicBlock *PredBB;
10057   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10058     PredBB = ContainingLoop->getLoopPredecessor();
10059   else
10060     PredBB = BB->getSinglePredecessor();
10061   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10062        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10063     if (ProveViaGuard(Pair.first))
10064       return true;
10065 
10066     const BranchInst *LoopEntryPredicate =
10067         dyn_cast<BranchInst>(Pair.first->getTerminator());
10068     if (!LoopEntryPredicate ||
10069         LoopEntryPredicate->isUnconditional())
10070       continue;
10071 
10072     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10073                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10074       return true;
10075   }
10076 
10077   // Check conditions due to any @llvm.assume intrinsics.
10078   for (auto &AssumeVH : AC.assumptions()) {
10079     if (!AssumeVH)
10080       continue;
10081     auto *CI = cast<CallInst>(AssumeVH);
10082     if (!DT.dominates(CI, BB))
10083       continue;
10084 
10085     if (ProveViaCond(CI->getArgOperand(0), false))
10086       return true;
10087   }
10088 
10089   return false;
10090 }
10091 
10092 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10093                                                ICmpInst::Predicate Pred,
10094                                                const SCEV *LHS,
10095                                                const SCEV *RHS) {
10096   // Interpret a null as meaning no loop, where there is obviously no guard
10097   // (interprocedural conditions notwithstanding).
10098   if (!L)
10099     return false;
10100 
10101   // Both LHS and RHS must be available at loop entry.
10102   assert(isAvailableAtLoopEntry(LHS, L) &&
10103          "LHS is not available at Loop Entry");
10104   assert(isAvailableAtLoopEntry(RHS, L) &&
10105          "RHS is not available at Loop Entry");
10106   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10107 }
10108 
10109 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10110                                     const SCEV *RHS,
10111                                     const Value *FoundCondValue, bool Inverse,
10112                                     const Instruction *Context) {
10113   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10114     return false;
10115 
10116   auto ClearOnExit =
10117       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10118 
10119   // Recursively handle And and Or conditions.
10120   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
10121     if (BO->getOpcode() == Instruction::And) {
10122       if (!Inverse)
10123         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10124                              Context) ||
10125                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10126                              Context);
10127     } else if (BO->getOpcode() == Instruction::Or) {
10128       if (Inverse)
10129         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10130                              Context) ||
10131                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10132                              Context);
10133     }
10134   }
10135 
10136   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10137   if (!ICI) return false;
10138 
10139   // Now that we found a conditional branch that dominates the loop or controls
10140   // the loop latch. Check to see if it is the comparison we are looking for.
10141   ICmpInst::Predicate FoundPred;
10142   if (Inverse)
10143     FoundPred = ICI->getInversePredicate();
10144   else
10145     FoundPred = ICI->getPredicate();
10146 
10147   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10148   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10149 
10150   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10151 }
10152 
10153 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10154                                     const SCEV *RHS,
10155                                     ICmpInst::Predicate FoundPred,
10156                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10157                                     const Instruction *Context) {
10158   // Balance the types.
10159   if (getTypeSizeInBits(LHS->getType()) <
10160       getTypeSizeInBits(FoundLHS->getType())) {
10161     // For unsigned and equality predicates, try to prove that both found
10162     // operands fit into narrow unsigned range. If so, try to prove facts in
10163     // narrow types.
10164     if (!CmpInst::isSigned(FoundPred)) {
10165       auto *NarrowType = LHS->getType();
10166       auto *WideType = FoundLHS->getType();
10167       auto BitWidth = getTypeSizeInBits(NarrowType);
10168       const SCEV *MaxValue = getZeroExtendExpr(
10169           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10170       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10171           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10172         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10173         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10174         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10175                                        TruncFoundRHS, Context))
10176           return true;
10177       }
10178     }
10179 
10180     if (CmpInst::isSigned(Pred)) {
10181       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10182       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10183     } else {
10184       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10185       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10186     }
10187   } else if (getTypeSizeInBits(LHS->getType()) >
10188       getTypeSizeInBits(FoundLHS->getType())) {
10189     if (CmpInst::isSigned(FoundPred)) {
10190       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10191       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10192     } else {
10193       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10194       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10195     }
10196   }
10197   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10198                                     FoundRHS, Context);
10199 }
10200 
10201 bool ScalarEvolution::isImpliedCondBalancedTypes(
10202     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10203     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10204     const Instruction *Context) {
10205   assert(getTypeSizeInBits(LHS->getType()) ==
10206              getTypeSizeInBits(FoundLHS->getType()) &&
10207          "Types should be balanced!");
10208   // Canonicalize the query to match the way instcombine will have
10209   // canonicalized the comparison.
10210   if (SimplifyICmpOperands(Pred, LHS, RHS))
10211     if (LHS == RHS)
10212       return CmpInst::isTrueWhenEqual(Pred);
10213   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10214     if (FoundLHS == FoundRHS)
10215       return CmpInst::isFalseWhenEqual(FoundPred);
10216 
10217   // Check to see if we can make the LHS or RHS match.
10218   if (LHS == FoundRHS || RHS == FoundLHS) {
10219     if (isa<SCEVConstant>(RHS)) {
10220       std::swap(FoundLHS, FoundRHS);
10221       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10222     } else {
10223       std::swap(LHS, RHS);
10224       Pred = ICmpInst::getSwappedPredicate(Pred);
10225     }
10226   }
10227 
10228   // Check whether the found predicate is the same as the desired predicate.
10229   if (FoundPred == Pred)
10230     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10231 
10232   // Check whether swapping the found predicate makes it the same as the
10233   // desired predicate.
10234   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10235     if (isa<SCEVConstant>(RHS))
10236       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10237     else
10238       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS,
10239                                    LHS, FoundLHS, FoundRHS, Context);
10240   }
10241 
10242   // Unsigned comparison is the same as signed comparison when both the operands
10243   // are non-negative.
10244   if (CmpInst::isUnsigned(FoundPred) &&
10245       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10246       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10247     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10248 
10249   // Check if we can make progress by sharpening ranges.
10250   if (FoundPred == ICmpInst::ICMP_NE &&
10251       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10252 
10253     const SCEVConstant *C = nullptr;
10254     const SCEV *V = nullptr;
10255 
10256     if (isa<SCEVConstant>(FoundLHS)) {
10257       C = cast<SCEVConstant>(FoundLHS);
10258       V = FoundRHS;
10259     } else {
10260       C = cast<SCEVConstant>(FoundRHS);
10261       V = FoundLHS;
10262     }
10263 
10264     // The guarding predicate tells us that C != V. If the known range
10265     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10266     // range we consider has to correspond to same signedness as the
10267     // predicate we're interested in folding.
10268 
10269     APInt Min = ICmpInst::isSigned(Pred) ?
10270         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10271 
10272     if (Min == C->getAPInt()) {
10273       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10274       // This is true even if (Min + 1) wraps around -- in case of
10275       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10276 
10277       APInt SharperMin = Min + 1;
10278 
10279       switch (Pred) {
10280         case ICmpInst::ICMP_SGE:
10281         case ICmpInst::ICMP_UGE:
10282           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10283           // RHS, we're done.
10284           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10285                                     Context))
10286             return true;
10287           LLVM_FALLTHROUGH;
10288 
10289         case ICmpInst::ICMP_SGT:
10290         case ICmpInst::ICMP_UGT:
10291           // We know from the range information that (V `Pred` Min ||
10292           // V == Min).  We know from the guarding condition that !(V
10293           // == Min).  This gives us
10294           //
10295           //       V `Pred` Min || V == Min && !(V == Min)
10296           //   =>  V `Pred` Min
10297           //
10298           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10299 
10300           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10301                                     Context))
10302             return true;
10303           break;
10304 
10305         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10306         case ICmpInst::ICMP_SLE:
10307         case ICmpInst::ICMP_ULE:
10308           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10309                                     LHS, V, getConstant(SharperMin), Context))
10310             return true;
10311           LLVM_FALLTHROUGH;
10312 
10313         case ICmpInst::ICMP_SLT:
10314         case ICmpInst::ICMP_ULT:
10315           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10316                                     LHS, V, getConstant(Min), Context))
10317             return true;
10318           break;
10319 
10320         default:
10321           // No change
10322           break;
10323       }
10324     }
10325   }
10326 
10327   // Check whether the actual condition is beyond sufficient.
10328   if (FoundPred == ICmpInst::ICMP_EQ)
10329     if (ICmpInst::isTrueWhenEqual(Pred))
10330       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10331         return true;
10332   if (Pred == ICmpInst::ICMP_NE)
10333     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10334       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10335                                 Context))
10336         return true;
10337 
10338   // Otherwise assume the worst.
10339   return false;
10340 }
10341 
10342 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10343                                      const SCEV *&L, const SCEV *&R,
10344                                      SCEV::NoWrapFlags &Flags) {
10345   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10346   if (!AE || AE->getNumOperands() != 2)
10347     return false;
10348 
10349   L = AE->getOperand(0);
10350   R = AE->getOperand(1);
10351   Flags = AE->getNoWrapFlags();
10352   return true;
10353 }
10354 
10355 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10356                                                            const SCEV *Less) {
10357   // We avoid subtracting expressions here because this function is usually
10358   // fairly deep in the call stack (i.e. is called many times).
10359 
10360   // X - X = 0.
10361   if (More == Less)
10362     return APInt(getTypeSizeInBits(More->getType()), 0);
10363 
10364   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10365     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10366     const auto *MAR = cast<SCEVAddRecExpr>(More);
10367 
10368     if (LAR->getLoop() != MAR->getLoop())
10369       return None;
10370 
10371     // We look at affine expressions only; not for correctness but to keep
10372     // getStepRecurrence cheap.
10373     if (!LAR->isAffine() || !MAR->isAffine())
10374       return None;
10375 
10376     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10377       return None;
10378 
10379     Less = LAR->getStart();
10380     More = MAR->getStart();
10381 
10382     // fall through
10383   }
10384 
10385   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10386     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10387     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10388     return M - L;
10389   }
10390 
10391   SCEV::NoWrapFlags Flags;
10392   const SCEV *LLess = nullptr, *RLess = nullptr;
10393   const SCEV *LMore = nullptr, *RMore = nullptr;
10394   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10395   // Compare (X + C1) vs X.
10396   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10397     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10398       if (RLess == More)
10399         return -(C1->getAPInt());
10400 
10401   // Compare X vs (X + C2).
10402   if (splitBinaryAdd(More, LMore, RMore, Flags))
10403     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10404       if (RMore == Less)
10405         return C2->getAPInt();
10406 
10407   // Compare (X + C1) vs (X + C2).
10408   if (C1 && C2 && RLess == RMore)
10409     return C2->getAPInt() - C1->getAPInt();
10410 
10411   return None;
10412 }
10413 
10414 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10415     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10416     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10417   // Try to recognize the following pattern:
10418   //
10419   //   FoundRHS = ...
10420   // ...
10421   // loop:
10422   //   FoundLHS = {Start,+,W}
10423   // context_bb: // Basic block from the same loop
10424   //   known(Pred, FoundLHS, FoundRHS)
10425   //
10426   // If some predicate is known in the context of a loop, it is also known on
10427   // each iteration of this loop, including the first iteration. Therefore, in
10428   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10429   // prove the original pred using this fact.
10430   if (!Context)
10431     return false;
10432   const BasicBlock *ContextBB = Context->getParent();
10433   // Make sure AR varies in the context block.
10434   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10435     const Loop *L = AR->getLoop();
10436     // Make sure that context belongs to the loop and executes on 1st iteration
10437     // (if it ever executes at all).
10438     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10439       return false;
10440     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10441       return false;
10442     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10443   }
10444 
10445   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10446     const Loop *L = AR->getLoop();
10447     // Make sure that context belongs to the loop and executes on 1st iteration
10448     // (if it ever executes at all).
10449     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10450       return false;
10451     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10452       return false;
10453     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10454   }
10455 
10456   return false;
10457 }
10458 
10459 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10460     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10461     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10462   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10463     return false;
10464 
10465   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10466   if (!AddRecLHS)
10467     return false;
10468 
10469   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10470   if (!AddRecFoundLHS)
10471     return false;
10472 
10473   // We'd like to let SCEV reason about control dependencies, so we constrain
10474   // both the inequalities to be about add recurrences on the same loop.  This
10475   // way we can use isLoopEntryGuardedByCond later.
10476 
10477   const Loop *L = AddRecFoundLHS->getLoop();
10478   if (L != AddRecLHS->getLoop())
10479     return false;
10480 
10481   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10482   //
10483   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10484   //                                                                  ... (2)
10485   //
10486   // Informal proof for (2), assuming (1) [*]:
10487   //
10488   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10489   //
10490   // Then
10491   //
10492   //       FoundLHS s< FoundRHS s< INT_MIN - C
10493   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10494   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10495   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10496   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10497   // <=>  FoundLHS + C s< FoundRHS + C
10498   //
10499   // [*]: (1) can be proved by ruling out overflow.
10500   //
10501   // [**]: This can be proved by analyzing all the four possibilities:
10502   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10503   //    (A s>= 0, B s>= 0).
10504   //
10505   // Note:
10506   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10507   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10508   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10509   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10510   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10511   // C)".
10512 
10513   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10514   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10515   if (!LDiff || !RDiff || *LDiff != *RDiff)
10516     return false;
10517 
10518   if (LDiff->isMinValue())
10519     return true;
10520 
10521   APInt FoundRHSLimit;
10522 
10523   if (Pred == CmpInst::ICMP_ULT) {
10524     FoundRHSLimit = -(*RDiff);
10525   } else {
10526     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10527     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10528   }
10529 
10530   // Try to prove (1) or (2), as needed.
10531   return isAvailableAtLoopEntry(FoundRHS, L) &&
10532          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10533                                   getConstant(FoundRHSLimit));
10534 }
10535 
10536 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10537                                         const SCEV *LHS, const SCEV *RHS,
10538                                         const SCEV *FoundLHS,
10539                                         const SCEV *FoundRHS, unsigned Depth) {
10540   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10541 
10542   auto ClearOnExit = make_scope_exit([&]() {
10543     if (LPhi) {
10544       bool Erased = PendingMerges.erase(LPhi);
10545       assert(Erased && "Failed to erase LPhi!");
10546       (void)Erased;
10547     }
10548     if (RPhi) {
10549       bool Erased = PendingMerges.erase(RPhi);
10550       assert(Erased && "Failed to erase RPhi!");
10551       (void)Erased;
10552     }
10553   });
10554 
10555   // Find respective Phis and check that they are not being pending.
10556   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10557     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10558       if (!PendingMerges.insert(Phi).second)
10559         return false;
10560       LPhi = Phi;
10561     }
10562   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10563     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10564       // If we detect a loop of Phi nodes being processed by this method, for
10565       // example:
10566       //
10567       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10568       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10569       //
10570       // we don't want to deal with a case that complex, so return conservative
10571       // answer false.
10572       if (!PendingMerges.insert(Phi).second)
10573         return false;
10574       RPhi = Phi;
10575     }
10576 
10577   // If none of LHS, RHS is a Phi, nothing to do here.
10578   if (!LPhi && !RPhi)
10579     return false;
10580 
10581   // If there is a SCEVUnknown Phi we are interested in, make it left.
10582   if (!LPhi) {
10583     std::swap(LHS, RHS);
10584     std::swap(FoundLHS, FoundRHS);
10585     std::swap(LPhi, RPhi);
10586     Pred = ICmpInst::getSwappedPredicate(Pred);
10587   }
10588 
10589   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10590   const BasicBlock *LBB = LPhi->getParent();
10591   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10592 
10593   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10594     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10595            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10596            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10597   };
10598 
10599   if (RPhi && RPhi->getParent() == LBB) {
10600     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10601     // If we compare two Phis from the same block, and for each entry block
10602     // the predicate is true for incoming values from this block, then the
10603     // predicate is also true for the Phis.
10604     for (const BasicBlock *IncBB : predecessors(LBB)) {
10605       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10606       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10607       if (!ProvedEasily(L, R))
10608         return false;
10609     }
10610   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10611     // Case two: RHS is also a Phi from the same basic block, and it is an
10612     // AddRec. It means that there is a loop which has both AddRec and Unknown
10613     // PHIs, for it we can compare incoming values of AddRec from above the loop
10614     // and latch with their respective incoming values of LPhi.
10615     // TODO: Generalize to handle loops with many inputs in a header.
10616     if (LPhi->getNumIncomingValues() != 2) return false;
10617 
10618     auto *RLoop = RAR->getLoop();
10619     auto *Predecessor = RLoop->getLoopPredecessor();
10620     assert(Predecessor && "Loop with AddRec with no predecessor?");
10621     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10622     if (!ProvedEasily(L1, RAR->getStart()))
10623       return false;
10624     auto *Latch = RLoop->getLoopLatch();
10625     assert(Latch && "Loop with AddRec with no latch?");
10626     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10627     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10628       return false;
10629   } else {
10630     // In all other cases go over inputs of LHS and compare each of them to RHS,
10631     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10632     // At this point RHS is either a non-Phi, or it is a Phi from some block
10633     // different from LBB.
10634     for (const BasicBlock *IncBB : predecessors(LBB)) {
10635       // Check that RHS is available in this block.
10636       if (!dominates(RHS, IncBB))
10637         return false;
10638       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10639       if (!ProvedEasily(L, RHS))
10640         return false;
10641     }
10642   }
10643   return true;
10644 }
10645 
10646 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10647                                             const SCEV *LHS, const SCEV *RHS,
10648                                             const SCEV *FoundLHS,
10649                                             const SCEV *FoundRHS,
10650                                             const Instruction *Context) {
10651   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10652     return true;
10653 
10654   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10655     return true;
10656 
10657   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10658                                           Context))
10659     return true;
10660 
10661   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10662                                      FoundLHS, FoundRHS) ||
10663          // ~x < ~y --> x > y
10664          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10665                                      getNotSCEV(FoundRHS),
10666                                      getNotSCEV(FoundLHS));
10667 }
10668 
10669 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10670 template <typename MinMaxExprType>
10671 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10672                                  const SCEV *Candidate) {
10673   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10674   if (!MinMaxExpr)
10675     return false;
10676 
10677   return is_contained(MinMaxExpr->operands(), Candidate);
10678 }
10679 
10680 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10681                                            ICmpInst::Predicate Pred,
10682                                            const SCEV *LHS, const SCEV *RHS) {
10683   // If both sides are affine addrecs for the same loop, with equal
10684   // steps, and we know the recurrences don't wrap, then we only
10685   // need to check the predicate on the starting values.
10686 
10687   if (!ICmpInst::isRelational(Pred))
10688     return false;
10689 
10690   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10691   if (!LAR)
10692     return false;
10693   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10694   if (!RAR)
10695     return false;
10696   if (LAR->getLoop() != RAR->getLoop())
10697     return false;
10698   if (!LAR->isAffine() || !RAR->isAffine())
10699     return false;
10700 
10701   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10702     return false;
10703 
10704   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10705                          SCEV::FlagNSW : SCEV::FlagNUW;
10706   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10707     return false;
10708 
10709   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10710 }
10711 
10712 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10713 /// expression?
10714 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10715                                         ICmpInst::Predicate Pred,
10716                                         const SCEV *LHS, const SCEV *RHS) {
10717   switch (Pred) {
10718   default:
10719     return false;
10720 
10721   case ICmpInst::ICMP_SGE:
10722     std::swap(LHS, RHS);
10723     LLVM_FALLTHROUGH;
10724   case ICmpInst::ICMP_SLE:
10725     return
10726         // min(A, ...) <= A
10727         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10728         // A <= max(A, ...)
10729         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10730 
10731   case ICmpInst::ICMP_UGE:
10732     std::swap(LHS, RHS);
10733     LLVM_FALLTHROUGH;
10734   case ICmpInst::ICMP_ULE:
10735     return
10736         // min(A, ...) <= A
10737         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10738         // A <= max(A, ...)
10739         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10740   }
10741 
10742   llvm_unreachable("covered switch fell through?!");
10743 }
10744 
10745 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10746                                              const SCEV *LHS, const SCEV *RHS,
10747                                              const SCEV *FoundLHS,
10748                                              const SCEV *FoundRHS,
10749                                              unsigned Depth) {
10750   assert(getTypeSizeInBits(LHS->getType()) ==
10751              getTypeSizeInBits(RHS->getType()) &&
10752          "LHS and RHS have different sizes?");
10753   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10754              getTypeSizeInBits(FoundRHS->getType()) &&
10755          "FoundLHS and FoundRHS have different sizes?");
10756   // We want to avoid hurting the compile time with analysis of too big trees.
10757   if (Depth > MaxSCEVOperationsImplicationDepth)
10758     return false;
10759 
10760   // We only want to work with GT comparison so far.
10761   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10762     Pred = CmpInst::getSwappedPredicate(Pred);
10763     std::swap(LHS, RHS);
10764     std::swap(FoundLHS, FoundRHS);
10765   }
10766 
10767   // For unsigned, try to reduce it to corresponding signed comparison.
10768   if (Pred == ICmpInst::ICMP_UGT)
10769     // We can replace unsigned predicate with its signed counterpart if all
10770     // involved values are non-negative.
10771     // TODO: We could have better support for unsigned.
10772     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10773       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10774       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10775       // use this fact to prove that LHS and RHS are non-negative.
10776       const SCEV *MinusOne = getMinusOne(LHS->getType());
10777       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10778                                 FoundRHS) &&
10779           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10780                                 FoundRHS))
10781         Pred = ICmpInst::ICMP_SGT;
10782     }
10783 
10784   if (Pred != ICmpInst::ICMP_SGT)
10785     return false;
10786 
10787   auto GetOpFromSExt = [&](const SCEV *S) {
10788     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10789       return Ext->getOperand();
10790     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10791     // the constant in some cases.
10792     return S;
10793   };
10794 
10795   // Acquire values from extensions.
10796   auto *OrigLHS = LHS;
10797   auto *OrigFoundLHS = FoundLHS;
10798   LHS = GetOpFromSExt(LHS);
10799   FoundLHS = GetOpFromSExt(FoundLHS);
10800 
10801   // Is the SGT predicate can be proved trivially or using the found context.
10802   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10803     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10804            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10805                                   FoundRHS, Depth + 1);
10806   };
10807 
10808   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10809     // We want to avoid creation of any new non-constant SCEV. Since we are
10810     // going to compare the operands to RHS, we should be certain that we don't
10811     // need any size extensions for this. So let's decline all cases when the
10812     // sizes of types of LHS and RHS do not match.
10813     // TODO: Maybe try to get RHS from sext to catch more cases?
10814     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10815       return false;
10816 
10817     // Should not overflow.
10818     if (!LHSAddExpr->hasNoSignedWrap())
10819       return false;
10820 
10821     auto *LL = LHSAddExpr->getOperand(0);
10822     auto *LR = LHSAddExpr->getOperand(1);
10823     auto *MinusOne = getMinusOne(RHS->getType());
10824 
10825     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10826     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10827       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10828     };
10829     // Try to prove the following rule:
10830     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10831     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10832     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10833       return true;
10834   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10835     Value *LL, *LR;
10836     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10837 
10838     using namespace llvm::PatternMatch;
10839 
10840     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10841       // Rules for division.
10842       // We are going to perform some comparisons with Denominator and its
10843       // derivative expressions. In general case, creating a SCEV for it may
10844       // lead to a complex analysis of the entire graph, and in particular it
10845       // can request trip count recalculation for the same loop. This would
10846       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10847       // this, we only want to create SCEVs that are constants in this section.
10848       // So we bail if Denominator is not a constant.
10849       if (!isa<ConstantInt>(LR))
10850         return false;
10851 
10852       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10853 
10854       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10855       // then a SCEV for the numerator already exists and matches with FoundLHS.
10856       auto *Numerator = getExistingSCEV(LL);
10857       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10858         return false;
10859 
10860       // Make sure that the numerator matches with FoundLHS and the denominator
10861       // is positive.
10862       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10863         return false;
10864 
10865       auto *DTy = Denominator->getType();
10866       auto *FRHSTy = FoundRHS->getType();
10867       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10868         // One of types is a pointer and another one is not. We cannot extend
10869         // them properly to a wider type, so let us just reject this case.
10870         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10871         // to avoid this check.
10872         return false;
10873 
10874       // Given that:
10875       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10876       auto *WTy = getWiderType(DTy, FRHSTy);
10877       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10878       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10879 
10880       // Try to prove the following rule:
10881       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10882       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10883       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10884       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10885       if (isKnownNonPositive(RHS) &&
10886           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10887         return true;
10888 
10889       // Try to prove the following rule:
10890       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10891       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10892       // If we divide it by Denominator > 2, then:
10893       // 1. If FoundLHS is negative, then the result is 0.
10894       // 2. If FoundLHS is non-negative, then the result is non-negative.
10895       // Anyways, the result is non-negative.
10896       auto *MinusOne = getMinusOne(WTy);
10897       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10898       if (isKnownNegative(RHS) &&
10899           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10900         return true;
10901     }
10902   }
10903 
10904   // If our expression contained SCEVUnknown Phis, and we split it down and now
10905   // need to prove something for them, try to prove the predicate for every
10906   // possible incoming values of those Phis.
10907   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10908     return true;
10909 
10910   return false;
10911 }
10912 
10913 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10914                                         const SCEV *LHS, const SCEV *RHS) {
10915   // zext x u<= sext x, sext x s<= zext x
10916   switch (Pred) {
10917   case ICmpInst::ICMP_SGE:
10918     std::swap(LHS, RHS);
10919     LLVM_FALLTHROUGH;
10920   case ICmpInst::ICMP_SLE: {
10921     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
10922     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10923     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10924     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10925       return true;
10926     break;
10927   }
10928   case ICmpInst::ICMP_UGE:
10929     std::swap(LHS, RHS);
10930     LLVM_FALLTHROUGH;
10931   case ICmpInst::ICMP_ULE: {
10932     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
10933     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10934     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10935     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10936       return true;
10937     break;
10938   }
10939   default:
10940     break;
10941   };
10942   return false;
10943 }
10944 
10945 bool
10946 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10947                                            const SCEV *LHS, const SCEV *RHS) {
10948   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10949          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10950          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10951          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10952          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10953 }
10954 
10955 bool
10956 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10957                                              const SCEV *LHS, const SCEV *RHS,
10958                                              const SCEV *FoundLHS,
10959                                              const SCEV *FoundRHS) {
10960   switch (Pred) {
10961   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10962   case ICmpInst::ICMP_EQ:
10963   case ICmpInst::ICMP_NE:
10964     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10965       return true;
10966     break;
10967   case ICmpInst::ICMP_SLT:
10968   case ICmpInst::ICMP_SLE:
10969     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10970         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10971       return true;
10972     break;
10973   case ICmpInst::ICMP_SGT:
10974   case ICmpInst::ICMP_SGE:
10975     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10976         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10977       return true;
10978     break;
10979   case ICmpInst::ICMP_ULT:
10980   case ICmpInst::ICMP_ULE:
10981     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10982         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10983       return true;
10984     break;
10985   case ICmpInst::ICMP_UGT:
10986   case ICmpInst::ICMP_UGE:
10987     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10988         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10989       return true;
10990     break;
10991   }
10992 
10993   // Maybe it can be proved via operations?
10994   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10995     return true;
10996 
10997   return false;
10998 }
10999 
11000 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11001                                                      const SCEV *LHS,
11002                                                      const SCEV *RHS,
11003                                                      const SCEV *FoundLHS,
11004                                                      const SCEV *FoundRHS) {
11005   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11006     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11007     // reduce the compile time impact of this optimization.
11008     return false;
11009 
11010   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11011   if (!Addend)
11012     return false;
11013 
11014   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11015 
11016   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11017   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11018   ConstantRange FoundLHSRange =
11019       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
11020 
11021   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11022   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11023 
11024   // We can also compute the range of values for `LHS` that satisfy the
11025   // consequent, "`LHS` `Pred` `RHS`":
11026   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11027   ConstantRange SatisfyingLHSRange =
11028       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
11029 
11030   // The antecedent implies the consequent if every value of `LHS` that
11031   // satisfies the antecedent also satisfies the consequent.
11032   return SatisfyingLHSRange.contains(LHSRange);
11033 }
11034 
11035 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11036                                          bool IsSigned, bool NoWrap) {
11037   assert(isKnownPositive(Stride) && "Positive stride expected!");
11038 
11039   if (NoWrap) return false;
11040 
11041   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11042   const SCEV *One = getOne(Stride->getType());
11043 
11044   if (IsSigned) {
11045     APInt MaxRHS = getSignedRangeMax(RHS);
11046     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11047     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11048 
11049     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11050     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11051   }
11052 
11053   APInt MaxRHS = getUnsignedRangeMax(RHS);
11054   APInt MaxValue = APInt::getMaxValue(BitWidth);
11055   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11056 
11057   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11058   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11059 }
11060 
11061 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11062                                          bool IsSigned, bool NoWrap) {
11063   if (NoWrap) return false;
11064 
11065   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11066   const SCEV *One = getOne(Stride->getType());
11067 
11068   if (IsSigned) {
11069     APInt MinRHS = getSignedRangeMin(RHS);
11070     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11071     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11072 
11073     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11074     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11075   }
11076 
11077   APInt MinRHS = getUnsignedRangeMin(RHS);
11078   APInt MinValue = APInt::getMinValue(BitWidth);
11079   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11080 
11081   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11082   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11083 }
11084 
11085 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
11086                                             bool Equality) {
11087   const SCEV *One = getOne(Step->getType());
11088   Delta = Equality ? getAddExpr(Delta, Step)
11089                    : getAddExpr(Delta, getMinusSCEV(Step, One));
11090   return getUDivExpr(Delta, Step);
11091 }
11092 
11093 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11094                                                     const SCEV *Stride,
11095                                                     const SCEV *End,
11096                                                     unsigned BitWidth,
11097                                                     bool IsSigned) {
11098 
11099   assert(!isKnownNonPositive(Stride) &&
11100          "Stride is expected strictly positive!");
11101   // Calculate the maximum backedge count based on the range of values
11102   // permitted by Start, End, and Stride.
11103   const SCEV *MaxBECount;
11104   APInt MinStart =
11105       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11106 
11107   APInt StrideForMaxBECount =
11108       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11109 
11110   // We already know that the stride is positive, so we paper over conservatism
11111   // in our range computation by forcing StrideForMaxBECount to be at least one.
11112   // In theory this is unnecessary, but we expect MaxBECount to be a
11113   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11114   // is nothing to constant fold it to).
11115   APInt One(BitWidth, 1, IsSigned);
11116   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11117 
11118   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11119                             : APInt::getMaxValue(BitWidth);
11120   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11121 
11122   // Although End can be a MAX expression we estimate MaxEnd considering only
11123   // the case End = RHS of the loop termination condition. This is safe because
11124   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11125   // taken count.
11126   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11127                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11128 
11129   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11130                               getConstant(StrideForMaxBECount) /* Step */,
11131                               false /* Equality */);
11132 
11133   return MaxBECount;
11134 }
11135 
11136 ScalarEvolution::ExitLimit
11137 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11138                                   const Loop *L, bool IsSigned,
11139                                   bool ControlsExit, bool AllowPredicates) {
11140   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11141 
11142   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11143   bool PredicatedIV = false;
11144 
11145   if (!IV && AllowPredicates) {
11146     // Try to make this an AddRec using runtime tests, in the first X
11147     // iterations of this loop, where X is the SCEV expression found by the
11148     // algorithm below.
11149     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11150     PredicatedIV = true;
11151   }
11152 
11153   // Avoid weird loops
11154   if (!IV || IV->getLoop() != L || !IV->isAffine())
11155     return getCouldNotCompute();
11156 
11157   bool NoWrap = ControlsExit &&
11158                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11159 
11160   const SCEV *Stride = IV->getStepRecurrence(*this);
11161 
11162   bool PositiveStride = isKnownPositive(Stride);
11163 
11164   // Avoid negative or zero stride values.
11165   if (!PositiveStride) {
11166     // We can compute the correct backedge taken count for loops with unknown
11167     // strides if we can prove that the loop is not an infinite loop with side
11168     // effects. Here's the loop structure we are trying to handle -
11169     //
11170     // i = start
11171     // do {
11172     //   A[i] = i;
11173     //   i += s;
11174     // } while (i < end);
11175     //
11176     // The backedge taken count for such loops is evaluated as -
11177     // (max(end, start + stride) - start - 1) /u stride
11178     //
11179     // The additional preconditions that we need to check to prove correctness
11180     // of the above formula is as follows -
11181     //
11182     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11183     //    NoWrap flag).
11184     // b) loop is single exit with no side effects.
11185     //
11186     //
11187     // Precondition a) implies that if the stride is negative, this is a single
11188     // trip loop. The backedge taken count formula reduces to zero in this case.
11189     //
11190     // Precondition b) implies that the unknown stride cannot be zero otherwise
11191     // we have UB.
11192     //
11193     // The positive stride case is the same as isKnownPositive(Stride) returning
11194     // true (original behavior of the function).
11195     //
11196     // We want to make sure that the stride is truly unknown as there are edge
11197     // cases where ScalarEvolution propagates no wrap flags to the
11198     // post-increment/decrement IV even though the increment/decrement operation
11199     // itself is wrapping. The computed backedge taken count may be wrong in
11200     // such cases. This is prevented by checking that the stride is not known to
11201     // be either positive or non-positive. For example, no wrap flags are
11202     // propagated to the post-increment IV of this loop with a trip count of 2 -
11203     //
11204     // unsigned char i;
11205     // for(i=127; i<128; i+=129)
11206     //   A[i] = i;
11207     //
11208     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11209         !loopHasNoSideEffects(L))
11210       return getCouldNotCompute();
11211   } else if (!Stride->isOne() &&
11212              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11213     // Avoid proven overflow cases: this will ensure that the backedge taken
11214     // count will not generate any unsigned overflow. Relaxed no-overflow
11215     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11216     // undefined behaviors like the case of C language.
11217     return getCouldNotCompute();
11218 
11219   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11220                                       : ICmpInst::ICMP_ULT;
11221   const SCEV *Start = IV->getStart();
11222   const SCEV *End = RHS;
11223   // When the RHS is not invariant, we do not know the end bound of the loop and
11224   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11225   // calculate the MaxBECount, given the start, stride and max value for the end
11226   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11227   // checked above).
11228   if (!isLoopInvariant(RHS, L)) {
11229     const SCEV *MaxBECount = computeMaxBECountForLT(
11230         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11231     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11232                      false /*MaxOrZero*/, Predicates);
11233   }
11234   // If the backedge is taken at least once, then it will be taken
11235   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11236   // is the LHS value of the less-than comparison the first time it is evaluated
11237   // and End is the RHS.
11238   const SCEV *BECountIfBackedgeTaken =
11239     computeBECount(getMinusSCEV(End, Start), Stride, false);
11240   // If the loop entry is guarded by the result of the backedge test of the
11241   // first loop iteration, then we know the backedge will be taken at least
11242   // once and so the backedge taken count is as above. If not then we use the
11243   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11244   // as if the backedge is taken at least once max(End,Start) is End and so the
11245   // result is as above, and if not max(End,Start) is Start so we get a backedge
11246   // count of zero.
11247   const SCEV *BECount;
11248   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11249     BECount = BECountIfBackedgeTaken;
11250   else {
11251     // If we know that RHS >= Start in the context of loop, then we know that
11252     // max(RHS, Start) = RHS at this point.
11253     if (isLoopEntryGuardedByCond(
11254             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11255       End = RHS;
11256     else
11257       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11258     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11259   }
11260 
11261   const SCEV *MaxBECount;
11262   bool MaxOrZero = false;
11263   if (isa<SCEVConstant>(BECount))
11264     MaxBECount = BECount;
11265   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11266     // If we know exactly how many times the backedge will be taken if it's
11267     // taken at least once, then the backedge count will either be that or
11268     // zero.
11269     MaxBECount = BECountIfBackedgeTaken;
11270     MaxOrZero = true;
11271   } else {
11272     MaxBECount = computeMaxBECountForLT(
11273         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11274   }
11275 
11276   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11277       !isa<SCEVCouldNotCompute>(BECount))
11278     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11279 
11280   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11281 }
11282 
11283 ScalarEvolution::ExitLimit
11284 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11285                                      const Loop *L, bool IsSigned,
11286                                      bool ControlsExit, bool AllowPredicates) {
11287   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11288   // We handle only IV > Invariant
11289   if (!isLoopInvariant(RHS, L))
11290     return getCouldNotCompute();
11291 
11292   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11293   if (!IV && AllowPredicates)
11294     // Try to make this an AddRec using runtime tests, in the first X
11295     // iterations of this loop, where X is the SCEV expression found by the
11296     // algorithm below.
11297     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11298 
11299   // Avoid weird loops
11300   if (!IV || IV->getLoop() != L || !IV->isAffine())
11301     return getCouldNotCompute();
11302 
11303   bool NoWrap = ControlsExit &&
11304                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11305 
11306   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11307 
11308   // Avoid negative or zero stride values
11309   if (!isKnownPositive(Stride))
11310     return getCouldNotCompute();
11311 
11312   // Avoid proven overflow cases: this will ensure that the backedge taken count
11313   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11314   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11315   // behaviors like the case of C language.
11316   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11317     return getCouldNotCompute();
11318 
11319   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11320                                       : ICmpInst::ICMP_UGT;
11321 
11322   const SCEV *Start = IV->getStart();
11323   const SCEV *End = RHS;
11324   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11325     // If we know that Start >= RHS in the context of loop, then we know that
11326     // min(RHS, Start) = RHS at this point.
11327     if (isLoopEntryGuardedByCond(
11328             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11329       End = RHS;
11330     else
11331       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11332   }
11333 
11334   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11335 
11336   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11337                             : getUnsignedRangeMax(Start);
11338 
11339   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11340                              : getUnsignedRangeMin(Stride);
11341 
11342   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11343   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11344                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11345 
11346   // Although End can be a MIN expression we estimate MinEnd considering only
11347   // the case End = RHS. This is safe because in the other case (Start - End)
11348   // is zero, leading to a zero maximum backedge taken count.
11349   APInt MinEnd =
11350     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11351              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11352 
11353   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11354                                ? BECount
11355                                : computeBECount(getConstant(MaxStart - MinEnd),
11356                                                 getConstant(MinStride), false);
11357 
11358   if (isa<SCEVCouldNotCompute>(MaxBECount))
11359     MaxBECount = BECount;
11360 
11361   return ExitLimit(BECount, MaxBECount, false, Predicates);
11362 }
11363 
11364 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11365                                                     ScalarEvolution &SE) const {
11366   if (Range.isFullSet())  // Infinite loop.
11367     return SE.getCouldNotCompute();
11368 
11369   // If the start is a non-zero constant, shift the range to simplify things.
11370   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11371     if (!SC->getValue()->isZero()) {
11372       SmallVector<const SCEV *, 4> Operands(operands());
11373       Operands[0] = SE.getZero(SC->getType());
11374       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11375                                              getNoWrapFlags(FlagNW));
11376       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11377         return ShiftedAddRec->getNumIterationsInRange(
11378             Range.subtract(SC->getAPInt()), SE);
11379       // This is strange and shouldn't happen.
11380       return SE.getCouldNotCompute();
11381     }
11382 
11383   // The only time we can solve this is when we have all constant indices.
11384   // Otherwise, we cannot determine the overflow conditions.
11385   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11386     return SE.getCouldNotCompute();
11387 
11388   // Okay at this point we know that all elements of the chrec are constants and
11389   // that the start element is zero.
11390 
11391   // First check to see if the range contains zero.  If not, the first
11392   // iteration exits.
11393   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11394   if (!Range.contains(APInt(BitWidth, 0)))
11395     return SE.getZero(getType());
11396 
11397   if (isAffine()) {
11398     // If this is an affine expression then we have this situation:
11399     //   Solve {0,+,A} in Range  ===  Ax in Range
11400 
11401     // We know that zero is in the range.  If A is positive then we know that
11402     // the upper value of the range must be the first possible exit value.
11403     // If A is negative then the lower of the range is the last possible loop
11404     // value.  Also note that we already checked for a full range.
11405     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11406     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11407 
11408     // The exit value should be (End+A)/A.
11409     APInt ExitVal = (End + A).udiv(A);
11410     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11411 
11412     // Evaluate at the exit value.  If we really did fall out of the valid
11413     // range, then we computed our trip count, otherwise wrap around or other
11414     // things must have happened.
11415     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11416     if (Range.contains(Val->getValue()))
11417       return SE.getCouldNotCompute();  // Something strange happened
11418 
11419     // Ensure that the previous value is in the range.  This is a sanity check.
11420     assert(Range.contains(
11421            EvaluateConstantChrecAtConstant(this,
11422            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11423            "Linear scev computation is off in a bad way!");
11424     return SE.getConstant(ExitValue);
11425   }
11426 
11427   if (isQuadratic()) {
11428     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11429       return SE.getConstant(S.getValue());
11430   }
11431 
11432   return SE.getCouldNotCompute();
11433 }
11434 
11435 const SCEVAddRecExpr *
11436 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11437   assert(getNumOperands() > 1 && "AddRec with zero step?");
11438   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11439   // but in this case we cannot guarantee that the value returned will be an
11440   // AddRec because SCEV does not have a fixed point where it stops
11441   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11442   // may happen if we reach arithmetic depth limit while simplifying. So we
11443   // construct the returned value explicitly.
11444   SmallVector<const SCEV *, 3> Ops;
11445   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11446   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11447   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11448     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11449   // We know that the last operand is not a constant zero (otherwise it would
11450   // have been popped out earlier). This guarantees us that if the result has
11451   // the same last operand, then it will also not be popped out, meaning that
11452   // the returned value will be an AddRec.
11453   const SCEV *Last = getOperand(getNumOperands() - 1);
11454   assert(!Last->isZero() && "Recurrency with zero step?");
11455   Ops.push_back(Last);
11456   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11457                                                SCEV::FlagAnyWrap));
11458 }
11459 
11460 // Return true when S contains at least an undef value.
11461 static inline bool containsUndefs(const SCEV *S) {
11462   return SCEVExprContains(S, [](const SCEV *S) {
11463     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11464       return isa<UndefValue>(SU->getValue());
11465     return false;
11466   });
11467 }
11468 
11469 namespace {
11470 
11471 // Collect all steps of SCEV expressions.
11472 struct SCEVCollectStrides {
11473   ScalarEvolution &SE;
11474   SmallVectorImpl<const SCEV *> &Strides;
11475 
11476   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11477       : SE(SE), Strides(S) {}
11478 
11479   bool follow(const SCEV *S) {
11480     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11481       Strides.push_back(AR->getStepRecurrence(SE));
11482     return true;
11483   }
11484 
11485   bool isDone() const { return false; }
11486 };
11487 
11488 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11489 struct SCEVCollectTerms {
11490   SmallVectorImpl<const SCEV *> &Terms;
11491 
11492   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11493 
11494   bool follow(const SCEV *S) {
11495     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11496         isa<SCEVSignExtendExpr>(S)) {
11497       if (!containsUndefs(S))
11498         Terms.push_back(S);
11499 
11500       // Stop recursion: once we collected a term, do not walk its operands.
11501       return false;
11502     }
11503 
11504     // Keep looking.
11505     return true;
11506   }
11507 
11508   bool isDone() const { return false; }
11509 };
11510 
11511 // Check if a SCEV contains an AddRecExpr.
11512 struct SCEVHasAddRec {
11513   bool &ContainsAddRec;
11514 
11515   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11516     ContainsAddRec = false;
11517   }
11518 
11519   bool follow(const SCEV *S) {
11520     if (isa<SCEVAddRecExpr>(S)) {
11521       ContainsAddRec = true;
11522 
11523       // Stop recursion: once we collected a term, do not walk its operands.
11524       return false;
11525     }
11526 
11527     // Keep looking.
11528     return true;
11529   }
11530 
11531   bool isDone() const { return false; }
11532 };
11533 
11534 // Find factors that are multiplied with an expression that (possibly as a
11535 // subexpression) contains an AddRecExpr. In the expression:
11536 //
11537 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11538 //
11539 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11540 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11541 // parameters as they form a product with an induction variable.
11542 //
11543 // This collector expects all array size parameters to be in the same MulExpr.
11544 // It might be necessary to later add support for collecting parameters that are
11545 // spread over different nested MulExpr.
11546 struct SCEVCollectAddRecMultiplies {
11547   SmallVectorImpl<const SCEV *> &Terms;
11548   ScalarEvolution &SE;
11549 
11550   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11551       : Terms(T), SE(SE) {}
11552 
11553   bool follow(const SCEV *S) {
11554     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11555       bool HasAddRec = false;
11556       SmallVector<const SCEV *, 0> Operands;
11557       for (auto Op : Mul->operands()) {
11558         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11559         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11560           Operands.push_back(Op);
11561         } else if (Unknown) {
11562           HasAddRec = true;
11563         } else {
11564           bool ContainsAddRec = false;
11565           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11566           visitAll(Op, ContiansAddRec);
11567           HasAddRec |= ContainsAddRec;
11568         }
11569       }
11570       if (Operands.size() == 0)
11571         return true;
11572 
11573       if (!HasAddRec)
11574         return false;
11575 
11576       Terms.push_back(SE.getMulExpr(Operands));
11577       // Stop recursion: once we collected a term, do not walk its operands.
11578       return false;
11579     }
11580 
11581     // Keep looking.
11582     return true;
11583   }
11584 
11585   bool isDone() const { return false; }
11586 };
11587 
11588 } // end anonymous namespace
11589 
11590 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11591 /// two places:
11592 ///   1) The strides of AddRec expressions.
11593 ///   2) Unknowns that are multiplied with AddRec expressions.
11594 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11595     SmallVectorImpl<const SCEV *> &Terms) {
11596   SmallVector<const SCEV *, 4> Strides;
11597   SCEVCollectStrides StrideCollector(*this, Strides);
11598   visitAll(Expr, StrideCollector);
11599 
11600   LLVM_DEBUG({
11601     dbgs() << "Strides:\n";
11602     for (const SCEV *S : Strides)
11603       dbgs() << *S << "\n";
11604   });
11605 
11606   for (const SCEV *S : Strides) {
11607     SCEVCollectTerms TermCollector(Terms);
11608     visitAll(S, TermCollector);
11609   }
11610 
11611   LLVM_DEBUG({
11612     dbgs() << "Terms:\n";
11613     for (const SCEV *T : Terms)
11614       dbgs() << *T << "\n";
11615   });
11616 
11617   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11618   visitAll(Expr, MulCollector);
11619 }
11620 
11621 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11622                                    SmallVectorImpl<const SCEV *> &Terms,
11623                                    SmallVectorImpl<const SCEV *> &Sizes) {
11624   int Last = Terms.size() - 1;
11625   const SCEV *Step = Terms[Last];
11626 
11627   // End of recursion.
11628   if (Last == 0) {
11629     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11630       SmallVector<const SCEV *, 2> Qs;
11631       for (const SCEV *Op : M->operands())
11632         if (!isa<SCEVConstant>(Op))
11633           Qs.push_back(Op);
11634 
11635       Step = SE.getMulExpr(Qs);
11636     }
11637 
11638     Sizes.push_back(Step);
11639     return true;
11640   }
11641 
11642   for (const SCEV *&Term : Terms) {
11643     // Normalize the terms before the next call to findArrayDimensionsRec.
11644     const SCEV *Q, *R;
11645     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11646 
11647     // Bail out when GCD does not evenly divide one of the terms.
11648     if (!R->isZero())
11649       return false;
11650 
11651     Term = Q;
11652   }
11653 
11654   // Remove all SCEVConstants.
11655   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
11656 
11657   if (Terms.size() > 0)
11658     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11659       return false;
11660 
11661   Sizes.push_back(Step);
11662   return true;
11663 }
11664 
11665 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11666 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11667   for (const SCEV *T : Terms)
11668     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11669       return true;
11670 
11671   return false;
11672 }
11673 
11674 // Return the number of product terms in S.
11675 static inline int numberOfTerms(const SCEV *S) {
11676   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11677     return Expr->getNumOperands();
11678   return 1;
11679 }
11680 
11681 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11682   if (isa<SCEVConstant>(T))
11683     return nullptr;
11684 
11685   if (isa<SCEVUnknown>(T))
11686     return T;
11687 
11688   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11689     SmallVector<const SCEV *, 2> Factors;
11690     for (const SCEV *Op : M->operands())
11691       if (!isa<SCEVConstant>(Op))
11692         Factors.push_back(Op);
11693 
11694     return SE.getMulExpr(Factors);
11695   }
11696 
11697   return T;
11698 }
11699 
11700 /// Return the size of an element read or written by Inst.
11701 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11702   Type *Ty;
11703   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11704     Ty = Store->getValueOperand()->getType();
11705   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11706     Ty = Load->getType();
11707   else
11708     return nullptr;
11709 
11710   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11711   return getSizeOfExpr(ETy, Ty);
11712 }
11713 
11714 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11715                                           SmallVectorImpl<const SCEV *> &Sizes,
11716                                           const SCEV *ElementSize) {
11717   if (Terms.size() < 1 || !ElementSize)
11718     return;
11719 
11720   // Early return when Terms do not contain parameters: we do not delinearize
11721   // non parametric SCEVs.
11722   if (!containsParameters(Terms))
11723     return;
11724 
11725   LLVM_DEBUG({
11726     dbgs() << "Terms:\n";
11727     for (const SCEV *T : Terms)
11728       dbgs() << *T << "\n";
11729   });
11730 
11731   // Remove duplicates.
11732   array_pod_sort(Terms.begin(), Terms.end());
11733   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11734 
11735   // Put larger terms first.
11736   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11737     return numberOfTerms(LHS) > numberOfTerms(RHS);
11738   });
11739 
11740   // Try to divide all terms by the element size. If term is not divisible by
11741   // element size, proceed with the original term.
11742   for (const SCEV *&Term : Terms) {
11743     const SCEV *Q, *R;
11744     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11745     if (!Q->isZero())
11746       Term = Q;
11747   }
11748 
11749   SmallVector<const SCEV *, 4> NewTerms;
11750 
11751   // Remove constant factors.
11752   for (const SCEV *T : Terms)
11753     if (const SCEV *NewT = removeConstantFactors(*this, T))
11754       NewTerms.push_back(NewT);
11755 
11756   LLVM_DEBUG({
11757     dbgs() << "Terms after sorting:\n";
11758     for (const SCEV *T : NewTerms)
11759       dbgs() << *T << "\n";
11760   });
11761 
11762   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11763     Sizes.clear();
11764     return;
11765   }
11766 
11767   // The last element to be pushed into Sizes is the size of an element.
11768   Sizes.push_back(ElementSize);
11769 
11770   LLVM_DEBUG({
11771     dbgs() << "Sizes:\n";
11772     for (const SCEV *S : Sizes)
11773       dbgs() << *S << "\n";
11774   });
11775 }
11776 
11777 void ScalarEvolution::computeAccessFunctions(
11778     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11779     SmallVectorImpl<const SCEV *> &Sizes) {
11780   // Early exit in case this SCEV is not an affine multivariate function.
11781   if (Sizes.empty())
11782     return;
11783 
11784   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11785     if (!AR->isAffine())
11786       return;
11787 
11788   const SCEV *Res = Expr;
11789   int Last = Sizes.size() - 1;
11790   for (int i = Last; i >= 0; i--) {
11791     const SCEV *Q, *R;
11792     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11793 
11794     LLVM_DEBUG({
11795       dbgs() << "Res: " << *Res << "\n";
11796       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11797       dbgs() << "Res divided by Sizes[i]:\n";
11798       dbgs() << "Quotient: " << *Q << "\n";
11799       dbgs() << "Remainder: " << *R << "\n";
11800     });
11801 
11802     Res = Q;
11803 
11804     // Do not record the last subscript corresponding to the size of elements in
11805     // the array.
11806     if (i == Last) {
11807 
11808       // Bail out if the remainder is too complex.
11809       if (isa<SCEVAddRecExpr>(R)) {
11810         Subscripts.clear();
11811         Sizes.clear();
11812         return;
11813       }
11814 
11815       continue;
11816     }
11817 
11818     // Record the access function for the current subscript.
11819     Subscripts.push_back(R);
11820   }
11821 
11822   // Also push in last position the remainder of the last division: it will be
11823   // the access function of the innermost dimension.
11824   Subscripts.push_back(Res);
11825 
11826   std::reverse(Subscripts.begin(), Subscripts.end());
11827 
11828   LLVM_DEBUG({
11829     dbgs() << "Subscripts:\n";
11830     for (const SCEV *S : Subscripts)
11831       dbgs() << *S << "\n";
11832   });
11833 }
11834 
11835 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11836 /// sizes of an array access. Returns the remainder of the delinearization that
11837 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11838 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11839 /// expressions in the stride and base of a SCEV corresponding to the
11840 /// computation of a GCD (greatest common divisor) of base and stride.  When
11841 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11842 ///
11843 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11844 ///
11845 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11846 ///
11847 ///    for (long i = 0; i < n; i++)
11848 ///      for (long j = 0; j < m; j++)
11849 ///        for (long k = 0; k < o; k++)
11850 ///          A[i][j][k] = 1.0;
11851 ///  }
11852 ///
11853 /// the delinearization input is the following AddRec SCEV:
11854 ///
11855 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11856 ///
11857 /// From this SCEV, we are able to say that the base offset of the access is %A
11858 /// because it appears as an offset that does not divide any of the strides in
11859 /// the loops:
11860 ///
11861 ///  CHECK: Base offset: %A
11862 ///
11863 /// and then SCEV->delinearize determines the size of some of the dimensions of
11864 /// the array as these are the multiples by which the strides are happening:
11865 ///
11866 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11867 ///
11868 /// Note that the outermost dimension remains of UnknownSize because there are
11869 /// no strides that would help identifying the size of the last dimension: when
11870 /// the array has been statically allocated, one could compute the size of that
11871 /// dimension by dividing the overall size of the array by the size of the known
11872 /// dimensions: %m * %o * 8.
11873 ///
11874 /// Finally delinearize provides the access functions for the array reference
11875 /// that does correspond to A[i][j][k] of the above C testcase:
11876 ///
11877 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11878 ///
11879 /// The testcases are checking the output of a function pass:
11880 /// DelinearizationPass that walks through all loads and stores of a function
11881 /// asking for the SCEV of the memory access with respect to all enclosing
11882 /// loops, calling SCEV->delinearize on that and printing the results.
11883 void ScalarEvolution::delinearize(const SCEV *Expr,
11884                                  SmallVectorImpl<const SCEV *> &Subscripts,
11885                                  SmallVectorImpl<const SCEV *> &Sizes,
11886                                  const SCEV *ElementSize) {
11887   // First step: collect parametric terms.
11888   SmallVector<const SCEV *, 4> Terms;
11889   collectParametricTerms(Expr, Terms);
11890 
11891   if (Terms.empty())
11892     return;
11893 
11894   // Second step: find subscript sizes.
11895   findArrayDimensions(Terms, Sizes, ElementSize);
11896 
11897   if (Sizes.empty())
11898     return;
11899 
11900   // Third step: compute the access functions for each subscript.
11901   computeAccessFunctions(Expr, Subscripts, Sizes);
11902 
11903   if (Subscripts.empty())
11904     return;
11905 
11906   LLVM_DEBUG({
11907     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11908     dbgs() << "ArrayDecl[UnknownSize]";
11909     for (const SCEV *S : Sizes)
11910       dbgs() << "[" << *S << "]";
11911 
11912     dbgs() << "\nArrayRef";
11913     for (const SCEV *S : Subscripts)
11914       dbgs() << "[" << *S << "]";
11915     dbgs() << "\n";
11916   });
11917 }
11918 
11919 bool ScalarEvolution::getIndexExpressionsFromGEP(
11920     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
11921     SmallVectorImpl<int> &Sizes) {
11922   assert(Subscripts.empty() && Sizes.empty() &&
11923          "Expected output lists to be empty on entry to this function.");
11924   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
11925   Type *Ty = GEP->getPointerOperandType();
11926   bool DroppedFirstDim = false;
11927   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
11928     const SCEV *Expr = getSCEV(GEP->getOperand(i));
11929     if (i == 1) {
11930       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
11931         Ty = PtrTy->getElementType();
11932       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
11933         Ty = ArrayTy->getElementType();
11934       } else {
11935         Subscripts.clear();
11936         Sizes.clear();
11937         return false;
11938       }
11939       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
11940         if (Const->getValue()->isZero()) {
11941           DroppedFirstDim = true;
11942           continue;
11943         }
11944       Subscripts.push_back(Expr);
11945       continue;
11946     }
11947 
11948     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
11949     if (!ArrayTy) {
11950       Subscripts.clear();
11951       Sizes.clear();
11952       return false;
11953     }
11954 
11955     Subscripts.push_back(Expr);
11956     if (!(DroppedFirstDim && i == 2))
11957       Sizes.push_back(ArrayTy->getNumElements());
11958 
11959     Ty = ArrayTy->getElementType();
11960   }
11961   return !Subscripts.empty();
11962 }
11963 
11964 //===----------------------------------------------------------------------===//
11965 //                   SCEVCallbackVH Class Implementation
11966 //===----------------------------------------------------------------------===//
11967 
11968 void ScalarEvolution::SCEVCallbackVH::deleted() {
11969   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11970   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11971     SE->ConstantEvolutionLoopExitValue.erase(PN);
11972   SE->eraseValueFromMap(getValPtr());
11973   // this now dangles!
11974 }
11975 
11976 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11977   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11978 
11979   // Forget all the expressions associated with users of the old value,
11980   // so that future queries will recompute the expressions using the new
11981   // value.
11982   Value *Old = getValPtr();
11983   SmallVector<User *, 16> Worklist(Old->users());
11984   SmallPtrSet<User *, 8> Visited;
11985   while (!Worklist.empty()) {
11986     User *U = Worklist.pop_back_val();
11987     // Deleting the Old value will cause this to dangle. Postpone
11988     // that until everything else is done.
11989     if (U == Old)
11990       continue;
11991     if (!Visited.insert(U).second)
11992       continue;
11993     if (PHINode *PN = dyn_cast<PHINode>(U))
11994       SE->ConstantEvolutionLoopExitValue.erase(PN);
11995     SE->eraseValueFromMap(U);
11996     llvm::append_range(Worklist, U->users());
11997   }
11998   // Delete the Old value.
11999   if (PHINode *PN = dyn_cast<PHINode>(Old))
12000     SE->ConstantEvolutionLoopExitValue.erase(PN);
12001   SE->eraseValueFromMap(Old);
12002   // this now dangles!
12003 }
12004 
12005 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12006   : CallbackVH(V), SE(se) {}
12007 
12008 //===----------------------------------------------------------------------===//
12009 //                   ScalarEvolution Class Implementation
12010 //===----------------------------------------------------------------------===//
12011 
12012 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12013                                  AssumptionCache &AC, DominatorTree &DT,
12014                                  LoopInfo &LI)
12015     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12016       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12017       LoopDispositions(64), BlockDispositions(64) {
12018   // To use guards for proving predicates, we need to scan every instruction in
12019   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12020   // time if the IR does not actually contain any calls to
12021   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12022   //
12023   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12024   // to _add_ guards to the module when there weren't any before, and wants
12025   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12026   // efficient in lieu of being smart in that rather obscure case.
12027 
12028   auto *GuardDecl = F.getParent()->getFunction(
12029       Intrinsic::getName(Intrinsic::experimental_guard));
12030   HasGuards = GuardDecl && !GuardDecl->use_empty();
12031 }
12032 
12033 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12034     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12035       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12036       ValueExprMap(std::move(Arg.ValueExprMap)),
12037       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12038       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12039       PendingMerges(std::move(Arg.PendingMerges)),
12040       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12041       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12042       PredicatedBackedgeTakenCounts(
12043           std::move(Arg.PredicatedBackedgeTakenCounts)),
12044       ConstantEvolutionLoopExitValue(
12045           std::move(Arg.ConstantEvolutionLoopExitValue)),
12046       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12047       LoopDispositions(std::move(Arg.LoopDispositions)),
12048       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12049       BlockDispositions(std::move(Arg.BlockDispositions)),
12050       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12051       SignedRanges(std::move(Arg.SignedRanges)),
12052       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12053       UniquePreds(std::move(Arg.UniquePreds)),
12054       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12055       LoopUsers(std::move(Arg.LoopUsers)),
12056       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12057       FirstUnknown(Arg.FirstUnknown) {
12058   Arg.FirstUnknown = nullptr;
12059 }
12060 
12061 ScalarEvolution::~ScalarEvolution() {
12062   // Iterate through all the SCEVUnknown instances and call their
12063   // destructors, so that they release their references to their values.
12064   for (SCEVUnknown *U = FirstUnknown; U;) {
12065     SCEVUnknown *Tmp = U;
12066     U = U->Next;
12067     Tmp->~SCEVUnknown();
12068   }
12069   FirstUnknown = nullptr;
12070 
12071   ExprValueMap.clear();
12072   ValueExprMap.clear();
12073   HasRecMap.clear();
12074 
12075   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
12076   // that a loop had multiple computable exits.
12077   for (auto &BTCI : BackedgeTakenCounts)
12078     BTCI.second.clear();
12079   for (auto &BTCI : PredicatedBackedgeTakenCounts)
12080     BTCI.second.clear();
12081 
12082   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12083   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12084   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12085   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12086   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12087 }
12088 
12089 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12090   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12091 }
12092 
12093 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12094                           const Loop *L) {
12095   // Print all inner loops first
12096   for (Loop *I : *L)
12097     PrintLoopInfo(OS, SE, I);
12098 
12099   OS << "Loop ";
12100   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12101   OS << ": ";
12102 
12103   SmallVector<BasicBlock *, 8> ExitingBlocks;
12104   L->getExitingBlocks(ExitingBlocks);
12105   if (ExitingBlocks.size() != 1)
12106     OS << "<multiple exits> ";
12107 
12108   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12109     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12110   else
12111     OS << "Unpredictable backedge-taken count.\n";
12112 
12113   if (ExitingBlocks.size() > 1)
12114     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12115       OS << "  exit count for " << ExitingBlock->getName() << ": "
12116          << *SE->getExitCount(L, ExitingBlock) << "\n";
12117     }
12118 
12119   OS << "Loop ";
12120   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12121   OS << ": ";
12122 
12123   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12124     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12125     if (SE->isBackedgeTakenCountMaxOrZero(L))
12126       OS << ", actual taken count either this or zero.";
12127   } else {
12128     OS << "Unpredictable max backedge-taken count. ";
12129   }
12130 
12131   OS << "\n"
12132         "Loop ";
12133   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12134   OS << ": ";
12135 
12136   SCEVUnionPredicate Pred;
12137   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12138   if (!isa<SCEVCouldNotCompute>(PBT)) {
12139     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12140     OS << " Predicates:\n";
12141     Pred.print(OS, 4);
12142   } else {
12143     OS << "Unpredictable predicated backedge-taken count. ";
12144   }
12145   OS << "\n";
12146 
12147   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12148     OS << "Loop ";
12149     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12150     OS << ": ";
12151     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12152   }
12153 }
12154 
12155 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12156   switch (LD) {
12157   case ScalarEvolution::LoopVariant:
12158     return "Variant";
12159   case ScalarEvolution::LoopInvariant:
12160     return "Invariant";
12161   case ScalarEvolution::LoopComputable:
12162     return "Computable";
12163   }
12164   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12165 }
12166 
12167 void ScalarEvolution::print(raw_ostream &OS) const {
12168   // ScalarEvolution's implementation of the print method is to print
12169   // out SCEV values of all instructions that are interesting. Doing
12170   // this potentially causes it to create new SCEV objects though,
12171   // which technically conflicts with the const qualifier. This isn't
12172   // observable from outside the class though, so casting away the
12173   // const isn't dangerous.
12174   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12175 
12176   if (ClassifyExpressions) {
12177     OS << "Classifying expressions for: ";
12178     F.printAsOperand(OS, /*PrintType=*/false);
12179     OS << "\n";
12180     for (Instruction &I : instructions(F))
12181       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12182         OS << I << '\n';
12183         OS << "  -->  ";
12184         const SCEV *SV = SE.getSCEV(&I);
12185         SV->print(OS);
12186         if (!isa<SCEVCouldNotCompute>(SV)) {
12187           OS << " U: ";
12188           SE.getUnsignedRange(SV).print(OS);
12189           OS << " S: ";
12190           SE.getSignedRange(SV).print(OS);
12191         }
12192 
12193         const Loop *L = LI.getLoopFor(I.getParent());
12194 
12195         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12196         if (AtUse != SV) {
12197           OS << "  -->  ";
12198           AtUse->print(OS);
12199           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12200             OS << " U: ";
12201             SE.getUnsignedRange(AtUse).print(OS);
12202             OS << " S: ";
12203             SE.getSignedRange(AtUse).print(OS);
12204           }
12205         }
12206 
12207         if (L) {
12208           OS << "\t\t" "Exits: ";
12209           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12210           if (!SE.isLoopInvariant(ExitValue, L)) {
12211             OS << "<<Unknown>>";
12212           } else {
12213             OS << *ExitValue;
12214           }
12215 
12216           bool First = true;
12217           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12218             if (First) {
12219               OS << "\t\t" "LoopDispositions: { ";
12220               First = false;
12221             } else {
12222               OS << ", ";
12223             }
12224 
12225             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12226             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12227           }
12228 
12229           for (auto *InnerL : depth_first(L)) {
12230             if (InnerL == L)
12231               continue;
12232             if (First) {
12233               OS << "\t\t" "LoopDispositions: { ";
12234               First = false;
12235             } else {
12236               OS << ", ";
12237             }
12238 
12239             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12240             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12241           }
12242 
12243           OS << " }";
12244         }
12245 
12246         OS << "\n";
12247       }
12248   }
12249 
12250   OS << "Determining loop execution counts for: ";
12251   F.printAsOperand(OS, /*PrintType=*/false);
12252   OS << "\n";
12253   for (Loop *I : LI)
12254     PrintLoopInfo(OS, &SE, I);
12255 }
12256 
12257 ScalarEvolution::LoopDisposition
12258 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12259   auto &Values = LoopDispositions[S];
12260   for (auto &V : Values) {
12261     if (V.getPointer() == L)
12262       return V.getInt();
12263   }
12264   Values.emplace_back(L, LoopVariant);
12265   LoopDisposition D = computeLoopDisposition(S, L);
12266   auto &Values2 = LoopDispositions[S];
12267   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12268     if (V.getPointer() == L) {
12269       V.setInt(D);
12270       break;
12271     }
12272   }
12273   return D;
12274 }
12275 
12276 ScalarEvolution::LoopDisposition
12277 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12278   switch (S->getSCEVType()) {
12279   case scConstant:
12280     return LoopInvariant;
12281   case scPtrToInt:
12282   case scTruncate:
12283   case scZeroExtend:
12284   case scSignExtend:
12285     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12286   case scAddRecExpr: {
12287     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12288 
12289     // If L is the addrec's loop, it's computable.
12290     if (AR->getLoop() == L)
12291       return LoopComputable;
12292 
12293     // Add recurrences are never invariant in the function-body (null loop).
12294     if (!L)
12295       return LoopVariant;
12296 
12297     // Everything that is not defined at loop entry is variant.
12298     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12299       return LoopVariant;
12300     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12301            " dominate the contained loop's header?");
12302 
12303     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12304     if (AR->getLoop()->contains(L))
12305       return LoopInvariant;
12306 
12307     // This recurrence is variant w.r.t. L if any of its operands
12308     // are variant.
12309     for (auto *Op : AR->operands())
12310       if (!isLoopInvariant(Op, L))
12311         return LoopVariant;
12312 
12313     // Otherwise it's loop-invariant.
12314     return LoopInvariant;
12315   }
12316   case scAddExpr:
12317   case scMulExpr:
12318   case scUMaxExpr:
12319   case scSMaxExpr:
12320   case scUMinExpr:
12321   case scSMinExpr: {
12322     bool HasVarying = false;
12323     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12324       LoopDisposition D = getLoopDisposition(Op, L);
12325       if (D == LoopVariant)
12326         return LoopVariant;
12327       if (D == LoopComputable)
12328         HasVarying = true;
12329     }
12330     return HasVarying ? LoopComputable : LoopInvariant;
12331   }
12332   case scUDivExpr: {
12333     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12334     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12335     if (LD == LoopVariant)
12336       return LoopVariant;
12337     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12338     if (RD == LoopVariant)
12339       return LoopVariant;
12340     return (LD == LoopInvariant && RD == LoopInvariant) ?
12341            LoopInvariant : LoopComputable;
12342   }
12343   case scUnknown:
12344     // All non-instruction values are loop invariant.  All instructions are loop
12345     // invariant if they are not contained in the specified loop.
12346     // Instructions are never considered invariant in the function body
12347     // (null loop) because they are defined within the "loop".
12348     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12349       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12350     return LoopInvariant;
12351   case scCouldNotCompute:
12352     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12353   }
12354   llvm_unreachable("Unknown SCEV kind!");
12355 }
12356 
12357 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12358   return getLoopDisposition(S, L) == LoopInvariant;
12359 }
12360 
12361 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12362   return getLoopDisposition(S, L) == LoopComputable;
12363 }
12364 
12365 ScalarEvolution::BlockDisposition
12366 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12367   auto &Values = BlockDispositions[S];
12368   for (auto &V : Values) {
12369     if (V.getPointer() == BB)
12370       return V.getInt();
12371   }
12372   Values.emplace_back(BB, DoesNotDominateBlock);
12373   BlockDisposition D = computeBlockDisposition(S, BB);
12374   auto &Values2 = BlockDispositions[S];
12375   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12376     if (V.getPointer() == BB) {
12377       V.setInt(D);
12378       break;
12379     }
12380   }
12381   return D;
12382 }
12383 
12384 ScalarEvolution::BlockDisposition
12385 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12386   switch (S->getSCEVType()) {
12387   case scConstant:
12388     return ProperlyDominatesBlock;
12389   case scPtrToInt:
12390   case scTruncate:
12391   case scZeroExtend:
12392   case scSignExtend:
12393     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12394   case scAddRecExpr: {
12395     // This uses a "dominates" query instead of "properly dominates" query
12396     // to test for proper dominance too, because the instruction which
12397     // produces the addrec's value is a PHI, and a PHI effectively properly
12398     // dominates its entire containing block.
12399     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12400     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12401       return DoesNotDominateBlock;
12402 
12403     // Fall through into SCEVNAryExpr handling.
12404     LLVM_FALLTHROUGH;
12405   }
12406   case scAddExpr:
12407   case scMulExpr:
12408   case scUMaxExpr:
12409   case scSMaxExpr:
12410   case scUMinExpr:
12411   case scSMinExpr: {
12412     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12413     bool Proper = true;
12414     for (const SCEV *NAryOp : NAry->operands()) {
12415       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12416       if (D == DoesNotDominateBlock)
12417         return DoesNotDominateBlock;
12418       if (D == DominatesBlock)
12419         Proper = false;
12420     }
12421     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12422   }
12423   case scUDivExpr: {
12424     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12425     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12426     BlockDisposition LD = getBlockDisposition(LHS, BB);
12427     if (LD == DoesNotDominateBlock)
12428       return DoesNotDominateBlock;
12429     BlockDisposition RD = getBlockDisposition(RHS, BB);
12430     if (RD == DoesNotDominateBlock)
12431       return DoesNotDominateBlock;
12432     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12433       ProperlyDominatesBlock : DominatesBlock;
12434   }
12435   case scUnknown:
12436     if (Instruction *I =
12437           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12438       if (I->getParent() == BB)
12439         return DominatesBlock;
12440       if (DT.properlyDominates(I->getParent(), BB))
12441         return ProperlyDominatesBlock;
12442       return DoesNotDominateBlock;
12443     }
12444     return ProperlyDominatesBlock;
12445   case scCouldNotCompute:
12446     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12447   }
12448   llvm_unreachable("Unknown SCEV kind!");
12449 }
12450 
12451 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12452   return getBlockDisposition(S, BB) >= DominatesBlock;
12453 }
12454 
12455 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12456   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12457 }
12458 
12459 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12460   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12461 }
12462 
12463 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12464   auto IsS = [&](const SCEV *X) { return S == X; };
12465   auto ContainsS = [&](const SCEV *X) {
12466     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12467   };
12468   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12469 }
12470 
12471 void
12472 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12473   ValuesAtScopes.erase(S);
12474   LoopDispositions.erase(S);
12475   BlockDispositions.erase(S);
12476   UnsignedRanges.erase(S);
12477   SignedRanges.erase(S);
12478   ExprValueMap.erase(S);
12479   HasRecMap.erase(S);
12480   MinTrailingZerosCache.erase(S);
12481 
12482   for (auto I = PredicatedSCEVRewrites.begin();
12483        I != PredicatedSCEVRewrites.end();) {
12484     std::pair<const SCEV *, const Loop *> Entry = I->first;
12485     if (Entry.first == S)
12486       PredicatedSCEVRewrites.erase(I++);
12487     else
12488       ++I;
12489   }
12490 
12491   auto RemoveSCEVFromBackedgeMap =
12492       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12493         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12494           BackedgeTakenInfo &BEInfo = I->second;
12495           if (BEInfo.hasOperand(S, this)) {
12496             BEInfo.clear();
12497             Map.erase(I++);
12498           } else
12499             ++I;
12500         }
12501       };
12502 
12503   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12504   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12505 }
12506 
12507 void
12508 ScalarEvolution::getUsedLoops(const SCEV *S,
12509                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12510   struct FindUsedLoops {
12511     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12512         : LoopsUsed(LoopsUsed) {}
12513     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12514     bool follow(const SCEV *S) {
12515       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12516         LoopsUsed.insert(AR->getLoop());
12517       return true;
12518     }
12519 
12520     bool isDone() const { return false; }
12521   };
12522 
12523   FindUsedLoops F(LoopsUsed);
12524   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12525 }
12526 
12527 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12528   SmallPtrSet<const Loop *, 8> LoopsUsed;
12529   getUsedLoops(S, LoopsUsed);
12530   for (auto *L : LoopsUsed)
12531     LoopUsers[L].push_back(S);
12532 }
12533 
12534 void ScalarEvolution::verify() const {
12535   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12536   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12537 
12538   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12539 
12540   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12541   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12542     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12543 
12544     const SCEV *visitConstant(const SCEVConstant *Constant) {
12545       return SE.getConstant(Constant->getAPInt());
12546     }
12547 
12548     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12549       return SE.getUnknown(Expr->getValue());
12550     }
12551 
12552     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12553       return SE.getCouldNotCompute();
12554     }
12555   };
12556 
12557   SCEVMapper SCM(SE2);
12558 
12559   while (!LoopStack.empty()) {
12560     auto *L = LoopStack.pop_back_val();
12561     llvm::append_range(LoopStack, *L);
12562 
12563     auto *CurBECount = SCM.visit(
12564         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12565     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12566 
12567     if (CurBECount == SE2.getCouldNotCompute() ||
12568         NewBECount == SE2.getCouldNotCompute()) {
12569       // NB! This situation is legal, but is very suspicious -- whatever pass
12570       // change the loop to make a trip count go from could not compute to
12571       // computable or vice-versa *should have* invalidated SCEV.  However, we
12572       // choose not to assert here (for now) since we don't want false
12573       // positives.
12574       continue;
12575     }
12576 
12577     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12578       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12579       // not propagate undef aggressively).  This means we can (and do) fail
12580       // verification in cases where a transform makes the trip count of a loop
12581       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12582       // both cases the loop iterates "undef" times, but SCEV thinks we
12583       // increased the trip count of the loop by 1 incorrectly.
12584       continue;
12585     }
12586 
12587     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12588         SE.getTypeSizeInBits(NewBECount->getType()))
12589       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12590     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12591              SE.getTypeSizeInBits(NewBECount->getType()))
12592       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12593 
12594     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12595 
12596     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12597     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12598       dbgs() << "Trip Count for " << *L << " Changed!\n";
12599       dbgs() << "Old: " << *CurBECount << "\n";
12600       dbgs() << "New: " << *NewBECount << "\n";
12601       dbgs() << "Delta: " << *Delta << "\n";
12602       std::abort();
12603     }
12604   }
12605 
12606   // Collect all valid loops currently in LoopInfo.
12607   SmallPtrSet<Loop *, 32> ValidLoops;
12608   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12609   while (!Worklist.empty()) {
12610     Loop *L = Worklist.pop_back_val();
12611     if (ValidLoops.contains(L))
12612       continue;
12613     ValidLoops.insert(L);
12614     Worklist.append(L->begin(), L->end());
12615   }
12616   // Check for SCEV expressions referencing invalid/deleted loops.
12617   for (auto &KV : ValueExprMap) {
12618     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12619     if (!AR)
12620       continue;
12621     assert(ValidLoops.contains(AR->getLoop()) &&
12622            "AddRec references invalid loop");
12623   }
12624 }
12625 
12626 bool ScalarEvolution::invalidate(
12627     Function &F, const PreservedAnalyses &PA,
12628     FunctionAnalysisManager::Invalidator &Inv) {
12629   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12630   // of its dependencies is invalidated.
12631   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12632   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12633          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12634          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12635          Inv.invalidate<LoopAnalysis>(F, PA);
12636 }
12637 
12638 AnalysisKey ScalarEvolutionAnalysis::Key;
12639 
12640 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12641                                              FunctionAnalysisManager &AM) {
12642   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12643                          AM.getResult<AssumptionAnalysis>(F),
12644                          AM.getResult<DominatorTreeAnalysis>(F),
12645                          AM.getResult<LoopAnalysis>(F));
12646 }
12647 
12648 PreservedAnalyses
12649 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12650   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12651   return PreservedAnalyses::all();
12652 }
12653 
12654 PreservedAnalyses
12655 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12656   // For compatibility with opt's -analyze feature under legacy pass manager
12657   // which was not ported to NPM. This keeps tests using
12658   // update_analyze_test_checks.py working.
12659   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12660      << F.getName() << "':\n";
12661   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12662   return PreservedAnalyses::all();
12663 }
12664 
12665 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12666                       "Scalar Evolution Analysis", false, true)
12667 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12668 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12669 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12670 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12671 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12672                     "Scalar Evolution Analysis", false, true)
12673 
12674 char ScalarEvolutionWrapperPass::ID = 0;
12675 
12676 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12677   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12678 }
12679 
12680 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12681   SE.reset(new ScalarEvolution(
12682       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12683       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12684       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12685       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12686   return false;
12687 }
12688 
12689 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12690 
12691 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12692   SE->print(OS);
12693 }
12694 
12695 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12696   if (!VerifySCEV)
12697     return;
12698 
12699   SE->verify();
12700 }
12701 
12702 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12703   AU.setPreservesAll();
12704   AU.addRequiredTransitive<AssumptionCacheTracker>();
12705   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12706   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12707   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12708 }
12709 
12710 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12711                                                         const SCEV *RHS) {
12712   FoldingSetNodeID ID;
12713   assert(LHS->getType() == RHS->getType() &&
12714          "Type mismatch between LHS and RHS");
12715   // Unique this node based on the arguments
12716   ID.AddInteger(SCEVPredicate::P_Equal);
12717   ID.AddPointer(LHS);
12718   ID.AddPointer(RHS);
12719   void *IP = nullptr;
12720   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12721     return S;
12722   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12723       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12724   UniquePreds.InsertNode(Eq, IP);
12725   return Eq;
12726 }
12727 
12728 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12729     const SCEVAddRecExpr *AR,
12730     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12731   FoldingSetNodeID ID;
12732   // Unique this node based on the arguments
12733   ID.AddInteger(SCEVPredicate::P_Wrap);
12734   ID.AddPointer(AR);
12735   ID.AddInteger(AddedFlags);
12736   void *IP = nullptr;
12737   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12738     return S;
12739   auto *OF = new (SCEVAllocator)
12740       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12741   UniquePreds.InsertNode(OF, IP);
12742   return OF;
12743 }
12744 
12745 namespace {
12746 
12747 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12748 public:
12749 
12750   /// Rewrites \p S in the context of a loop L and the SCEV predication
12751   /// infrastructure.
12752   ///
12753   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12754   /// equivalences present in \p Pred.
12755   ///
12756   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12757   /// \p NewPreds such that the result will be an AddRecExpr.
12758   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12759                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12760                              SCEVUnionPredicate *Pred) {
12761     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12762     return Rewriter.visit(S);
12763   }
12764 
12765   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12766     if (Pred) {
12767       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12768       for (auto *Pred : ExprPreds)
12769         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12770           if (IPred->getLHS() == Expr)
12771             return IPred->getRHS();
12772     }
12773     return convertToAddRecWithPreds(Expr);
12774   }
12775 
12776   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12777     const SCEV *Operand = visit(Expr->getOperand());
12778     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12779     if (AR && AR->getLoop() == L && AR->isAffine()) {
12780       // This couldn't be folded because the operand didn't have the nuw
12781       // flag. Add the nusw flag as an assumption that we could make.
12782       const SCEV *Step = AR->getStepRecurrence(SE);
12783       Type *Ty = Expr->getType();
12784       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12785         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12786                                 SE.getSignExtendExpr(Step, Ty), L,
12787                                 AR->getNoWrapFlags());
12788     }
12789     return SE.getZeroExtendExpr(Operand, Expr->getType());
12790   }
12791 
12792   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12793     const SCEV *Operand = visit(Expr->getOperand());
12794     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12795     if (AR && AR->getLoop() == L && AR->isAffine()) {
12796       // This couldn't be folded because the operand didn't have the nsw
12797       // flag. Add the nssw flag as an assumption that we could make.
12798       const SCEV *Step = AR->getStepRecurrence(SE);
12799       Type *Ty = Expr->getType();
12800       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12801         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12802                                 SE.getSignExtendExpr(Step, Ty), L,
12803                                 AR->getNoWrapFlags());
12804     }
12805     return SE.getSignExtendExpr(Operand, Expr->getType());
12806   }
12807 
12808 private:
12809   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12810                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12811                         SCEVUnionPredicate *Pred)
12812       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12813 
12814   bool addOverflowAssumption(const SCEVPredicate *P) {
12815     if (!NewPreds) {
12816       // Check if we've already made this assumption.
12817       return Pred && Pred->implies(P);
12818     }
12819     NewPreds->insert(P);
12820     return true;
12821   }
12822 
12823   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12824                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12825     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12826     return addOverflowAssumption(A);
12827   }
12828 
12829   // If \p Expr represents a PHINode, we try to see if it can be represented
12830   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12831   // to add this predicate as a runtime overflow check, we return the AddRec.
12832   // If \p Expr does not meet these conditions (is not a PHI node, or we
12833   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12834   // return \p Expr.
12835   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12836     if (!isa<PHINode>(Expr->getValue()))
12837       return Expr;
12838     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12839     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12840     if (!PredicatedRewrite)
12841       return Expr;
12842     for (auto *P : PredicatedRewrite->second){
12843       // Wrap predicates from outer loops are not supported.
12844       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12845         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12846         if (L != AR->getLoop())
12847           return Expr;
12848       }
12849       if (!addOverflowAssumption(P))
12850         return Expr;
12851     }
12852     return PredicatedRewrite->first;
12853   }
12854 
12855   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12856   SCEVUnionPredicate *Pred;
12857   const Loop *L;
12858 };
12859 
12860 } // end anonymous namespace
12861 
12862 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12863                                                    SCEVUnionPredicate &Preds) {
12864   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12865 }
12866 
12867 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12868     const SCEV *S, const Loop *L,
12869     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12870   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12871   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12872   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12873 
12874   if (!AddRec)
12875     return nullptr;
12876 
12877   // Since the transformation was successful, we can now transfer the SCEV
12878   // predicates.
12879   for (auto *P : TransformPreds)
12880     Preds.insert(P);
12881 
12882   return AddRec;
12883 }
12884 
12885 /// SCEV predicates
12886 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12887                              SCEVPredicateKind Kind)
12888     : FastID(ID), Kind(Kind) {}
12889 
12890 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12891                                        const SCEV *LHS, const SCEV *RHS)
12892     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12893   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12894   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12895 }
12896 
12897 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12898   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12899 
12900   if (!Op)
12901     return false;
12902 
12903   return Op->LHS == LHS && Op->RHS == RHS;
12904 }
12905 
12906 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12907 
12908 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12909 
12910 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12911   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12912 }
12913 
12914 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12915                                      const SCEVAddRecExpr *AR,
12916                                      IncrementWrapFlags Flags)
12917     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12918 
12919 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12920 
12921 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12922   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12923 
12924   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12925 }
12926 
12927 bool SCEVWrapPredicate::isAlwaysTrue() const {
12928   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12929   IncrementWrapFlags IFlags = Flags;
12930 
12931   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12932     IFlags = clearFlags(IFlags, IncrementNSSW);
12933 
12934   return IFlags == IncrementAnyWrap;
12935 }
12936 
12937 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12938   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12939   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12940     OS << "<nusw>";
12941   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12942     OS << "<nssw>";
12943   OS << "\n";
12944 }
12945 
12946 SCEVWrapPredicate::IncrementWrapFlags
12947 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12948                                    ScalarEvolution &SE) {
12949   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12950   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12951 
12952   // We can safely transfer the NSW flag as NSSW.
12953   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12954     ImpliedFlags = IncrementNSSW;
12955 
12956   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12957     // If the increment is positive, the SCEV NUW flag will also imply the
12958     // WrapPredicate NUSW flag.
12959     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12960       if (Step->getValue()->getValue().isNonNegative())
12961         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12962   }
12963 
12964   return ImpliedFlags;
12965 }
12966 
12967 /// Union predicates don't get cached so create a dummy set ID for it.
12968 SCEVUnionPredicate::SCEVUnionPredicate()
12969     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12970 
12971 bool SCEVUnionPredicate::isAlwaysTrue() const {
12972   return all_of(Preds,
12973                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12974 }
12975 
12976 ArrayRef<const SCEVPredicate *>
12977 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12978   auto I = SCEVToPreds.find(Expr);
12979   if (I == SCEVToPreds.end())
12980     return ArrayRef<const SCEVPredicate *>();
12981   return I->second;
12982 }
12983 
12984 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12985   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12986     return all_of(Set->Preds,
12987                   [this](const SCEVPredicate *I) { return this->implies(I); });
12988 
12989   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12990   if (ScevPredsIt == SCEVToPreds.end())
12991     return false;
12992   auto &SCEVPreds = ScevPredsIt->second;
12993 
12994   return any_of(SCEVPreds,
12995                 [N](const SCEVPredicate *I) { return I->implies(N); });
12996 }
12997 
12998 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12999 
13000 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13001   for (auto Pred : Preds)
13002     Pred->print(OS, Depth);
13003 }
13004 
13005 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13006   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13007     for (auto Pred : Set->Preds)
13008       add(Pred);
13009     return;
13010   }
13011 
13012   if (implies(N))
13013     return;
13014 
13015   const SCEV *Key = N->getExpr();
13016   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13017                 " associated expression!");
13018 
13019   SCEVToPreds[Key].push_back(N);
13020   Preds.push_back(N);
13021 }
13022 
13023 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13024                                                      Loop &L)
13025     : SE(SE), L(L) {}
13026 
13027 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13028   const SCEV *Expr = SE.getSCEV(V);
13029   RewriteEntry &Entry = RewriteMap[Expr];
13030 
13031   // If we already have an entry and the version matches, return it.
13032   if (Entry.second && Generation == Entry.first)
13033     return Entry.second;
13034 
13035   // We found an entry but it's stale. Rewrite the stale entry
13036   // according to the current predicate.
13037   if (Entry.second)
13038     Expr = Entry.second;
13039 
13040   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13041   Entry = {Generation, NewSCEV};
13042 
13043   return NewSCEV;
13044 }
13045 
13046 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13047   if (!BackedgeCount) {
13048     SCEVUnionPredicate BackedgePred;
13049     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13050     addPredicate(BackedgePred);
13051   }
13052   return BackedgeCount;
13053 }
13054 
13055 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13056   if (Preds.implies(&Pred))
13057     return;
13058   Preds.add(&Pred);
13059   updateGeneration();
13060 }
13061 
13062 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13063   return Preds;
13064 }
13065 
13066 void PredicatedScalarEvolution::updateGeneration() {
13067   // If the generation number wrapped recompute everything.
13068   if (++Generation == 0) {
13069     for (auto &II : RewriteMap) {
13070       const SCEV *Rewritten = II.second.second;
13071       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13072     }
13073   }
13074 }
13075 
13076 void PredicatedScalarEvolution::setNoOverflow(
13077     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13078   const SCEV *Expr = getSCEV(V);
13079   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13080 
13081   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13082 
13083   // Clear the statically implied flags.
13084   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13085   addPredicate(*SE.getWrapPredicate(AR, Flags));
13086 
13087   auto II = FlagsMap.insert({V, Flags});
13088   if (!II.second)
13089     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13090 }
13091 
13092 bool PredicatedScalarEvolution::hasNoOverflow(
13093     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13094   const SCEV *Expr = getSCEV(V);
13095   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13096 
13097   Flags = SCEVWrapPredicate::clearFlags(
13098       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13099 
13100   auto II = FlagsMap.find(V);
13101 
13102   if (II != FlagsMap.end())
13103     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13104 
13105   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13106 }
13107 
13108 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13109   const SCEV *Expr = this->getSCEV(V);
13110   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13111   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13112 
13113   if (!New)
13114     return nullptr;
13115 
13116   for (auto *P : NewPreds)
13117     Preds.add(P);
13118 
13119   updateGeneration();
13120   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13121   return New;
13122 }
13123 
13124 PredicatedScalarEvolution::PredicatedScalarEvolution(
13125     const PredicatedScalarEvolution &Init)
13126     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13127       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13128   for (auto I : Init.FlagsMap)
13129     FlagsMap.insert(I);
13130 }
13131 
13132 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13133   // For each block.
13134   for (auto *BB : L.getBlocks())
13135     for (auto &I : *BB) {
13136       if (!SE.isSCEVable(I.getType()))
13137         continue;
13138 
13139       auto *Expr = SE.getSCEV(&I);
13140       auto II = RewriteMap.find(Expr);
13141 
13142       if (II == RewriteMap.end())
13143         continue;
13144 
13145       // Don't print things that are not interesting.
13146       if (II->second.second == Expr)
13147         continue;
13148 
13149       OS.indent(Depth) << "[PSE]" << I << ":\n";
13150       OS.indent(Depth + 2) << *Expr << "\n";
13151       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13152     }
13153 }
13154 
13155 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13156 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13157 // for URem with constant power-of-2 second operands.
13158 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13159 // 4, A / B becomes X / 8).
13160 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13161                                 const SCEV *&RHS) {
13162   // Try to match 'zext (trunc A to iB) to iY', which is used
13163   // for URem with constant power-of-2 second operands. Make sure the size of
13164   // the operand A matches the size of the whole expressions.
13165   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13166     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13167       LHS = Trunc->getOperand();
13168       // Bail out if the type of the LHS is larger than the type of the
13169       // expression for now.
13170       if (getTypeSizeInBits(LHS->getType()) >
13171           getTypeSizeInBits(Expr->getType()))
13172         return false;
13173       if (LHS->getType() != Expr->getType())
13174         LHS = getZeroExtendExpr(LHS, Expr->getType());
13175       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13176                         << getTypeSizeInBits(Trunc->getType()));
13177       return true;
13178     }
13179   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13180   if (Add == nullptr || Add->getNumOperands() != 2)
13181     return false;
13182 
13183   const SCEV *A = Add->getOperand(1);
13184   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13185 
13186   if (Mul == nullptr)
13187     return false;
13188 
13189   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13190     // (SomeExpr + (-(SomeExpr / B) * B)).
13191     if (Expr == getURemExpr(A, B)) {
13192       LHS = A;
13193       RHS = B;
13194       return true;
13195     }
13196     return false;
13197   };
13198 
13199   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13200   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13201     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13202            MatchURemWithDivisor(Mul->getOperand(2));
13203 
13204   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13205   if (Mul->getNumOperands() == 2)
13206     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13207            MatchURemWithDivisor(Mul->getOperand(0)) ||
13208            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13209            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13210   return false;
13211 }
13212 
13213 const SCEV *
13214 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13215   SmallVector<BasicBlock*, 16> ExitingBlocks;
13216   L->getExitingBlocks(ExitingBlocks);
13217 
13218   // Form an expression for the maximum exit count possible for this loop. We
13219   // merge the max and exact information to approximate a version of
13220   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13221   SmallVector<const SCEV*, 4> ExitCounts;
13222   for (BasicBlock *ExitingBB : ExitingBlocks) {
13223     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13224     if (isa<SCEVCouldNotCompute>(ExitCount))
13225       ExitCount = getExitCount(L, ExitingBB,
13226                                   ScalarEvolution::ConstantMaximum);
13227     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13228       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13229              "We should only have known counts for exiting blocks that "
13230              "dominate latch!");
13231       ExitCounts.push_back(ExitCount);
13232     }
13233   }
13234   if (ExitCounts.empty())
13235     return getCouldNotCompute();
13236   return getUMinFromMismatchedTypes(ExitCounts);
13237 }
13238 
13239 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13240 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13241 /// we cannot guarantee that the replacement is loop invariant in the loop of
13242 /// the AddRec.
13243 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13244   ValueToSCEVMapTy &Map;
13245 
13246 public:
13247   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13248       : SCEVRewriteVisitor(SE), Map(M) {}
13249 
13250   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13251 
13252   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13253     auto I = Map.find(Expr->getValue());
13254     if (I == Map.end())
13255       return Expr;
13256     return I->second;
13257   }
13258 };
13259 
13260 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13261   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13262                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13263     // If we have LHS == 0, check if LHS is computing a property of some unknown
13264     // SCEV %v which we can rewrite %v to express explicitly.
13265     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13266     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13267         RHSC->getValue()->isNullValue()) {
13268       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13269       // explicitly express that.
13270       const SCEV *URemLHS = nullptr;
13271       const SCEV *URemRHS = nullptr;
13272       if (matchURem(LHS, URemLHS, URemRHS)) {
13273         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13274           Value *V = LHSUnknown->getValue();
13275           auto Multiple =
13276               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13277                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13278           RewriteMap[V] = Multiple;
13279           return;
13280         }
13281       }
13282     }
13283 
13284     if (!isa<SCEVUnknown>(LHS)) {
13285       std::swap(LHS, RHS);
13286       Predicate = CmpInst::getSwappedPredicate(Predicate);
13287     }
13288 
13289     // For now, limit to conditions that provide information about unknown
13290     // expressions.
13291     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13292     if (!LHSUnknown)
13293       return;
13294 
13295     // TODO: use information from more predicates.
13296     switch (Predicate) {
13297     case CmpInst::ICMP_ULT: {
13298       if (!containsAddRecurrence(RHS)) {
13299         const SCEV *Base = LHS;
13300         auto I = RewriteMap.find(LHSUnknown->getValue());
13301         if (I != RewriteMap.end())
13302           Base = I->second;
13303 
13304         RewriteMap[LHSUnknown->getValue()] =
13305             getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13306       }
13307       break;
13308     }
13309     case CmpInst::ICMP_ULE: {
13310       if (!containsAddRecurrence(RHS)) {
13311         const SCEV *Base = LHS;
13312         auto I = RewriteMap.find(LHSUnknown->getValue());
13313         if (I != RewriteMap.end())
13314           Base = I->second;
13315         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13316       }
13317       break;
13318     }
13319     case CmpInst::ICMP_EQ:
13320       if (isa<SCEVConstant>(RHS))
13321         RewriteMap[LHSUnknown->getValue()] = RHS;
13322       break;
13323     case CmpInst::ICMP_NE:
13324       if (isa<SCEVConstant>(RHS) &&
13325           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13326         RewriteMap[LHSUnknown->getValue()] =
13327             getUMaxExpr(LHS, getOne(RHS->getType()));
13328       break;
13329     default:
13330       break;
13331     }
13332   };
13333   // Starting at the loop predecessor, climb up the predecessor chain, as long
13334   // as there are predecessors that can be found that have unique successors
13335   // leading to the original header.
13336   // TODO: share this logic with isLoopEntryGuardedByCond.
13337   ValueToSCEVMapTy RewriteMap;
13338   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13339            L->getLoopPredecessor(), L->getHeader());
13340        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13341 
13342     const BranchInst *LoopEntryPredicate =
13343         dyn_cast<BranchInst>(Pair.first->getTerminator());
13344     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13345       continue;
13346 
13347     // TODO: use information from more complex conditions, e.g. AND expressions.
13348     auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13349     if (!Cmp)
13350       continue;
13351 
13352     auto Predicate = Cmp->getPredicate();
13353     if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13354       Predicate = CmpInst::getInversePredicate(Predicate);
13355     CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13356                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13357   }
13358 
13359   // Also collect information from assumptions dominating the loop.
13360   for (auto &AssumeVH : AC.assumptions()) {
13361     if (!AssumeVH)
13362       continue;
13363     auto *AssumeI = cast<CallInst>(AssumeVH);
13364     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13365     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13366       continue;
13367     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13368                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13369   }
13370 
13371   if (RewriteMap.empty())
13372     return Expr;
13373   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13374   return Rewriter.visit(Expr);
13375 }
13376